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