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