• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
1208 	if ((common->cmnd[1] & ~0x02) != 0 ||	/* Mask away MSF */
1209 			start_track > 1) {
1210 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1211 		return -EINVAL;
1212 	}
1213 
1214 	memset(buf, 0, 20);
1215 	buf[1] = (20-2);		/* TOC data length */
1216 	buf[2] = 1;			/* First track number */
1217 	buf[3] = 1;			/* Last track number */
1218 	buf[5] = 0x16;			/* Data track, copying allowed */
1219 	buf[6] = 0x01;			/* Only track is number 1 */
1220 	store_cdrom_address(&buf[8], msf, 0);
1221 
1222 	buf[13] = 0x16;			/* Lead-out track is data */
1223 	buf[14] = 0xAA;			/* Lead-out track number */
1224 	store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1225 	return 20;
1226 }
1227 
do_mode_sense(struct fsg_common * common,struct fsg_buffhd * bh)1228 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1229 {
1230 	struct fsg_lun	*curlun = common->curlun;
1231 	int		mscmnd = common->cmnd[0];
1232 	u8		*buf = (u8 *) bh->buf;
1233 	u8		*buf0 = buf;
1234 	int		pc, page_code;
1235 	int		changeable_values, all_pages;
1236 	int		valid_page = 0;
1237 	int		len, limit;
1238 
1239 	if ((common->cmnd[1] & ~0x08) != 0) {	/* Mask away DBD */
1240 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1241 		return -EINVAL;
1242 	}
1243 	pc = common->cmnd[2] >> 6;
1244 	page_code = common->cmnd[2] & 0x3f;
1245 	if (pc == 3) {
1246 		curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1247 		return -EINVAL;
1248 	}
1249 	changeable_values = (pc == 1);
1250 	all_pages = (page_code == 0x3f);
1251 
1252 	/*
1253 	 * Write the mode parameter header.  Fixed values are: default
1254 	 * medium type, no cache control (DPOFUA), and no block descriptors.
1255 	 * The only variable value is the WriteProtect bit.  We will fill in
1256 	 * the mode data length later.
1257 	 */
1258 	memset(buf, 0, 8);
1259 	if (mscmnd == MODE_SENSE) {
1260 		buf[2] = (curlun->ro ? 0x80 : 0x00);		/* WP, DPOFUA */
1261 		buf += 4;
1262 		limit = 255;
1263 	} else {			/* MODE_SENSE_10 */
1264 		buf[3] = (curlun->ro ? 0x80 : 0x00);		/* WP, DPOFUA */
1265 		buf += 8;
1266 		limit = 65535;		/* Should really be FSG_BUFLEN */
1267 	}
1268 
1269 	/* No block descriptors */
1270 
1271 	/*
1272 	 * The mode pages, in numerical order.  The only page we support
1273 	 * is the Caching page.
1274 	 */
1275 	if (page_code == 0x08 || all_pages) {
1276 		valid_page = 1;
1277 		buf[0] = 0x08;		/* Page code */
1278 		buf[1] = 10;		/* Page length */
1279 		memset(buf+2, 0, 10);	/* None of the fields are changeable */
1280 
1281 		if (!changeable_values) {
1282 			buf[2] = 0x04;	/* Write cache enable, */
1283 					/* Read cache not disabled */
1284 					/* No cache retention priorities */
1285 			put_unaligned_be16(0xffff, &buf[4]);
1286 					/* Don't disable prefetch */
1287 					/* Minimum prefetch = 0 */
1288 			put_unaligned_be16(0xffff, &buf[8]);
1289 					/* Maximum prefetch */
1290 			put_unaligned_be16(0xffff, &buf[10]);
1291 					/* Maximum prefetch ceiling */
1292 		}
1293 		buf += 12;
1294 	}
1295 
1296 	/*
1297 	 * Check that a valid page was requested and the mode data length
1298 	 * isn't too long.
1299 	 */
1300 	len = buf - buf0;
1301 	if (!valid_page || len > limit) {
1302 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1303 		return -EINVAL;
1304 	}
1305 
1306 	/*  Store the mode data length */
1307 	if (mscmnd == MODE_SENSE)
1308 		buf0[0] = len - 1;
1309 	else
1310 		put_unaligned_be16(len - 2, buf0);
1311 	return len;
1312 }
1313 
do_start_stop(struct fsg_common * common)1314 static int do_start_stop(struct fsg_common *common)
1315 {
1316 	struct fsg_lun	*curlun = common->curlun;
1317 	int		loej, start;
1318 
1319 	if (!curlun) {
1320 		return -EINVAL;
1321 	} else if (!curlun->removable) {
1322 		curlun->sense_data = SS_INVALID_COMMAND;
1323 		return -EINVAL;
1324 	} else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1325 		   (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1326 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1327 		return -EINVAL;
1328 	}
1329 
1330 	loej  = common->cmnd[4] & 0x02;
1331 	start = common->cmnd[4] & 0x01;
1332 
1333 	/*
1334 	 * Our emulation doesn't support mounting; the medium is
1335 	 * available for use as soon as it is loaded.
1336 	 */
1337 	if (start) {
1338 		if (!fsg_lun_is_open(curlun)) {
1339 			curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1340 			return -EINVAL;
1341 		}
1342 		return 0;
1343 	}
1344 
1345 	/* Are we allowed to unload the media? */
1346 	if (curlun->prevent_medium_removal) {
1347 		LDBG(curlun, "unload attempt prevented\n");
1348 		curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1349 		return -EINVAL;
1350 	}
1351 
1352 	if (!loej)
1353 		return 0;
1354 
1355 	up_read(&common->filesem);
1356 	down_write(&common->filesem);
1357 	fsg_lun_close(curlun);
1358 	up_write(&common->filesem);
1359 	down_read(&common->filesem);
1360 
1361 	return 0;
1362 }
1363 
do_prevent_allow(struct fsg_common * common)1364 static int do_prevent_allow(struct fsg_common *common)
1365 {
1366 	struct fsg_lun	*curlun = common->curlun;
1367 	int		prevent;
1368 
1369 	if (!common->curlun) {
1370 		return -EINVAL;
1371 	} else if (!common->curlun->removable) {
1372 		common->curlun->sense_data = SS_INVALID_COMMAND;
1373 		return -EINVAL;
1374 	}
1375 
1376 	prevent = common->cmnd[4] & 0x01;
1377 	if ((common->cmnd[4] & ~0x01) != 0) {	/* Mask away Prevent */
1378 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1379 		return -EINVAL;
1380 	}
1381 
1382 	if (curlun->prevent_medium_removal && !prevent)
1383 		fsg_lun_fsync_sub(curlun);
1384 	curlun->prevent_medium_removal = prevent;
1385 	return 0;
1386 }
1387 
do_read_format_capacities(struct fsg_common * common,struct fsg_buffhd * bh)1388 static int do_read_format_capacities(struct fsg_common *common,
1389 			struct fsg_buffhd *bh)
1390 {
1391 	struct fsg_lun	*curlun = common->curlun;
1392 	u8		*buf = (u8 *) bh->buf;
1393 
1394 	buf[0] = buf[1] = buf[2] = 0;
1395 	buf[3] = 8;	/* Only the Current/Maximum Capacity Descriptor */
1396 	buf += 4;
1397 
1398 	put_unaligned_be32(curlun->num_sectors, &buf[0]);
1399 						/* Number of blocks */
1400 	put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */
1401 	buf[4] = 0x02;				/* Current capacity */
1402 	return 12;
1403 }
1404 
do_mode_select(struct fsg_common * common,struct fsg_buffhd * bh)1405 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1406 {
1407 	struct fsg_lun	*curlun = common->curlun;
1408 
1409 	/* We don't support MODE SELECT */
1410 	if (curlun)
1411 		curlun->sense_data = SS_INVALID_COMMAND;
1412 	return -EINVAL;
1413 }
1414 
1415 
1416 /*-------------------------------------------------------------------------*/
1417 
halt_bulk_in_endpoint(struct fsg_dev * fsg)1418 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1419 {
1420 	int	rc;
1421 
1422 	rc = fsg_set_halt(fsg, fsg->bulk_in);
1423 	if (rc == -EAGAIN)
1424 		VDBG(fsg, "delayed bulk-in endpoint halt\n");
1425 	while (rc != 0) {
1426 		if (rc != -EAGAIN) {
1427 			WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1428 			rc = 0;
1429 			break;
1430 		}
1431 
1432 		/* Wait for a short time and then try again */
1433 		if (msleep_interruptible(100) != 0)
1434 			return -EINTR;
1435 		rc = usb_ep_set_halt(fsg->bulk_in);
1436 	}
1437 	return rc;
1438 }
1439 
wedge_bulk_in_endpoint(struct fsg_dev * fsg)1440 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1441 {
1442 	int	rc;
1443 
1444 	DBG(fsg, "bulk-in set wedge\n");
1445 	rc = usb_ep_set_wedge(fsg->bulk_in);
1446 	if (rc == -EAGAIN)
1447 		VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1448 	while (rc != 0) {
1449 		if (rc != -EAGAIN) {
1450 			WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1451 			rc = 0;
1452 			break;
1453 		}
1454 
1455 		/* Wait for a short time and then try again */
1456 		if (msleep_interruptible(100) != 0)
1457 			return -EINTR;
1458 		rc = usb_ep_set_wedge(fsg->bulk_in);
1459 	}
1460 	return rc;
1461 }
1462 
throw_away_data(struct fsg_common * common)1463 static int throw_away_data(struct fsg_common *common)
1464 {
1465 	struct fsg_buffhd	*bh, *bh2;
1466 	u32			amount;
1467 	int			rc;
1468 
1469 	for (bh = common->next_buffhd_to_drain;
1470 	     bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1471 	     bh = common->next_buffhd_to_drain) {
1472 
1473 		/* Try to submit another request if we need one */
1474 		bh2 = common->next_buffhd_to_fill;
1475 		if (bh2->state == BUF_STATE_EMPTY &&
1476 				common->usb_amount_left > 0) {
1477 			amount = min(common->usb_amount_left, FSG_BUFLEN);
1478 
1479 			/*
1480 			 * Except at the end of the transfer, amount will be
1481 			 * equal to the buffer size, which is divisible by
1482 			 * the bulk-out maxpacket size.
1483 			 */
1484 			set_bulk_out_req_length(common, bh2, amount);
1485 			if (!start_out_transfer(common, bh2))
1486 				/* Dunno what to do if common->fsg is NULL */
1487 				return -EIO;
1488 			common->next_buffhd_to_fill = bh2->next;
1489 			common->usb_amount_left -= amount;
1490 			continue;
1491 		}
1492 
1493 		/* Wait for the data to be received */
1494 		rc = sleep_thread(common, false, bh);
1495 		if (rc)
1496 			return rc;
1497 
1498 		/* Throw away the data in a filled buffer */
1499 		bh->state = BUF_STATE_EMPTY;
1500 		common->next_buffhd_to_drain = bh->next;
1501 
1502 		/* A short packet or an error ends everything */
1503 		if (bh->outreq->actual < bh->bulk_out_intended_length ||
1504 				bh->outreq->status != 0) {
1505 			raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1506 			return -EINTR;
1507 		}
1508 	}
1509 	return 0;
1510 }
1511 
finish_reply(struct fsg_common * common)1512 static int finish_reply(struct fsg_common *common)
1513 {
1514 	struct fsg_buffhd	*bh = common->next_buffhd_to_fill;
1515 	int			rc = 0;
1516 
1517 	switch (common->data_dir) {
1518 	case DATA_DIR_NONE:
1519 		break;			/* Nothing to send */
1520 
1521 	/*
1522 	 * If we don't know whether the host wants to read or write,
1523 	 * this must be CB or CBI with an unknown command.  We mustn't
1524 	 * try to send or receive any data.  So stall both bulk pipes
1525 	 * if we can and wait for a reset.
1526 	 */
1527 	case DATA_DIR_UNKNOWN:
1528 		if (!common->can_stall) {
1529 			/* Nothing */
1530 		} else if (fsg_is_set(common)) {
1531 			fsg_set_halt(common->fsg, common->fsg->bulk_out);
1532 			rc = halt_bulk_in_endpoint(common->fsg);
1533 		} else {
1534 			/* Don't know what to do if common->fsg is NULL */
1535 			rc = -EIO;
1536 		}
1537 		break;
1538 
1539 	/* All but the last buffer of data must have already been sent */
1540 	case DATA_DIR_TO_HOST:
1541 		if (common->data_size == 0) {
1542 			/* Nothing to send */
1543 
1544 		/* Don't know what to do if common->fsg is NULL */
1545 		} else if (!fsg_is_set(common)) {
1546 			rc = -EIO;
1547 
1548 		/* If there's no residue, simply send the last buffer */
1549 		} else if (common->residue == 0) {
1550 			bh->inreq->zero = 0;
1551 			if (!start_in_transfer(common, bh))
1552 				return -EIO;
1553 			common->next_buffhd_to_fill = bh->next;
1554 
1555 		/*
1556 		 * For Bulk-only, mark the end of the data with a short
1557 		 * packet.  If we are allowed to stall, halt the bulk-in
1558 		 * endpoint.  (Note: This violates the Bulk-Only Transport
1559 		 * specification, which requires us to pad the data if we
1560 		 * don't halt the endpoint.  Presumably nobody will mind.)
1561 		 */
1562 		} else {
1563 			bh->inreq->zero = 1;
1564 			if (!start_in_transfer(common, bh))
1565 				rc = -EIO;
1566 			common->next_buffhd_to_fill = bh->next;
1567 			if (common->can_stall)
1568 				rc = halt_bulk_in_endpoint(common->fsg);
1569 		}
1570 		break;
1571 
1572 	/*
1573 	 * We have processed all we want from the data the host has sent.
1574 	 * There may still be outstanding bulk-out requests.
1575 	 */
1576 	case DATA_DIR_FROM_HOST:
1577 		if (common->residue == 0) {
1578 			/* Nothing to receive */
1579 
1580 		/* Did the host stop sending unexpectedly early? */
1581 		} else if (common->short_packet_received) {
1582 			raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1583 			rc = -EINTR;
1584 
1585 		/*
1586 		 * We haven't processed all the incoming data.  Even though
1587 		 * we may be allowed to stall, doing so would cause a race.
1588 		 * The controller may already have ACK'ed all the remaining
1589 		 * bulk-out packets, in which case the host wouldn't see a
1590 		 * STALL.  Not realizing the endpoint was halted, it wouldn't
1591 		 * clear the halt -- leading to problems later on.
1592 		 */
1593 #if 0
1594 		} else if (common->can_stall) {
1595 			if (fsg_is_set(common))
1596 				fsg_set_halt(common->fsg,
1597 					     common->fsg->bulk_out);
1598 			raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1599 			rc = -EINTR;
1600 #endif
1601 
1602 		/*
1603 		 * We can't stall.  Read in the excess data and throw it
1604 		 * all away.
1605 		 */
1606 		} else {
1607 			rc = throw_away_data(common);
1608 		}
1609 		break;
1610 	}
1611 	return rc;
1612 }
1613 
send_status(struct fsg_common * common)1614 static void send_status(struct fsg_common *common)
1615 {
1616 	struct fsg_lun		*curlun = common->curlun;
1617 	struct fsg_buffhd	*bh;
1618 	struct bulk_cs_wrap	*csw;
1619 	int			rc;
1620 	u8			status = US_BULK_STAT_OK;
1621 	u32			sd, sdinfo = 0;
1622 
1623 	/* Wait for the next buffer to become available */
1624 	bh = common->next_buffhd_to_fill;
1625 	rc = sleep_thread(common, false, bh);
1626 	if (rc)
1627 		return;
1628 
1629 	if (curlun) {
1630 		sd = curlun->sense_data;
1631 		sdinfo = curlun->sense_data_info;
1632 	} else if (common->bad_lun_okay)
1633 		sd = SS_NO_SENSE;
1634 	else
1635 		sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1636 
1637 	if (common->phase_error) {
1638 		DBG(common, "sending phase-error status\n");
1639 		status = US_BULK_STAT_PHASE;
1640 		sd = SS_INVALID_COMMAND;
1641 	} else if (sd != SS_NO_SENSE) {
1642 		DBG(common, "sending command-failure status\n");
1643 		status = US_BULK_STAT_FAIL;
1644 		VDBG(common, "  sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1645 				"  info x%x\n",
1646 				SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1647 	}
1648 
1649 	/* Store and send the Bulk-only CSW */
1650 	csw = (void *)bh->buf;
1651 
1652 	csw->Signature = cpu_to_le32(US_BULK_CS_SIGN);
1653 	csw->Tag = common->tag;
1654 	csw->Residue = cpu_to_le32(common->residue);
1655 	csw->Status = status;
1656 
1657 	bh->inreq->length = US_BULK_CS_WRAP_LEN;
1658 	bh->inreq->zero = 0;
1659 	if (!start_in_transfer(common, bh))
1660 		/* Don't know what to do if common->fsg is NULL */
1661 		return;
1662 
1663 	common->next_buffhd_to_fill = bh->next;
1664 	return;
1665 }
1666 
1667 
1668 /*-------------------------------------------------------------------------*/
1669 
1670 /*
1671  * Check whether the command is properly formed and whether its data size
1672  * and direction agree with the values we already have.
1673  */
check_command(struct fsg_common * common,int cmnd_size,enum data_direction data_dir,unsigned int mask,int needs_medium,const char * name)1674 static int check_command(struct fsg_common *common, int cmnd_size,
1675 			 enum data_direction data_dir, unsigned int mask,
1676 			 int needs_medium, const char *name)
1677 {
1678 	int			i;
1679 	unsigned int		lun = common->cmnd[1] >> 5;
1680 	static const char	dirletter[4] = {'u', 'o', 'i', 'n'};
1681 	char			hdlen[20];
1682 	struct fsg_lun		*curlun;
1683 
1684 	hdlen[0] = 0;
1685 	if (common->data_dir != DATA_DIR_UNKNOWN)
1686 		sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1687 			common->data_size);
1688 	VDBG(common, "SCSI command: %s;  Dc=%d, D%c=%u;  Hc=%d%s\n",
1689 	     name, cmnd_size, dirletter[(int) data_dir],
1690 	     common->data_size_from_cmnd, common->cmnd_size, hdlen);
1691 
1692 	/*
1693 	 * We can't reply at all until we know the correct data direction
1694 	 * and size.
1695 	 */
1696 	if (common->data_size_from_cmnd == 0)
1697 		data_dir = DATA_DIR_NONE;
1698 	if (common->data_size < common->data_size_from_cmnd) {
1699 		/*
1700 		 * Host data size < Device data size is a phase error.
1701 		 * Carry out the command, but only transfer as much as
1702 		 * we are allowed.
1703 		 */
1704 		common->data_size_from_cmnd = common->data_size;
1705 		common->phase_error = 1;
1706 	}
1707 	common->residue = common->data_size;
1708 	common->usb_amount_left = common->data_size;
1709 
1710 	/* Conflicting data directions is a phase error */
1711 	if (common->data_dir != data_dir && common->data_size_from_cmnd > 0) {
1712 		common->phase_error = 1;
1713 		return -EINVAL;
1714 	}
1715 
1716 	/* Verify the length of the command itself */
1717 	if (cmnd_size != common->cmnd_size) {
1718 
1719 		/*
1720 		 * Special case workaround: There are plenty of buggy SCSI
1721 		 * implementations. Many have issues with cbw->Length
1722 		 * field passing a wrong command size. For those cases we
1723 		 * always try to work around the problem by using the length
1724 		 * sent by the host side provided it is at least as large
1725 		 * as the correct command length.
1726 		 * Examples of such cases would be MS-Windows, which issues
1727 		 * REQUEST SENSE with cbw->Length == 12 where it should
1728 		 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1729 		 * REQUEST SENSE with cbw->Length == 10 where it should
1730 		 * be 6 as well.
1731 		 */
1732 		if (cmnd_size <= common->cmnd_size) {
1733 			DBG(common, "%s is buggy! Expected length %d "
1734 			    "but we got %d\n", name,
1735 			    cmnd_size, common->cmnd_size);
1736 			cmnd_size = common->cmnd_size;
1737 		} else {
1738 			common->phase_error = 1;
1739 			return -EINVAL;
1740 		}
1741 	}
1742 
1743 	/* Check that the LUN values are consistent */
1744 	if (common->lun != lun)
1745 		DBG(common, "using LUN %u from CBW, not LUN %u from CDB\n",
1746 		    common->lun, lun);
1747 
1748 	/* Check the LUN */
1749 	curlun = common->curlun;
1750 	if (curlun) {
1751 		if (common->cmnd[0] != REQUEST_SENSE) {
1752 			curlun->sense_data = SS_NO_SENSE;
1753 			curlun->sense_data_info = 0;
1754 			curlun->info_valid = 0;
1755 		}
1756 	} else {
1757 		common->bad_lun_okay = 0;
1758 
1759 		/*
1760 		 * INQUIRY and REQUEST SENSE commands are explicitly allowed
1761 		 * to use unsupported LUNs; all others may not.
1762 		 */
1763 		if (common->cmnd[0] != INQUIRY &&
1764 		    common->cmnd[0] != REQUEST_SENSE) {
1765 			DBG(common, "unsupported LUN %u\n", common->lun);
1766 			return -EINVAL;
1767 		}
1768 	}
1769 
1770 	/*
1771 	 * If a unit attention condition exists, only INQUIRY and
1772 	 * REQUEST SENSE commands are allowed; anything else must fail.
1773 	 */
1774 	if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1775 	    common->cmnd[0] != INQUIRY &&
1776 	    common->cmnd[0] != REQUEST_SENSE) {
1777 		curlun->sense_data = curlun->unit_attention_data;
1778 		curlun->unit_attention_data = SS_NO_SENSE;
1779 		return -EINVAL;
1780 	}
1781 
1782 	/* Check that only command bytes listed in the mask are non-zero */
1783 	common->cmnd[1] &= 0x1f;			/* Mask away the LUN */
1784 	for (i = 1; i < cmnd_size; ++i) {
1785 		if (common->cmnd[i] && !(mask & (1 << i))) {
1786 			if (curlun)
1787 				curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1788 			return -EINVAL;
1789 		}
1790 	}
1791 
1792 	/* If the medium isn't mounted and the command needs to access
1793 	 * it, return an error. */
1794 	if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1795 		curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1796 		return -EINVAL;
1797 	}
1798 
1799 	return 0;
1800 }
1801 
1802 /* 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)1803 static int check_command_size_in_blocks(struct fsg_common *common,
1804 		int cmnd_size, enum data_direction data_dir,
1805 		unsigned int mask, int needs_medium, const char *name)
1806 {
1807 	if (common->curlun)
1808 		common->data_size_from_cmnd <<= common->curlun->blkbits;
1809 	return check_command(common, cmnd_size, data_dir,
1810 			mask, needs_medium, name);
1811 }
1812 
do_scsi_command(struct fsg_common * common)1813 static int do_scsi_command(struct fsg_common *common)
1814 {
1815 	struct fsg_buffhd	*bh;
1816 	int			rc;
1817 	int			reply = -EINVAL;
1818 	int			i;
1819 	static char		unknown[16];
1820 
1821 	dump_cdb(common);
1822 
1823 	/* Wait for the next buffer to become available for data or status */
1824 	bh = common->next_buffhd_to_fill;
1825 	common->next_buffhd_to_drain = bh;
1826 	rc = sleep_thread(common, false, bh);
1827 	if (rc)
1828 		return rc;
1829 
1830 	common->phase_error = 0;
1831 	common->short_packet_received = 0;
1832 
1833 	down_read(&common->filesem);	/* We're using the backing file */
1834 	switch (common->cmnd[0]) {
1835 
1836 	case INQUIRY:
1837 		common->data_size_from_cmnd = common->cmnd[4];
1838 		reply = check_command(common, 6, DATA_DIR_TO_HOST,
1839 				      (1<<4), 0,
1840 				      "INQUIRY");
1841 		if (reply == 0)
1842 			reply = do_inquiry(common, bh);
1843 		break;
1844 
1845 	case MODE_SELECT:
1846 		common->data_size_from_cmnd = common->cmnd[4];
1847 		reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1848 				      (1<<1) | (1<<4), 0,
1849 				      "MODE SELECT(6)");
1850 		if (reply == 0)
1851 			reply = do_mode_select(common, bh);
1852 		break;
1853 
1854 	case MODE_SELECT_10:
1855 		common->data_size_from_cmnd =
1856 			get_unaligned_be16(&common->cmnd[7]);
1857 		reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1858 				      (1<<1) | (3<<7), 0,
1859 				      "MODE SELECT(10)");
1860 		if (reply == 0)
1861 			reply = do_mode_select(common, bh);
1862 		break;
1863 
1864 	case MODE_SENSE:
1865 		common->data_size_from_cmnd = common->cmnd[4];
1866 		reply = check_command(common, 6, DATA_DIR_TO_HOST,
1867 				      (1<<1) | (1<<2) | (1<<4), 0,
1868 				      "MODE SENSE(6)");
1869 		if (reply == 0)
1870 			reply = do_mode_sense(common, bh);
1871 		break;
1872 
1873 	case MODE_SENSE_10:
1874 		common->data_size_from_cmnd =
1875 			get_unaligned_be16(&common->cmnd[7]);
1876 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1877 				      (1<<1) | (1<<2) | (3<<7), 0,
1878 				      "MODE SENSE(10)");
1879 		if (reply == 0)
1880 			reply = do_mode_sense(common, bh);
1881 		break;
1882 
1883 	case ALLOW_MEDIUM_REMOVAL:
1884 		common->data_size_from_cmnd = 0;
1885 		reply = check_command(common, 6, DATA_DIR_NONE,
1886 				      (1<<4), 0,
1887 				      "PREVENT-ALLOW MEDIUM REMOVAL");
1888 		if (reply == 0)
1889 			reply = do_prevent_allow(common);
1890 		break;
1891 
1892 	case READ_6:
1893 		i = common->cmnd[4];
1894 		common->data_size_from_cmnd = (i == 0) ? 256 : i;
1895 		reply = check_command_size_in_blocks(common, 6,
1896 				      DATA_DIR_TO_HOST,
1897 				      (7<<1) | (1<<4), 1,
1898 				      "READ(6)");
1899 		if (reply == 0)
1900 			reply = do_read(common);
1901 		break;
1902 
1903 	case READ_10:
1904 		common->data_size_from_cmnd =
1905 				get_unaligned_be16(&common->cmnd[7]);
1906 		reply = check_command_size_in_blocks(common, 10,
1907 				      DATA_DIR_TO_HOST,
1908 				      (1<<1) | (0xf<<2) | (3<<7), 1,
1909 				      "READ(10)");
1910 		if (reply == 0)
1911 			reply = do_read(common);
1912 		break;
1913 
1914 	case READ_12:
1915 		common->data_size_from_cmnd =
1916 				get_unaligned_be32(&common->cmnd[6]);
1917 		reply = check_command_size_in_blocks(common, 12,
1918 				      DATA_DIR_TO_HOST,
1919 				      (1<<1) | (0xf<<2) | (0xf<<6), 1,
1920 				      "READ(12)");
1921 		if (reply == 0)
1922 			reply = do_read(common);
1923 		break;
1924 
1925 	case READ_CAPACITY:
1926 		common->data_size_from_cmnd = 8;
1927 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1928 				      (0xf<<2) | (1<<8), 1,
1929 				      "READ CAPACITY");
1930 		if (reply == 0)
1931 			reply = do_read_capacity(common, bh);
1932 		break;
1933 
1934 	case READ_HEADER:
1935 		if (!common->curlun || !common->curlun->cdrom)
1936 			goto unknown_cmnd;
1937 		common->data_size_from_cmnd =
1938 			get_unaligned_be16(&common->cmnd[7]);
1939 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1940 				      (3<<7) | (0x1f<<1), 1,
1941 				      "READ HEADER");
1942 		if (reply == 0)
1943 			reply = do_read_header(common, bh);
1944 		break;
1945 
1946 	case READ_TOC:
1947 		if (!common->curlun || !common->curlun->cdrom)
1948 			goto unknown_cmnd;
1949 		common->data_size_from_cmnd =
1950 			get_unaligned_be16(&common->cmnd[7]);
1951 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1952 				      (7<<6) | (1<<1), 1,
1953 				      "READ TOC");
1954 		if (reply == 0)
1955 			reply = do_read_toc(common, bh);
1956 		break;
1957 
1958 	case READ_FORMAT_CAPACITIES:
1959 		common->data_size_from_cmnd =
1960 			get_unaligned_be16(&common->cmnd[7]);
1961 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1962 				      (3<<7), 1,
1963 				      "READ FORMAT CAPACITIES");
1964 		if (reply == 0)
1965 			reply = do_read_format_capacities(common, bh);
1966 		break;
1967 
1968 	case REQUEST_SENSE:
1969 		common->data_size_from_cmnd = common->cmnd[4];
1970 		reply = check_command(common, 6, DATA_DIR_TO_HOST,
1971 				      (1<<4), 0,
1972 				      "REQUEST SENSE");
1973 		if (reply == 0)
1974 			reply = do_request_sense(common, bh);
1975 		break;
1976 
1977 	case START_STOP:
1978 		common->data_size_from_cmnd = 0;
1979 		reply = check_command(common, 6, DATA_DIR_NONE,
1980 				      (1<<1) | (1<<4), 0,
1981 				      "START-STOP UNIT");
1982 		if (reply == 0)
1983 			reply = do_start_stop(common);
1984 		break;
1985 
1986 	case SYNCHRONIZE_CACHE:
1987 		common->data_size_from_cmnd = 0;
1988 		reply = check_command(common, 10, DATA_DIR_NONE,
1989 				      (0xf<<2) | (3<<7), 1,
1990 				      "SYNCHRONIZE CACHE");
1991 		if (reply == 0)
1992 			reply = do_synchronize_cache(common);
1993 		break;
1994 
1995 	case TEST_UNIT_READY:
1996 		common->data_size_from_cmnd = 0;
1997 		reply = check_command(common, 6, DATA_DIR_NONE,
1998 				0, 1,
1999 				"TEST UNIT READY");
2000 		break;
2001 
2002 	/*
2003 	 * Although optional, this command is used by MS-Windows.  We
2004 	 * support a minimal version: BytChk must be 0.
2005 	 */
2006 	case VERIFY:
2007 		common->data_size_from_cmnd = 0;
2008 		reply = check_command(common, 10, DATA_DIR_NONE,
2009 				      (1<<1) | (0xf<<2) | (3<<7), 1,
2010 				      "VERIFY");
2011 		if (reply == 0)
2012 			reply = do_verify(common);
2013 		break;
2014 
2015 	case WRITE_6:
2016 		i = common->cmnd[4];
2017 		common->data_size_from_cmnd = (i == 0) ? 256 : i;
2018 		reply = check_command_size_in_blocks(common, 6,
2019 				      DATA_DIR_FROM_HOST,
2020 				      (7<<1) | (1<<4), 1,
2021 				      "WRITE(6)");
2022 		if (reply == 0)
2023 			reply = do_write(common);
2024 		break;
2025 
2026 	case WRITE_10:
2027 		common->data_size_from_cmnd =
2028 				get_unaligned_be16(&common->cmnd[7]);
2029 		reply = check_command_size_in_blocks(common, 10,
2030 				      DATA_DIR_FROM_HOST,
2031 				      (1<<1) | (0xf<<2) | (3<<7), 1,
2032 				      "WRITE(10)");
2033 		if (reply == 0)
2034 			reply = do_write(common);
2035 		break;
2036 
2037 	case WRITE_12:
2038 		common->data_size_from_cmnd =
2039 				get_unaligned_be32(&common->cmnd[6]);
2040 		reply = check_command_size_in_blocks(common, 12,
2041 				      DATA_DIR_FROM_HOST,
2042 				      (1<<1) | (0xf<<2) | (0xf<<6), 1,
2043 				      "WRITE(12)");
2044 		if (reply == 0)
2045 			reply = do_write(common);
2046 		break;
2047 
2048 	/*
2049 	 * Some mandatory commands that we recognize but don't implement.
2050 	 * They don't mean much in this setting.  It's left as an exercise
2051 	 * for anyone interested to implement RESERVE and RELEASE in terms
2052 	 * of Posix locks.
2053 	 */
2054 	case FORMAT_UNIT:
2055 	case RELEASE:
2056 	case RESERVE:
2057 	case SEND_DIAGNOSTIC:
2058 
2059 	default:
2060 unknown_cmnd:
2061 		common->data_size_from_cmnd = 0;
2062 		sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2063 		reply = check_command(common, common->cmnd_size,
2064 				      DATA_DIR_UNKNOWN, ~0, 0, unknown);
2065 		if (reply == 0) {
2066 			common->curlun->sense_data = SS_INVALID_COMMAND;
2067 			reply = -EINVAL;
2068 		}
2069 		break;
2070 	}
2071 	up_read(&common->filesem);
2072 
2073 	if (reply == -EINTR || signal_pending(current))
2074 		return -EINTR;
2075 
2076 	/* Set up the single reply buffer for finish_reply() */
2077 	if (reply == -EINVAL)
2078 		reply = 0;		/* Error reply length */
2079 	if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2080 		reply = min((u32)reply, common->data_size_from_cmnd);
2081 		bh->inreq->length = reply;
2082 		bh->state = BUF_STATE_FULL;
2083 		common->residue -= reply;
2084 	}				/* Otherwise it's already set */
2085 
2086 	return 0;
2087 }
2088 
2089 
2090 /*-------------------------------------------------------------------------*/
2091 
received_cbw(struct fsg_dev * fsg,struct fsg_buffhd * bh)2092 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2093 {
2094 	struct usb_request	*req = bh->outreq;
2095 	struct bulk_cb_wrap	*cbw = req->buf;
2096 	struct fsg_common	*common = fsg->common;
2097 
2098 	/* Was this a real packet?  Should it be ignored? */
2099 	if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2100 		return -EINVAL;
2101 
2102 	/* Is the CBW valid? */
2103 	if (req->actual != US_BULK_CB_WRAP_LEN ||
2104 			cbw->Signature != cpu_to_le32(
2105 				US_BULK_CB_SIGN)) {
2106 		DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2107 				req->actual,
2108 				le32_to_cpu(cbw->Signature));
2109 
2110 		/*
2111 		 * The Bulk-only spec says we MUST stall the IN endpoint
2112 		 * (6.6.1), so it's unavoidable.  It also says we must
2113 		 * retain this state until the next reset, but there's
2114 		 * no way to tell the controller driver it should ignore
2115 		 * Clear-Feature(HALT) requests.
2116 		 *
2117 		 * We aren't required to halt the OUT endpoint; instead
2118 		 * we can simply accept and discard any data received
2119 		 * until the next reset.
2120 		 */
2121 		wedge_bulk_in_endpoint(fsg);
2122 		set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2123 		return -EINVAL;
2124 	}
2125 
2126 	/* Is the CBW meaningful? */
2127 	if (cbw->Lun >= ARRAY_SIZE(common->luns) ||
2128 	    cbw->Flags & ~US_BULK_FLAG_IN || cbw->Length <= 0 ||
2129 	    cbw->Length > MAX_COMMAND_SIZE) {
2130 		DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2131 				"cmdlen %u\n",
2132 				cbw->Lun, cbw->Flags, cbw->Length);
2133 
2134 		/*
2135 		 * We can do anything we want here, so let's stall the
2136 		 * bulk pipes if we are allowed to.
2137 		 */
2138 		if (common->can_stall) {
2139 			fsg_set_halt(fsg, fsg->bulk_out);
2140 			halt_bulk_in_endpoint(fsg);
2141 		}
2142 		return -EINVAL;
2143 	}
2144 
2145 	/* Save the command for later */
2146 	common->cmnd_size = cbw->Length;
2147 	memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2148 	if (cbw->Flags & US_BULK_FLAG_IN)
2149 		common->data_dir = DATA_DIR_TO_HOST;
2150 	else
2151 		common->data_dir = DATA_DIR_FROM_HOST;
2152 	common->data_size = le32_to_cpu(cbw->DataTransferLength);
2153 	if (common->data_size == 0)
2154 		common->data_dir = DATA_DIR_NONE;
2155 	common->lun = cbw->Lun;
2156 	if (common->lun < ARRAY_SIZE(common->luns))
2157 		common->curlun = common->luns[common->lun];
2158 	else
2159 		common->curlun = NULL;
2160 	common->tag = cbw->Tag;
2161 	return 0;
2162 }
2163 
get_next_command(struct fsg_common * common)2164 static int get_next_command(struct fsg_common *common)
2165 {
2166 	struct fsg_buffhd	*bh;
2167 	int			rc = 0;
2168 
2169 	/* Wait for the next buffer to become available */
2170 	bh = common->next_buffhd_to_fill;
2171 	rc = sleep_thread(common, true, bh);
2172 	if (rc)
2173 		return rc;
2174 
2175 	/* Queue a request to read a Bulk-only CBW */
2176 	set_bulk_out_req_length(common, bh, US_BULK_CB_WRAP_LEN);
2177 	if (!start_out_transfer(common, bh))
2178 		/* Don't know what to do if common->fsg is NULL */
2179 		return -EIO;
2180 
2181 	/*
2182 	 * We will drain the buffer in software, which means we
2183 	 * can reuse it for the next filling.  No need to advance
2184 	 * next_buffhd_to_fill.
2185 	 */
2186 
2187 	/* Wait for the CBW to arrive */
2188 	rc = sleep_thread(common, true, bh);
2189 	if (rc)
2190 		return rc;
2191 
2192 	rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2193 	bh->state = BUF_STATE_EMPTY;
2194 
2195 	return rc;
2196 }
2197 
2198 
2199 /*-------------------------------------------------------------------------*/
2200 
alloc_request(struct fsg_common * common,struct usb_ep * ep,struct usb_request ** preq)2201 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2202 		struct usb_request **preq)
2203 {
2204 	*preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2205 	if (*preq)
2206 		return 0;
2207 	ERROR(common, "can't allocate request for %s\n", ep->name);
2208 	return -ENOMEM;
2209 }
2210 
2211 /* Reset interface setting and re-init endpoint state (toggle etc). */
do_set_interface(struct fsg_common * common,struct fsg_dev * new_fsg)2212 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2213 {
2214 	struct fsg_dev *fsg;
2215 	int i, rc = 0;
2216 
2217 	if (common->running)
2218 		DBG(common, "reset interface\n");
2219 
2220 reset:
2221 	/* Deallocate the requests */
2222 	if (common->fsg) {
2223 		fsg = common->fsg;
2224 
2225 		for (i = 0; i < common->fsg_num_buffers; ++i) {
2226 			struct fsg_buffhd *bh = &common->buffhds[i];
2227 
2228 			if (bh->inreq) {
2229 				usb_ep_free_request(fsg->bulk_in, bh->inreq);
2230 				bh->inreq = NULL;
2231 			}
2232 			if (bh->outreq) {
2233 				usb_ep_free_request(fsg->bulk_out, bh->outreq);
2234 				bh->outreq = NULL;
2235 			}
2236 		}
2237 
2238 		/* Disable the endpoints */
2239 		if (fsg->bulk_in_enabled) {
2240 			usb_ep_disable(fsg->bulk_in);
2241 			fsg->bulk_in_enabled = 0;
2242 		}
2243 		if (fsg->bulk_out_enabled) {
2244 			usb_ep_disable(fsg->bulk_out);
2245 			fsg->bulk_out_enabled = 0;
2246 		}
2247 
2248 		common->fsg = NULL;
2249 		wake_up(&common->fsg_wait);
2250 	}
2251 
2252 	common->running = 0;
2253 	if (!new_fsg || rc)
2254 		return rc;
2255 
2256 	common->fsg = new_fsg;
2257 	fsg = common->fsg;
2258 
2259 	/* Enable the endpoints */
2260 	rc = config_ep_by_speed(common->gadget, &(fsg->function), fsg->bulk_in);
2261 	if (rc)
2262 		goto reset;
2263 	rc = usb_ep_enable(fsg->bulk_in);
2264 	if (rc)
2265 		goto reset;
2266 	fsg->bulk_in->driver_data = common;
2267 	fsg->bulk_in_enabled = 1;
2268 
2269 	rc = config_ep_by_speed(common->gadget, &(fsg->function),
2270 				fsg->bulk_out);
2271 	if (rc)
2272 		goto reset;
2273 	rc = usb_ep_enable(fsg->bulk_out);
2274 	if (rc)
2275 		goto reset;
2276 	fsg->bulk_out->driver_data = common;
2277 	fsg->bulk_out_enabled = 1;
2278 	common->bulk_out_maxpacket = usb_endpoint_maxp(fsg->bulk_out->desc);
2279 	clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2280 
2281 	/* Allocate the requests */
2282 	for (i = 0; i < common->fsg_num_buffers; ++i) {
2283 		struct fsg_buffhd	*bh = &common->buffhds[i];
2284 
2285 		rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2286 		if (rc)
2287 			goto reset;
2288 		rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2289 		if (rc)
2290 			goto reset;
2291 		bh->inreq->buf = bh->outreq->buf = bh->buf;
2292 		bh->inreq->context = bh->outreq->context = bh;
2293 		bh->inreq->complete = bulk_in_complete;
2294 		bh->outreq->complete = bulk_out_complete;
2295 	}
2296 
2297 	common->running = 1;
2298 	for (i = 0; i < ARRAY_SIZE(common->luns); ++i)
2299 		if (common->luns[i])
2300 			common->luns[i]->unit_attention_data =
2301 				SS_RESET_OCCURRED;
2302 	return rc;
2303 }
2304 
2305 
2306 /****************************** ALT CONFIGS ******************************/
2307 
fsg_set_alt(struct usb_function * f,unsigned intf,unsigned alt)2308 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2309 {
2310 	struct fsg_dev *fsg = fsg_from_func(f);
2311 
2312 	__raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE, fsg);
2313 	return USB_GADGET_DELAYED_STATUS;
2314 }
2315 
fsg_disable(struct usb_function * f)2316 static void fsg_disable(struct usb_function *f)
2317 {
2318 	struct fsg_dev *fsg = fsg_from_func(f);
2319 
2320 	__raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE, NULL);
2321 }
2322 
2323 
2324 /*-------------------------------------------------------------------------*/
2325 
handle_exception(struct fsg_common * common)2326 static void handle_exception(struct fsg_common *common)
2327 {
2328 	int			i;
2329 	struct fsg_buffhd	*bh;
2330 	enum fsg_state		old_state;
2331 	struct fsg_lun		*curlun;
2332 	unsigned int		exception_req_tag;
2333 	struct fsg_dev		*new_fsg;
2334 
2335 	/*
2336 	 * Clear the existing signals.  Anything but SIGUSR1 is converted
2337 	 * into a high-priority EXIT exception.
2338 	 */
2339 	for (;;) {
2340 		int sig = kernel_dequeue_signal();
2341 		if (!sig)
2342 			break;
2343 		if (sig != SIGUSR1) {
2344 			spin_lock_irq(&common->lock);
2345 			if (common->state < FSG_STATE_EXIT)
2346 				DBG(common, "Main thread exiting on signal\n");
2347 			common->state = FSG_STATE_EXIT;
2348 			spin_unlock_irq(&common->lock);
2349 		}
2350 	}
2351 
2352 	/* Cancel all the pending transfers */
2353 	if (likely(common->fsg)) {
2354 		for (i = 0; i < common->fsg_num_buffers; ++i) {
2355 			bh = &common->buffhds[i];
2356 			if (bh->state == BUF_STATE_SENDING)
2357 				usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2358 			if (bh->state == BUF_STATE_RECEIVING)
2359 				usb_ep_dequeue(common->fsg->bulk_out,
2360 					       bh->outreq);
2361 
2362 			/* Wait for a transfer to become idle */
2363 			if (sleep_thread(common, false, bh))
2364 				return;
2365 		}
2366 
2367 		/* Clear out the controller's fifos */
2368 		if (common->fsg->bulk_in_enabled)
2369 			usb_ep_fifo_flush(common->fsg->bulk_in);
2370 		if (common->fsg->bulk_out_enabled)
2371 			usb_ep_fifo_flush(common->fsg->bulk_out);
2372 	}
2373 
2374 	/*
2375 	 * Reset the I/O buffer states and pointers, the SCSI
2376 	 * state, and the exception.  Then invoke the handler.
2377 	 */
2378 	spin_lock_irq(&common->lock);
2379 
2380 	for (i = 0; i < common->fsg_num_buffers; ++i) {
2381 		bh = &common->buffhds[i];
2382 		bh->state = BUF_STATE_EMPTY;
2383 	}
2384 	common->next_buffhd_to_fill = &common->buffhds[0];
2385 	common->next_buffhd_to_drain = &common->buffhds[0];
2386 	exception_req_tag = common->exception_req_tag;
2387 	new_fsg = common->exception_arg;
2388 	old_state = common->state;
2389 	common->state = FSG_STATE_NORMAL;
2390 
2391 	if (old_state != FSG_STATE_ABORT_BULK_OUT) {
2392 		for (i = 0; i < ARRAY_SIZE(common->luns); ++i) {
2393 			curlun = common->luns[i];
2394 			if (!curlun)
2395 				continue;
2396 			curlun->prevent_medium_removal = 0;
2397 			curlun->sense_data = SS_NO_SENSE;
2398 			curlun->unit_attention_data = SS_NO_SENSE;
2399 			curlun->sense_data_info = 0;
2400 			curlun->info_valid = 0;
2401 		}
2402 	}
2403 	spin_unlock_irq(&common->lock);
2404 
2405 	/* Carry out any extra actions required for the exception */
2406 	switch (old_state) {
2407 	case FSG_STATE_NORMAL:
2408 		break;
2409 
2410 	case FSG_STATE_ABORT_BULK_OUT:
2411 		send_status(common);
2412 		break;
2413 
2414 	case FSG_STATE_PROTOCOL_RESET:
2415 		/*
2416 		 * In case we were forced against our will to halt a
2417 		 * bulk endpoint, clear the halt now.  (The SuperH UDC
2418 		 * requires this.)
2419 		 */
2420 		if (!fsg_is_set(common))
2421 			break;
2422 		if (test_and_clear_bit(IGNORE_BULK_OUT,
2423 				       &common->fsg->atomic_bitflags))
2424 			usb_ep_clear_halt(common->fsg->bulk_in);
2425 
2426 		if (common->ep0_req_tag == exception_req_tag)
2427 			ep0_queue(common);	/* Complete the status stage */
2428 
2429 		/*
2430 		 * Technically this should go here, but it would only be
2431 		 * a waste of time.  Ditto for the INTERFACE_CHANGE and
2432 		 * CONFIG_CHANGE cases.
2433 		 */
2434 		/* for (i = 0; i < common->ARRAY_SIZE(common->luns); ++i) */
2435 		/*	if (common->luns[i]) */
2436 		/*		common->luns[i]->unit_attention_data = */
2437 		/*			SS_RESET_OCCURRED;  */
2438 		break;
2439 
2440 	case FSG_STATE_CONFIG_CHANGE:
2441 		do_set_interface(common, new_fsg);
2442 		if (new_fsg)
2443 			usb_composite_setup_continue(common->cdev);
2444 		break;
2445 
2446 	case FSG_STATE_EXIT:
2447 		do_set_interface(common, NULL);		/* Free resources */
2448 		spin_lock_irq(&common->lock);
2449 		common->state = FSG_STATE_TERMINATED;	/* Stop the thread */
2450 		spin_unlock_irq(&common->lock);
2451 		break;
2452 
2453 	case FSG_STATE_TERMINATED:
2454 		break;
2455 	}
2456 }
2457 
2458 
2459 /*-------------------------------------------------------------------------*/
2460 
fsg_main_thread(void * common_)2461 static int fsg_main_thread(void *common_)
2462 {
2463 	struct fsg_common	*common = common_;
2464 	int			i;
2465 
2466 	/*
2467 	 * Allow the thread to be killed by a signal, but set the signal mask
2468 	 * to block everything but INT, TERM, KILL, and USR1.
2469 	 */
2470 	allow_signal(SIGINT);
2471 	allow_signal(SIGTERM);
2472 	allow_signal(SIGKILL);
2473 	allow_signal(SIGUSR1);
2474 
2475 	/* Allow the thread to be frozen */
2476 	set_freezable();
2477 
2478 	/* The main loop */
2479 	while (common->state != FSG_STATE_TERMINATED) {
2480 		if (exception_in_progress(common) || signal_pending(current)) {
2481 			handle_exception(common);
2482 			continue;
2483 		}
2484 
2485 		if (!common->running) {
2486 			sleep_thread(common, true, NULL);
2487 			continue;
2488 		}
2489 
2490 		if (get_next_command(common) || exception_in_progress(common))
2491 			continue;
2492 		if (do_scsi_command(common) || exception_in_progress(common))
2493 			continue;
2494 		if (finish_reply(common) || exception_in_progress(common))
2495 			continue;
2496 		send_status(common);
2497 	}
2498 
2499 	spin_lock_irq(&common->lock);
2500 	common->thread_task = NULL;
2501 	spin_unlock_irq(&common->lock);
2502 
2503 	/* Eject media from all LUNs */
2504 
2505 	down_write(&common->filesem);
2506 	for (i = 0; i < ARRAY_SIZE(common->luns); i++) {
2507 		struct fsg_lun *curlun = common->luns[i];
2508 
2509 		if (curlun && fsg_lun_is_open(curlun))
2510 			fsg_lun_close(curlun);
2511 	}
2512 	up_write(&common->filesem);
2513 
2514 	/* Let fsg_unbind() know the thread has exited */
2515 	complete_and_exit(&common->thread_notifier, 0);
2516 }
2517 
2518 
2519 /*************************** DEVICE ATTRIBUTES ***************************/
2520 
ro_show(struct device * dev,struct device_attribute * attr,char * buf)2521 static ssize_t ro_show(struct device *dev, struct device_attribute *attr, char *buf)
2522 {
2523 	struct fsg_lun		*curlun = fsg_lun_from_dev(dev);
2524 
2525 	return fsg_show_ro(curlun, buf);
2526 }
2527 
nofua_show(struct device * dev,struct device_attribute * attr,char * buf)2528 static ssize_t nofua_show(struct device *dev, struct device_attribute *attr,
2529 			  char *buf)
2530 {
2531 	struct fsg_lun		*curlun = fsg_lun_from_dev(dev);
2532 
2533 	return fsg_show_nofua(curlun, buf);
2534 }
2535 
file_show(struct device * dev,struct device_attribute * attr,char * buf)2536 static ssize_t file_show(struct device *dev, struct device_attribute *attr,
2537 			 char *buf)
2538 {
2539 	struct fsg_lun		*curlun = fsg_lun_from_dev(dev);
2540 	struct rw_semaphore	*filesem = dev_get_drvdata(dev);
2541 
2542 	return fsg_show_file(curlun, filesem, buf);
2543 }
2544 
ro_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2545 static ssize_t ro_store(struct device *dev, struct device_attribute *attr,
2546 			const char *buf, size_t count)
2547 {
2548 	struct fsg_lun		*curlun = fsg_lun_from_dev(dev);
2549 	struct rw_semaphore	*filesem = dev_get_drvdata(dev);
2550 
2551 	return fsg_store_ro(curlun, filesem, buf, count);
2552 }
2553 
nofua_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2554 static ssize_t nofua_store(struct device *dev, struct device_attribute *attr,
2555 			   const char *buf, size_t count)
2556 {
2557 	struct fsg_lun		*curlun = fsg_lun_from_dev(dev);
2558 
2559 	return fsg_store_nofua(curlun, buf, count);
2560 }
2561 
file_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2562 static ssize_t file_store(struct device *dev, struct device_attribute *attr,
2563 			  const char *buf, size_t count)
2564 {
2565 	struct fsg_lun		*curlun = fsg_lun_from_dev(dev);
2566 	struct rw_semaphore	*filesem = dev_get_drvdata(dev);
2567 
2568 	return fsg_store_file(curlun, filesem, buf, count);
2569 }
2570 
2571 static DEVICE_ATTR_RW(nofua);
2572 /* mode wil be set in fsg_lun_attr_is_visible() */
2573 static DEVICE_ATTR(ro, 0, ro_show, ro_store);
2574 static DEVICE_ATTR(file, 0, file_show, file_store);
2575 
2576 /****************************** FSG COMMON ******************************/
2577 
fsg_lun_release(struct device * dev)2578 static void fsg_lun_release(struct device *dev)
2579 {
2580 	/* Nothing needs to be done */
2581 }
2582 
fsg_common_setup(struct fsg_common * common)2583 static struct fsg_common *fsg_common_setup(struct fsg_common *common)
2584 {
2585 	if (!common) {
2586 		common = kzalloc(sizeof(*common), GFP_KERNEL);
2587 		if (!common)
2588 			return ERR_PTR(-ENOMEM);
2589 		common->free_storage_on_release = 1;
2590 	} else {
2591 		common->free_storage_on_release = 0;
2592 	}
2593 	init_rwsem(&common->filesem);
2594 	spin_lock_init(&common->lock);
2595 	init_completion(&common->thread_notifier);
2596 	init_waitqueue_head(&common->io_wait);
2597 	init_waitqueue_head(&common->fsg_wait);
2598 	common->state = FSG_STATE_TERMINATED;
2599 	memset(common->luns, 0, sizeof(common->luns));
2600 
2601 	return common;
2602 }
2603 
fsg_common_set_sysfs(struct fsg_common * common,bool sysfs)2604 void fsg_common_set_sysfs(struct fsg_common *common, bool sysfs)
2605 {
2606 	common->sysfs = sysfs;
2607 }
2608 EXPORT_SYMBOL_GPL(fsg_common_set_sysfs);
2609 
_fsg_common_free_buffers(struct fsg_buffhd * buffhds,unsigned n)2610 static void _fsg_common_free_buffers(struct fsg_buffhd *buffhds, unsigned n)
2611 {
2612 	if (buffhds) {
2613 		struct fsg_buffhd *bh = buffhds;
2614 		while (n--) {
2615 			kfree(bh->buf);
2616 			++bh;
2617 		}
2618 		kfree(buffhds);
2619 	}
2620 }
2621 
fsg_common_set_num_buffers(struct fsg_common * common,unsigned int n)2622 int fsg_common_set_num_buffers(struct fsg_common *common, unsigned int n)
2623 {
2624 	struct fsg_buffhd *bh, *buffhds;
2625 	int i;
2626 
2627 	buffhds = kcalloc(n, sizeof(*buffhds), GFP_KERNEL);
2628 	if (!buffhds)
2629 		return -ENOMEM;
2630 
2631 	/* Data buffers cyclic list */
2632 	bh = buffhds;
2633 	i = n;
2634 	goto buffhds_first_it;
2635 	do {
2636 		bh->next = bh + 1;
2637 		++bh;
2638 buffhds_first_it:
2639 		bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2640 		if (unlikely(!bh->buf))
2641 			goto error_release;
2642 	} while (--i);
2643 	bh->next = buffhds;
2644 
2645 	_fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
2646 	common->fsg_num_buffers = n;
2647 	common->buffhds = buffhds;
2648 
2649 	return 0;
2650 
2651 error_release:
2652 	/*
2653 	 * "buf"s pointed to by heads after n - i are NULL
2654 	 * so releasing them won't hurt
2655 	 */
2656 	_fsg_common_free_buffers(buffhds, n);
2657 
2658 	return -ENOMEM;
2659 }
2660 EXPORT_SYMBOL_GPL(fsg_common_set_num_buffers);
2661 
fsg_common_remove_lun(struct fsg_lun * lun)2662 void fsg_common_remove_lun(struct fsg_lun *lun)
2663 {
2664 	if (device_is_registered(&lun->dev))
2665 		device_unregister(&lun->dev);
2666 	fsg_lun_close(lun);
2667 	kfree(lun);
2668 }
2669 EXPORT_SYMBOL_GPL(fsg_common_remove_lun);
2670 
_fsg_common_remove_luns(struct fsg_common * common,int n)2671 static void _fsg_common_remove_luns(struct fsg_common *common, int n)
2672 {
2673 	int i;
2674 
2675 	for (i = 0; i < n; ++i)
2676 		if (common->luns[i]) {
2677 			fsg_common_remove_lun(common->luns[i]);
2678 			common->luns[i] = NULL;
2679 		}
2680 }
2681 
fsg_common_remove_luns(struct fsg_common * common)2682 void fsg_common_remove_luns(struct fsg_common *common)
2683 {
2684 	_fsg_common_remove_luns(common, ARRAY_SIZE(common->luns));
2685 }
2686 EXPORT_SYMBOL_GPL(fsg_common_remove_luns);
2687 
fsg_common_free_buffers(struct fsg_common * common)2688 void fsg_common_free_buffers(struct fsg_common *common)
2689 {
2690 	_fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
2691 	common->buffhds = NULL;
2692 }
2693 EXPORT_SYMBOL_GPL(fsg_common_free_buffers);
2694 
fsg_common_set_cdev(struct fsg_common * common,struct usb_composite_dev * cdev,bool can_stall)2695 int fsg_common_set_cdev(struct fsg_common *common,
2696 			 struct usb_composite_dev *cdev, bool can_stall)
2697 {
2698 	struct usb_string *us;
2699 
2700 	common->gadget = cdev->gadget;
2701 	common->ep0 = cdev->gadget->ep0;
2702 	common->ep0req = cdev->req;
2703 	common->cdev = cdev;
2704 
2705 	us = usb_gstrings_attach(cdev, fsg_strings_array,
2706 				 ARRAY_SIZE(fsg_strings));
2707 	if (IS_ERR(us))
2708 		return PTR_ERR(us);
2709 
2710 	fsg_intf_desc.iInterface = us[FSG_STRING_INTERFACE].id;
2711 
2712 	/*
2713 	 * Some peripheral controllers are known not to be able to
2714 	 * halt bulk endpoints correctly.  If one of them is present,
2715 	 * disable stalls.
2716 	 */
2717 	common->can_stall = can_stall &&
2718 			gadget_is_stall_supported(common->gadget);
2719 
2720 	return 0;
2721 }
2722 EXPORT_SYMBOL_GPL(fsg_common_set_cdev);
2723 
2724 static struct attribute *fsg_lun_dev_attrs[] = {
2725 	&dev_attr_ro.attr,
2726 	&dev_attr_file.attr,
2727 	&dev_attr_nofua.attr,
2728 	NULL
2729 };
2730 
fsg_lun_dev_is_visible(struct kobject * kobj,struct attribute * attr,int idx)2731 static umode_t fsg_lun_dev_is_visible(struct kobject *kobj,
2732 				      struct attribute *attr, int idx)
2733 {
2734 	struct device *dev = kobj_to_dev(kobj);
2735 	struct fsg_lun *lun = fsg_lun_from_dev(dev);
2736 
2737 	if (attr == &dev_attr_ro.attr)
2738 		return lun->cdrom ? S_IRUGO : (S_IWUSR | S_IRUGO);
2739 	if (attr == &dev_attr_file.attr)
2740 		return lun->removable ? (S_IWUSR | S_IRUGO) : S_IRUGO;
2741 	return attr->mode;
2742 }
2743 
2744 static const struct attribute_group fsg_lun_dev_group = {
2745 	.attrs = fsg_lun_dev_attrs,
2746 	.is_visible = fsg_lun_dev_is_visible,
2747 };
2748 
2749 static const struct attribute_group *fsg_lun_dev_groups[] = {
2750 	&fsg_lun_dev_group,
2751 	NULL
2752 };
2753 
fsg_common_create_lun(struct fsg_common * common,struct fsg_lun_config * cfg,unsigned int id,const char * name,const char ** name_pfx)2754 int fsg_common_create_lun(struct fsg_common *common, struct fsg_lun_config *cfg,
2755 			  unsigned int id, const char *name,
2756 			  const char **name_pfx)
2757 {
2758 	struct fsg_lun *lun;
2759 	char *pathbuf, *p;
2760 	int rc = -ENOMEM;
2761 
2762 	if (id >= ARRAY_SIZE(common->luns))
2763 		return -ENODEV;
2764 
2765 	if (common->luns[id])
2766 		return -EBUSY;
2767 
2768 	if (!cfg->filename && !cfg->removable) {
2769 		pr_err("no file given for LUN%d\n", id);
2770 		return -EINVAL;
2771 	}
2772 
2773 	lun = kzalloc(sizeof(*lun), GFP_KERNEL);
2774 	if (!lun)
2775 		return -ENOMEM;
2776 
2777 	lun->name_pfx = name_pfx;
2778 
2779 	lun->cdrom = !!cfg->cdrom;
2780 	lun->ro = cfg->cdrom || cfg->ro;
2781 	lun->initially_ro = lun->ro;
2782 	lun->removable = !!cfg->removable;
2783 
2784 	if (!common->sysfs) {
2785 		/* we DON'T own the name!*/
2786 		lun->name = name;
2787 	} else {
2788 		lun->dev.release = fsg_lun_release;
2789 		lun->dev.parent = &common->gadget->dev;
2790 		lun->dev.groups = fsg_lun_dev_groups;
2791 		dev_set_drvdata(&lun->dev, &common->filesem);
2792 		dev_set_name(&lun->dev, "%s", name);
2793 		lun->name = dev_name(&lun->dev);
2794 
2795 		rc = device_register(&lun->dev);
2796 		if (rc) {
2797 			pr_info("failed to register LUN%d: %d\n", id, rc);
2798 			put_device(&lun->dev);
2799 			goto error_sysfs;
2800 		}
2801 	}
2802 
2803 	common->luns[id] = lun;
2804 
2805 	if (cfg->filename) {
2806 		rc = fsg_lun_open(lun, cfg->filename);
2807 		if (rc)
2808 			goto error_lun;
2809 	}
2810 
2811 	pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2812 	p = "(no medium)";
2813 	if (fsg_lun_is_open(lun)) {
2814 		p = "(error)";
2815 		if (pathbuf) {
2816 			p = file_path(lun->filp, pathbuf, PATH_MAX);
2817 			if (IS_ERR(p))
2818 				p = "(error)";
2819 		}
2820 	}
2821 	pr_info("LUN: %s%s%sfile: %s\n",
2822 	      lun->removable ? "removable " : "",
2823 	      lun->ro ? "read only " : "",
2824 	      lun->cdrom ? "CD-ROM " : "",
2825 	      p);
2826 	kfree(pathbuf);
2827 
2828 	return 0;
2829 
2830 error_lun:
2831 	if (device_is_registered(&lun->dev))
2832 		device_unregister(&lun->dev);
2833 	fsg_lun_close(lun);
2834 	common->luns[id] = NULL;
2835 error_sysfs:
2836 	kfree(lun);
2837 	return rc;
2838 }
2839 EXPORT_SYMBOL_GPL(fsg_common_create_lun);
2840 
fsg_common_create_luns(struct fsg_common * common,struct fsg_config * cfg)2841 int fsg_common_create_luns(struct fsg_common *common, struct fsg_config *cfg)
2842 {
2843 	char buf[8]; /* enough for 100000000 different numbers, decimal */
2844 	int i, rc;
2845 
2846 	fsg_common_remove_luns(common);
2847 
2848 	for (i = 0; i < cfg->nluns; ++i) {
2849 		snprintf(buf, sizeof(buf), "lun%d", i);
2850 		rc = fsg_common_create_lun(common, &cfg->luns[i], i, buf, NULL);
2851 		if (rc)
2852 			goto fail;
2853 	}
2854 
2855 	pr_info("Number of LUNs=%d\n", cfg->nluns);
2856 
2857 	return 0;
2858 
2859 fail:
2860 	_fsg_common_remove_luns(common, i);
2861 	return rc;
2862 }
2863 EXPORT_SYMBOL_GPL(fsg_common_create_luns);
2864 
fsg_common_set_inquiry_string(struct fsg_common * common,const char * vn,const char * pn)2865 void fsg_common_set_inquiry_string(struct fsg_common *common, const char *vn,
2866 				   const char *pn)
2867 {
2868 	int i;
2869 
2870 	/* Prepare inquiryString */
2871 	i = get_default_bcdDevice();
2872 	snprintf(common->inquiry_string, sizeof(common->inquiry_string),
2873 		 "%-8s%-16s%04x", vn ?: "Linux",
2874 		 /* Assume product name dependent on the first LUN */
2875 		 pn ?: ((*common->luns)->cdrom
2876 		     ? "File-CD Gadget"
2877 		     : "File-Stor Gadget"),
2878 		 i);
2879 }
2880 EXPORT_SYMBOL_GPL(fsg_common_set_inquiry_string);
2881 
fsg_common_release(struct fsg_common * common)2882 static void fsg_common_release(struct fsg_common *common)
2883 {
2884 	int i;
2885 
2886 	/* If the thread isn't already dead, tell it to exit now */
2887 	if (common->state != FSG_STATE_TERMINATED) {
2888 		raise_exception(common, FSG_STATE_EXIT);
2889 		wait_for_completion(&common->thread_notifier);
2890 	}
2891 
2892 	for (i = 0; i < ARRAY_SIZE(common->luns); ++i) {
2893 		struct fsg_lun *lun = common->luns[i];
2894 		if (!lun)
2895 			continue;
2896 		fsg_lun_close(lun);
2897 		if (device_is_registered(&lun->dev))
2898 			device_unregister(&lun->dev);
2899 		kfree(lun);
2900 	}
2901 
2902 	_fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
2903 	if (common->free_storage_on_release)
2904 		kfree(common);
2905 }
2906 
2907 
2908 /*-------------------------------------------------------------------------*/
2909 
fsg_bind(struct usb_configuration * c,struct usb_function * f)2910 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2911 {
2912 	struct fsg_dev		*fsg = fsg_from_func(f);
2913 	struct fsg_common	*common = fsg->common;
2914 	struct usb_gadget	*gadget = c->cdev->gadget;
2915 	int			i;
2916 	struct usb_ep		*ep;
2917 	unsigned		max_burst;
2918 	int			ret;
2919 	struct fsg_opts		*opts;
2920 
2921 	/* Don't allow to bind if we don't have at least one LUN */
2922 	ret = _fsg_common_get_max_lun(common);
2923 	if (ret < 0) {
2924 		pr_err("There should be at least one LUN.\n");
2925 		return -EINVAL;
2926 	}
2927 
2928 	opts = fsg_opts_from_func_inst(f->fi);
2929 	if (!opts->no_configfs) {
2930 		ret = fsg_common_set_cdev(fsg->common, c->cdev,
2931 					  fsg->common->can_stall);
2932 		if (ret)
2933 			return ret;
2934 		fsg_common_set_inquiry_string(fsg->common, NULL, NULL);
2935 	}
2936 
2937 	if (!common->thread_task) {
2938 		common->state = FSG_STATE_NORMAL;
2939 		common->thread_task =
2940 			kthread_create(fsg_main_thread, common, "file-storage");
2941 		if (IS_ERR(common->thread_task)) {
2942 			ret = PTR_ERR(common->thread_task);
2943 			common->thread_task = NULL;
2944 			common->state = FSG_STATE_TERMINATED;
2945 			return ret;
2946 		}
2947 		DBG(common, "I/O thread pid: %d\n",
2948 		    task_pid_nr(common->thread_task));
2949 		wake_up_process(common->thread_task);
2950 	}
2951 
2952 	fsg->gadget = gadget;
2953 
2954 	/* New interface */
2955 	i = usb_interface_id(c, f);
2956 	if (i < 0)
2957 		goto fail;
2958 	fsg_intf_desc.bInterfaceNumber = i;
2959 	fsg->interface_number = i;
2960 
2961 	/* Find all the endpoints we will use */
2962 	ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2963 	if (!ep)
2964 		goto autoconf_fail;
2965 	fsg->bulk_in = ep;
2966 
2967 	ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2968 	if (!ep)
2969 		goto autoconf_fail;
2970 	fsg->bulk_out = ep;
2971 
2972 	/* Assume endpoint addresses are the same for both speeds */
2973 	fsg_hs_bulk_in_desc.bEndpointAddress =
2974 		fsg_fs_bulk_in_desc.bEndpointAddress;
2975 	fsg_hs_bulk_out_desc.bEndpointAddress =
2976 		fsg_fs_bulk_out_desc.bEndpointAddress;
2977 
2978 	/* Calculate bMaxBurst, we know packet size is 1024 */
2979 	max_burst = min_t(unsigned, FSG_BUFLEN / 1024, 15);
2980 
2981 	fsg_ss_bulk_in_desc.bEndpointAddress =
2982 		fsg_fs_bulk_in_desc.bEndpointAddress;
2983 	fsg_ss_bulk_in_comp_desc.bMaxBurst = max_burst;
2984 
2985 	fsg_ss_bulk_out_desc.bEndpointAddress =
2986 		fsg_fs_bulk_out_desc.bEndpointAddress;
2987 	fsg_ss_bulk_out_comp_desc.bMaxBurst = max_burst;
2988 
2989 	ret = usb_assign_descriptors(f, fsg_fs_function, fsg_hs_function,
2990 			fsg_ss_function, fsg_ss_function);
2991 	if (ret)
2992 		goto autoconf_fail;
2993 
2994 	return 0;
2995 
2996 autoconf_fail:
2997 	ERROR(fsg, "unable to autoconfigure all endpoints\n");
2998 	i = -ENOTSUPP;
2999 fail:
3000 	/* terminate the thread */
3001 	if (fsg->common->state != FSG_STATE_TERMINATED) {
3002 		raise_exception(fsg->common, FSG_STATE_EXIT);
3003 		wait_for_completion(&fsg->common->thread_notifier);
3004 	}
3005 	return i;
3006 }
3007 
3008 /****************************** ALLOCATE FUNCTION *************************/
3009 
fsg_unbind(struct usb_configuration * c,struct usb_function * f)3010 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
3011 {
3012 	struct fsg_dev		*fsg = fsg_from_func(f);
3013 	struct fsg_common	*common = fsg->common;
3014 
3015 	DBG(fsg, "unbind\n");
3016 	if (fsg->common->fsg == fsg) {
3017 		__raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE, NULL);
3018 		/* FIXME: make interruptible or killable somehow? */
3019 		wait_event(common->fsg_wait, common->fsg != fsg);
3020 	}
3021 
3022 	usb_free_all_descriptors(&fsg->function);
3023 }
3024 
to_fsg_lun_opts(struct config_item * item)3025 static inline struct fsg_lun_opts *to_fsg_lun_opts(struct config_item *item)
3026 {
3027 	return container_of(to_config_group(item), struct fsg_lun_opts, group);
3028 }
3029 
to_fsg_opts(struct config_item * item)3030 static inline struct fsg_opts *to_fsg_opts(struct config_item *item)
3031 {
3032 	return container_of(to_config_group(item), struct fsg_opts,
3033 			    func_inst.group);
3034 }
3035 
fsg_lun_attr_release(struct config_item * item)3036 static void fsg_lun_attr_release(struct config_item *item)
3037 {
3038 	struct fsg_lun_opts *lun_opts;
3039 
3040 	lun_opts = to_fsg_lun_opts(item);
3041 	kfree(lun_opts);
3042 }
3043 
3044 static struct configfs_item_operations fsg_lun_item_ops = {
3045 	.release		= fsg_lun_attr_release,
3046 };
3047 
fsg_lun_opts_file_show(struct config_item * item,char * page)3048 static ssize_t fsg_lun_opts_file_show(struct config_item *item, char *page)
3049 {
3050 	struct fsg_lun_opts *opts = to_fsg_lun_opts(item);
3051 	struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
3052 
3053 	return fsg_show_file(opts->lun, &fsg_opts->common->filesem, page);
3054 }
3055 
fsg_lun_opts_file_store(struct config_item * item,const char * page,size_t len)3056 static ssize_t fsg_lun_opts_file_store(struct config_item *item,
3057 				       const char *page, size_t len)
3058 {
3059 	struct fsg_lun_opts *opts = to_fsg_lun_opts(item);
3060 	struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
3061 
3062 	return fsg_store_file(opts->lun, &fsg_opts->common->filesem, page, len);
3063 }
3064 
3065 CONFIGFS_ATTR(fsg_lun_opts_, file);
3066 
fsg_lun_opts_ro_show(struct config_item * item,char * page)3067 static ssize_t fsg_lun_opts_ro_show(struct config_item *item, char *page)
3068 {
3069 	return fsg_show_ro(to_fsg_lun_opts(item)->lun, page);
3070 }
3071 
fsg_lun_opts_ro_store(struct config_item * item,const char * page,size_t len)3072 static ssize_t fsg_lun_opts_ro_store(struct config_item *item,
3073 				       const char *page, size_t len)
3074 {
3075 	struct fsg_lun_opts *opts = to_fsg_lun_opts(item);
3076 	struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
3077 
3078 	return fsg_store_ro(opts->lun, &fsg_opts->common->filesem, page, len);
3079 }
3080 
3081 CONFIGFS_ATTR(fsg_lun_opts_, ro);
3082 
fsg_lun_opts_removable_show(struct config_item * item,char * page)3083 static ssize_t fsg_lun_opts_removable_show(struct config_item *item,
3084 					   char *page)
3085 {
3086 	return fsg_show_removable(to_fsg_lun_opts(item)->lun, page);
3087 }
3088 
fsg_lun_opts_removable_store(struct config_item * item,const char * page,size_t len)3089 static ssize_t fsg_lun_opts_removable_store(struct config_item *item,
3090 				       const char *page, size_t len)
3091 {
3092 	return fsg_store_removable(to_fsg_lun_opts(item)->lun, page, len);
3093 }
3094 
3095 CONFIGFS_ATTR(fsg_lun_opts_, removable);
3096 
fsg_lun_opts_cdrom_show(struct config_item * item,char * page)3097 static ssize_t fsg_lun_opts_cdrom_show(struct config_item *item, char *page)
3098 {
3099 	return fsg_show_cdrom(to_fsg_lun_opts(item)->lun, page);
3100 }
3101 
fsg_lun_opts_cdrom_store(struct config_item * item,const char * page,size_t len)3102 static ssize_t fsg_lun_opts_cdrom_store(struct config_item *item,
3103 				       const char *page, size_t len)
3104 {
3105 	struct fsg_lun_opts *opts = to_fsg_lun_opts(item);
3106 	struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
3107 
3108 	return fsg_store_cdrom(opts->lun, &fsg_opts->common->filesem, page,
3109 			       len);
3110 }
3111 
3112 CONFIGFS_ATTR(fsg_lun_opts_, cdrom);
3113 
fsg_lun_opts_nofua_show(struct config_item * item,char * page)3114 static ssize_t fsg_lun_opts_nofua_show(struct config_item *item, char *page)
3115 {
3116 	return fsg_show_nofua(to_fsg_lun_opts(item)->lun, page);
3117 }
3118 
fsg_lun_opts_nofua_store(struct config_item * item,const char * page,size_t len)3119 static ssize_t fsg_lun_opts_nofua_store(struct config_item *item,
3120 				       const char *page, size_t len)
3121 {
3122 	return fsg_store_nofua(to_fsg_lun_opts(item)->lun, page, len);
3123 }
3124 
3125 CONFIGFS_ATTR(fsg_lun_opts_, nofua);
3126 
fsg_lun_opts_inquiry_string_show(struct config_item * item,char * page)3127 static ssize_t fsg_lun_opts_inquiry_string_show(struct config_item *item,
3128 						char *page)
3129 {
3130 	return fsg_show_inquiry_string(to_fsg_lun_opts(item)->lun, page);
3131 }
3132 
fsg_lun_opts_inquiry_string_store(struct config_item * item,const char * page,size_t len)3133 static ssize_t fsg_lun_opts_inquiry_string_store(struct config_item *item,
3134 						 const char *page, size_t len)
3135 {
3136 	return fsg_store_inquiry_string(to_fsg_lun_opts(item)->lun, page, len);
3137 }
3138 
3139 CONFIGFS_ATTR(fsg_lun_opts_, inquiry_string);
3140 
3141 static struct configfs_attribute *fsg_lun_attrs[] = {
3142 	&fsg_lun_opts_attr_file,
3143 	&fsg_lun_opts_attr_ro,
3144 	&fsg_lun_opts_attr_removable,
3145 	&fsg_lun_opts_attr_cdrom,
3146 	&fsg_lun_opts_attr_nofua,
3147 	&fsg_lun_opts_attr_inquiry_string,
3148 	NULL,
3149 };
3150 
3151 static const struct config_item_type fsg_lun_type = {
3152 	.ct_item_ops	= &fsg_lun_item_ops,
3153 	.ct_attrs	= fsg_lun_attrs,
3154 	.ct_owner	= THIS_MODULE,
3155 };
3156 
fsg_lun_make(struct config_group * group,const char * name)3157 static struct config_group *fsg_lun_make(struct config_group *group,
3158 					 const char *name)
3159 {
3160 	struct fsg_lun_opts *opts;
3161 	struct fsg_opts *fsg_opts;
3162 	struct fsg_lun_config config;
3163 	char *num_str;
3164 	u8 num;
3165 	int ret;
3166 
3167 	num_str = strchr(name, '.');
3168 	if (!num_str) {
3169 		pr_err("Unable to locate . in LUN.NUMBER\n");
3170 		return ERR_PTR(-EINVAL);
3171 	}
3172 	num_str++;
3173 
3174 	ret = kstrtou8(num_str, 0, &num);
3175 	if (ret)
3176 		return ERR_PTR(ret);
3177 
3178 	fsg_opts = to_fsg_opts(&group->cg_item);
3179 	if (num >= FSG_MAX_LUNS)
3180 		return ERR_PTR(-ERANGE);
3181 	num = array_index_nospec(num, FSG_MAX_LUNS);
3182 
3183 	mutex_lock(&fsg_opts->lock);
3184 	if (fsg_opts->refcnt || fsg_opts->common->luns[num]) {
3185 		ret = -EBUSY;
3186 		goto out;
3187 	}
3188 
3189 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3190 	if (!opts) {
3191 		ret = -ENOMEM;
3192 		goto out;
3193 	}
3194 
3195 	memset(&config, 0, sizeof(config));
3196 	config.removable = true;
3197 
3198 	ret = fsg_common_create_lun(fsg_opts->common, &config, num, name,
3199 				    (const char **)&group->cg_item.ci_name);
3200 	if (ret) {
3201 		kfree(opts);
3202 		goto out;
3203 	}
3204 	opts->lun = fsg_opts->common->luns[num];
3205 	opts->lun_id = num;
3206 	mutex_unlock(&fsg_opts->lock);
3207 
3208 	config_group_init_type_name(&opts->group, name, &fsg_lun_type);
3209 
3210 	return &opts->group;
3211 out:
3212 	mutex_unlock(&fsg_opts->lock);
3213 	return ERR_PTR(ret);
3214 }
3215 
fsg_lun_drop(struct config_group * group,struct config_item * item)3216 static void fsg_lun_drop(struct config_group *group, struct config_item *item)
3217 {
3218 	struct fsg_lun_opts *lun_opts;
3219 	struct fsg_opts *fsg_opts;
3220 
3221 	lun_opts = to_fsg_lun_opts(item);
3222 	fsg_opts = to_fsg_opts(&group->cg_item);
3223 
3224 	mutex_lock(&fsg_opts->lock);
3225 	if (fsg_opts->refcnt) {
3226 		struct config_item *gadget;
3227 
3228 		gadget = group->cg_item.ci_parent->ci_parent;
3229 		unregister_gadget_item(gadget);
3230 	}
3231 
3232 	fsg_common_remove_lun(lun_opts->lun);
3233 	fsg_opts->common->luns[lun_opts->lun_id] = NULL;
3234 	lun_opts->lun_id = 0;
3235 	mutex_unlock(&fsg_opts->lock);
3236 
3237 	config_item_put(item);
3238 }
3239 
fsg_attr_release(struct config_item * item)3240 static void fsg_attr_release(struct config_item *item)
3241 {
3242 	struct fsg_opts *opts = to_fsg_opts(item);
3243 
3244 	usb_put_function_instance(&opts->func_inst);
3245 }
3246 
3247 static struct configfs_item_operations fsg_item_ops = {
3248 	.release		= fsg_attr_release,
3249 };
3250 
fsg_opts_stall_show(struct config_item * item,char * page)3251 static ssize_t fsg_opts_stall_show(struct config_item *item, char *page)
3252 {
3253 	struct fsg_opts *opts = to_fsg_opts(item);
3254 	int result;
3255 
3256 	mutex_lock(&opts->lock);
3257 	result = sprintf(page, "%d", opts->common->can_stall);
3258 	mutex_unlock(&opts->lock);
3259 
3260 	return result;
3261 }
3262 
fsg_opts_stall_store(struct config_item * item,const char * page,size_t len)3263 static ssize_t fsg_opts_stall_store(struct config_item *item, const char *page,
3264 				    size_t len)
3265 {
3266 	struct fsg_opts *opts = to_fsg_opts(item);
3267 	int ret;
3268 	bool stall;
3269 
3270 	mutex_lock(&opts->lock);
3271 
3272 	if (opts->refcnt) {
3273 		mutex_unlock(&opts->lock);
3274 		return -EBUSY;
3275 	}
3276 
3277 	ret = strtobool(page, &stall);
3278 	if (!ret) {
3279 		opts->common->can_stall = stall;
3280 		ret = len;
3281 	}
3282 
3283 	mutex_unlock(&opts->lock);
3284 
3285 	return ret;
3286 }
3287 
3288 CONFIGFS_ATTR(fsg_opts_, stall);
3289 
3290 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
fsg_opts_num_buffers_show(struct config_item * item,char * page)3291 static ssize_t fsg_opts_num_buffers_show(struct config_item *item, char *page)
3292 {
3293 	struct fsg_opts *opts = to_fsg_opts(item);
3294 	int result;
3295 
3296 	mutex_lock(&opts->lock);
3297 	result = sprintf(page, "%d", opts->common->fsg_num_buffers);
3298 	mutex_unlock(&opts->lock);
3299 
3300 	return result;
3301 }
3302 
fsg_opts_num_buffers_store(struct config_item * item,const char * page,size_t len)3303 static ssize_t fsg_opts_num_buffers_store(struct config_item *item,
3304 					  const char *page, size_t len)
3305 {
3306 	struct fsg_opts *opts = to_fsg_opts(item);
3307 	int ret;
3308 	u8 num;
3309 
3310 	mutex_lock(&opts->lock);
3311 	if (opts->refcnt) {
3312 		ret = -EBUSY;
3313 		goto end;
3314 	}
3315 	ret = kstrtou8(page, 0, &num);
3316 	if (ret)
3317 		goto end;
3318 
3319 	ret = fsg_common_set_num_buffers(opts->common, num);
3320 	if (ret)
3321 		goto end;
3322 	ret = len;
3323 
3324 end:
3325 	mutex_unlock(&opts->lock);
3326 	return ret;
3327 }
3328 
3329 CONFIGFS_ATTR(fsg_opts_, num_buffers);
3330 #endif
3331 
3332 static struct configfs_attribute *fsg_attrs[] = {
3333 	&fsg_opts_attr_stall,
3334 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
3335 	&fsg_opts_attr_num_buffers,
3336 #endif
3337 	NULL,
3338 };
3339 
3340 static struct configfs_group_operations fsg_group_ops = {
3341 	.make_group	= fsg_lun_make,
3342 	.drop_item	= fsg_lun_drop,
3343 };
3344 
3345 static const struct config_item_type fsg_func_type = {
3346 	.ct_item_ops	= &fsg_item_ops,
3347 	.ct_group_ops	= &fsg_group_ops,
3348 	.ct_attrs	= fsg_attrs,
3349 	.ct_owner	= THIS_MODULE,
3350 };
3351 
fsg_free_inst(struct usb_function_instance * fi)3352 static void fsg_free_inst(struct usb_function_instance *fi)
3353 {
3354 	struct fsg_opts *opts;
3355 
3356 	opts = fsg_opts_from_func_inst(fi);
3357 	fsg_common_release(opts->common);
3358 	kfree(opts);
3359 }
3360 
fsg_alloc_inst(void)3361 static struct usb_function_instance *fsg_alloc_inst(void)
3362 {
3363 	struct fsg_opts *opts;
3364 	struct fsg_lun_config config;
3365 	int rc;
3366 
3367 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3368 	if (!opts)
3369 		return ERR_PTR(-ENOMEM);
3370 	mutex_init(&opts->lock);
3371 	opts->func_inst.free_func_inst = fsg_free_inst;
3372 	opts->common = fsg_common_setup(opts->common);
3373 	if (IS_ERR(opts->common)) {
3374 		rc = PTR_ERR(opts->common);
3375 		goto release_opts;
3376 	}
3377 
3378 	rc = fsg_common_set_num_buffers(opts->common,
3379 					CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS);
3380 	if (rc)
3381 		goto release_common;
3382 
3383 	pr_info(FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
3384 
3385 	memset(&config, 0, sizeof(config));
3386 	config.removable = true;
3387 	rc = fsg_common_create_lun(opts->common, &config, 0, "lun.0",
3388 			(const char **)&opts->func_inst.group.cg_item.ci_name);
3389 	if (rc)
3390 		goto release_buffers;
3391 
3392 	opts->lun0.lun = opts->common->luns[0];
3393 	opts->lun0.lun_id = 0;
3394 
3395 	config_group_init_type_name(&opts->func_inst.group, "", &fsg_func_type);
3396 
3397 	config_group_init_type_name(&opts->lun0.group, "lun.0", &fsg_lun_type);
3398 	configfs_add_default_group(&opts->lun0.group, &opts->func_inst.group);
3399 
3400 	return &opts->func_inst;
3401 
3402 release_buffers:
3403 	fsg_common_free_buffers(opts->common);
3404 release_common:
3405 	kfree(opts->common);
3406 release_opts:
3407 	kfree(opts);
3408 	return ERR_PTR(rc);
3409 }
3410 
fsg_free(struct usb_function * f)3411 static void fsg_free(struct usb_function *f)
3412 {
3413 	struct fsg_dev *fsg;
3414 	struct fsg_opts *opts;
3415 
3416 	fsg = container_of(f, struct fsg_dev, function);
3417 	opts = container_of(f->fi, struct fsg_opts, func_inst);
3418 
3419 	mutex_lock(&opts->lock);
3420 	opts->refcnt--;
3421 	mutex_unlock(&opts->lock);
3422 
3423 	kfree(fsg);
3424 }
3425 
fsg_alloc(struct usb_function_instance * fi)3426 static struct usb_function *fsg_alloc(struct usb_function_instance *fi)
3427 {
3428 	struct fsg_opts *opts = fsg_opts_from_func_inst(fi);
3429 	struct fsg_common *common = opts->common;
3430 	struct fsg_dev *fsg;
3431 
3432 	fsg = kzalloc(sizeof(*fsg), GFP_KERNEL);
3433 	if (unlikely(!fsg))
3434 		return ERR_PTR(-ENOMEM);
3435 
3436 	mutex_lock(&opts->lock);
3437 	opts->refcnt++;
3438 	mutex_unlock(&opts->lock);
3439 
3440 	fsg->function.name	= FSG_DRIVER_DESC;
3441 	fsg->function.bind	= fsg_bind;
3442 	fsg->function.unbind	= fsg_unbind;
3443 	fsg->function.setup	= fsg_setup;
3444 	fsg->function.set_alt	= fsg_set_alt;
3445 	fsg->function.disable	= fsg_disable;
3446 	fsg->function.free_func	= fsg_free;
3447 
3448 	fsg->common               = common;
3449 
3450 	return &fsg->function;
3451 }
3452 
3453 DECLARE_USB_FUNCTION_INIT(mass_storage, fsg_alloc_inst, fsg_alloc);
3454 MODULE_LICENSE("GPL");
3455 MODULE_AUTHOR("Michal Nazarewicz");
3456 
3457 /************************* Module parameters *************************/
3458 
3459 
fsg_config_from_params(struct fsg_config * cfg,const struct fsg_module_parameters * params,unsigned int fsg_num_buffers)3460 void fsg_config_from_params(struct fsg_config *cfg,
3461 		       const struct fsg_module_parameters *params,
3462 		       unsigned int fsg_num_buffers)
3463 {
3464 	struct fsg_lun_config *lun;
3465 	unsigned i;
3466 
3467 	/* Configure LUNs */
3468 	cfg->nluns =
3469 		min(params->luns ?: (params->file_count ?: 1u),
3470 		    (unsigned)FSG_MAX_LUNS);
3471 	for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3472 		lun->ro = !!params->ro[i];
3473 		lun->cdrom = !!params->cdrom[i];
3474 		lun->removable = !!params->removable[i];
3475 		lun->filename =
3476 			params->file_count > i && params->file[i][0]
3477 			? params->file[i]
3478 			: NULL;
3479 	}
3480 
3481 	/* Let MSF use defaults */
3482 	cfg->vendor_name = NULL;
3483 	cfg->product_name = NULL;
3484 
3485 	cfg->ops = NULL;
3486 	cfg->private_data = NULL;
3487 
3488 	/* Finalise */
3489 	cfg->can_stall = params->stall;
3490 	cfg->fsg_num_buffers = fsg_num_buffers;
3491 }
3492 EXPORT_SYMBOL_GPL(fsg_config_from_params);
3493