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