xref: /rk3399_rockchip-uboot/drivers/usb/gadget/f_mass_storage.c (revision fc5f56b20bd67fdd4bd9fa913b96bd3f3f2a0e99)
1 /*
2  * f_mass_storage.c -- Mass Storage USB Composite Function
3  *
4  * Copyright (C) 2003-2008 Alan Stern
5  * Copyright (C) 2009 Samsung Electronics
6  *                    Author: Michal Nazarewicz <m.nazarewicz@samsung.com>
7  * All rights reserved.
8  *
9  * SPDX-License-Identifier: GPL-2.0+	BSD-3-Clause
10  */
11 
12 /*
13  * The Mass Storage Function acts as a USB Mass Storage device,
14  * appearing to the host as a disk drive or as a CD-ROM drive.  In
15  * addition to providing an example of a genuinely useful composite
16  * function for a USB device, it also illustrates a technique of
17  * double-buffering for increased throughput.
18  *
19  * Function supports multiple logical units (LUNs).  Backing storage
20  * for each LUN is provided by a regular file or a block device.
21  * Access for each LUN can be limited to read-only.  Moreover, the
22  * function can indicate that LUN is removable and/or CD-ROM.  (The
23  * later implies read-only access.)
24  *
25  * MSF is configured by specifying a fsg_config structure.  It has the
26  * following fields:
27  *
28  *	nluns		Number of LUNs function have (anywhere from 1
29  *				to FSG_MAX_LUNS which is 8).
30  *	luns		An array of LUN configuration values.  This
31  *				should be filled for each LUN that
32  *				function will include (ie. for "nluns"
33  *				LUNs).  Each element of the array has
34  *				the following fields:
35  *	->filename	The path to the backing file for the LUN.
36  *				Required if LUN is not marked as
37  *				removable.
38  *	->ro		Flag specifying access to the LUN shall be
39  *				read-only.  This is implied if CD-ROM
40  *				emulation is enabled as well as when
41  *				it was impossible to open "filename"
42  *				in R/W mode.
43  *	->removable	Flag specifying that LUN shall be indicated as
44  *				being removable.
45  *	->cdrom		Flag specifying that LUN shall be reported as
46  *				being a CD-ROM.
47  *
48  *	lun_name_format	A printf-like format for names of the LUN
49  *				devices.  This determines how the
50  *				directory in sysfs will be named.
51  *				Unless you are using several MSFs in
52  *				a single gadget (as opposed to single
53  *				MSF in many configurations) you may
54  *				leave it as NULL (in which case
55  *				"lun%d" will be used).  In the format
56  *				you can use "%d" to index LUNs for
57  *				MSF's with more than one LUN.  (Beware
58  *				that there is only one integer given
59  *				as an argument for the format and
60  *				specifying invalid format may cause
61  *				unspecified behaviour.)
62  *	thread_name	Name of the kernel thread process used by the
63  *				MSF.  You can safely set it to NULL
64  *				(in which case default "file-storage"
65  *				will be used).
66  *
67  *	vendor_name
68  *	product_name
69  *	release		Information used as a reply to INQUIRY
70  *				request.  To use default set to NULL,
71  *				NULL, 0xffff respectively.  The first
72  *				field should be 8 and the second 16
73  *				characters or less.
74  *
75  *	can_stall	Set to permit function to halt bulk endpoints.
76  *				Disabled on some USB devices known not
77  *				to work correctly.  You should set it
78  *				to true.
79  *
80  * If "removable" is not set for a LUN then a backing file must be
81  * specified.  If it is set, then NULL filename means the LUN's medium
82  * is not loaded (an empty string as "filename" in the fsg_config
83  * structure causes error).  The CD-ROM emulation includes a single
84  * data track and no audio tracks; hence there need be only one
85  * backing file per LUN.  Note also that the CD-ROM block length is
86  * set to 512 rather than the more common value 2048.
87  *
88  *
89  * MSF includes support for module parameters.  If gadget using it
90  * decides to use it, the following module parameters will be
91  * available:
92  *
93  *	file=filename[,filename...]
94  *			Names of the files or block devices used for
95  *				backing storage.
96  *	ro=b[,b...]	Default false, boolean for read-only access.
97  *	removable=b[,b...]
98  *			Default true, boolean for removable media.
99  *	cdrom=b[,b...]	Default false, boolean for whether to emulate
100  *				a CD-ROM drive.
101  *	luns=N		Default N = number of filenames, number of
102  *				LUNs to support.
103  *	stall		Default determined according to the type of
104  *				USB device controller (usually true),
105  *				boolean to permit the driver to halt
106  *				bulk endpoints.
107  *
108  * The module parameters may be prefixed with some string.  You need
109  * to consult gadget's documentation or source to verify whether it is
110  * using those module parameters and if it does what are the prefixes
111  * (look for FSG_MODULE_PARAMETERS() macro usage, what's inside it is
112  * the prefix).
113  *
114  *
115  * Requirements are modest; only a bulk-in and a bulk-out endpoint are
116  * needed.  The memory requirement amounts to two 16K buffers, size
117  * configurable by a parameter.  Support is included for both
118  * full-speed and high-speed operation.
119  *
120  * Note that the driver is slightly non-portable in that it assumes a
121  * single memory/DMA buffer will be useable for bulk-in, bulk-out, and
122  * interrupt-in endpoints.  With most device controllers this isn't an
123  * issue, but there may be some with hardware restrictions that prevent
124  * a buffer from being used by more than one endpoint.
125  *
126  *
127  * The pathnames of the backing files and the ro settings are
128  * available in the attribute files "file" and "ro" in the lun<n> (or
129  * to be more precise in a directory which name comes from
130  * "lun_name_format" option!) subdirectory of the gadget's sysfs
131  * directory.  If the "removable" option is set, writing to these
132  * files will simulate ejecting/loading the medium (writing an empty
133  * line means eject) and adjusting a write-enable tab.  Changes to the
134  * ro setting are not allowed when the medium is loaded or if CD-ROM
135  * emulation is being used.
136  *
137  * When a LUN receive an "eject" SCSI request (Start/Stop Unit),
138  * if the LUN is removable, the backing file is released to simulate
139  * ejection.
140  *
141  *
142  * This function is heavily based on "File-backed Storage Gadget" by
143  * Alan Stern which in turn is heavily based on "Gadget Zero" by David
144  * Brownell.  The driver's SCSI command interface was based on the
145  * "Information technology - Small Computer System Interface - 2"
146  * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
147  * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
148  * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
149  * was based on the "Universal Serial Bus Mass Storage Class UFI
150  * Command Specification" document, Revision 1.0, December 14, 1998,
151  * available at
152  * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
153  */
154 
155 /*
156  *				Driver Design
157  *
158  * The MSF is fairly straightforward.  There is a main kernel
159  * thread that handles most of the work.  Interrupt routines field
160  * callbacks from the controller driver: bulk- and interrupt-request
161  * completion notifications, endpoint-0 events, and disconnect events.
162  * Completion events are passed to the main thread by wakeup calls.  Many
163  * ep0 requests are handled at interrupt time, but SetInterface,
164  * SetConfiguration, and device reset requests are forwarded to the
165  * thread in the form of "exceptions" using SIGUSR1 signals (since they
166  * should interrupt any ongoing file I/O operations).
167  *
168  * The thread's main routine implements the standard command/data/status
169  * parts of a SCSI interaction.  It and its subroutines are full of tests
170  * for pending signals/exceptions -- all this polling is necessary since
171  * the kernel has no setjmp/longjmp equivalents.  (Maybe this is an
172  * indication that the driver really wants to be running in userspace.)
173  * An important point is that so long as the thread is alive it keeps an
174  * open reference to the backing file.  This will prevent unmounting
175  * the backing file's underlying filesystem and could cause problems
176  * during system shutdown, for example.  To prevent such problems, the
177  * thread catches INT, TERM, and KILL signals and converts them into
178  * an EXIT exception.
179  *
180  * In normal operation the main thread is started during the gadget's
181  * fsg_bind() callback and stopped during fsg_unbind().  But it can
182  * also exit when it receives a signal, and there's no point leaving
183  * the gadget running when the thread is dead.  At of this moment, MSF
184  * provides no way to deregister the gadget when thread dies -- maybe
185  * a callback functions is needed.
186  *
187  * To provide maximum throughput, the driver uses a circular pipeline of
188  * buffer heads (struct fsg_buffhd).  In principle the pipeline can be
189  * arbitrarily long; in practice the benefits don't justify having more
190  * than 2 stages (i.e., double buffering).  But it helps to think of the
191  * pipeline as being a long one.  Each buffer head contains a bulk-in and
192  * a bulk-out request pointer (since the buffer can be used for both
193  * output and input -- directions always are given from the host's
194  * point of view) as well as a pointer to the buffer and various state
195  * variables.
196  *
197  * Use of the pipeline follows a simple protocol.  There is a variable
198  * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
199  * At any time that buffer head may still be in use from an earlier
200  * request, so each buffer head has a state variable indicating whether
201  * it is EMPTY, FULL, or BUSY.  Typical use involves waiting for the
202  * buffer head to be EMPTY, filling the buffer either by file I/O or by
203  * USB I/O (during which the buffer head is BUSY), and marking the buffer
204  * head FULL when the I/O is complete.  Then the buffer will be emptied
205  * (again possibly by USB I/O, during which it is marked BUSY) and
206  * finally marked EMPTY again (possibly by a completion routine).
207  *
208  * A module parameter tells the driver to avoid stalling the bulk
209  * endpoints wherever the transport specification allows.  This is
210  * necessary for some UDCs like the SuperH, which cannot reliably clear a
211  * halt on a bulk endpoint.  However, under certain circumstances the
212  * Bulk-only specification requires a stall.  In such cases the driver
213  * will halt the endpoint and set a flag indicating that it should clear
214  * the halt in software during the next device reset.  Hopefully this
215  * will permit everything to work correctly.  Furthermore, although the
216  * specification allows the bulk-out endpoint to halt when the host sends
217  * too much data, implementing this would cause an unavoidable race.
218  * The driver will always use the "no-stall" approach for OUT transfers.
219  *
220  * One subtle point concerns sending status-stage responses for ep0
221  * requests.  Some of these requests, such as device reset, can involve
222  * interrupting an ongoing file I/O operation, which might take an
223  * arbitrarily long time.  During that delay the host might give up on
224  * the original ep0 request and issue a new one.  When that happens the
225  * driver should not notify the host about completion of the original
226  * request, as the host will no longer be waiting for it.  So the driver
227  * assigns to each ep0 request a unique tag, and it keeps track of the
228  * tag value of the request associated with a long-running exception
229  * (device-reset, interface-change, or configuration-change).  When the
230  * exception handler is finished, the status-stage response is submitted
231  * only if the current ep0 request tag is equal to the exception request
232  * tag.  Thus only the most recently received ep0 request will get a
233  * status-stage response.
234  *
235  * Warning: This driver source file is too long.  It ought to be split up
236  * into a header file plus about 3 separate .c files, to handle the details
237  * of the Gadget, USB Mass Storage, and SCSI protocols.
238  */
239 
240 /* #define VERBOSE_DEBUG */
241 /* #define DUMP_MSGS */
242 
243 #include <config.h>
244 #include <hexdump.h>
245 #include <malloc.h>
246 #include <common.h>
247 #include <console.h>
248 #include <g_dnl.h>
249 
250 #include <linux/err.h>
251 #include <linux/usb/ch9.h>
252 #include <linux/usb/gadget.h>
253 #include <usb_mass_storage.h>
254 #include <rockusb.h>
255 
256 #include <asm/unaligned.h>
257 #include <linux/bitops.h>
258 #include <linux/usb/gadget.h>
259 #include <linux/usb/gadget.h>
260 #include <linux/usb/composite.h>
261 #include <linux/bitmap.h>
262 #include <g_dnl.h>
263 
264 /*------------------------------------------------------------------------*/
265 
266 #define FSG_DRIVER_DESC	"Mass Storage Function"
267 #define FSG_DRIVER_VERSION	"2012/06/5"
268 
269 static const char fsg_string_interface[] = "Mass Storage";
270 
271 #define FSG_NO_INTR_EP 1
272 #define FSG_NO_DEVICE_STRINGS    1
273 #define FSG_NO_OTG               1
274 #define FSG_NO_INTR_EP           1
275 
276 #include "storage_common.c"
277 
278 /*-------------------------------------------------------------------------*/
279 
280 #define GFP_ATOMIC ((gfp_t) 0)
281 #define PAGE_CACHE_SHIFT	12
282 #define PAGE_CACHE_SIZE		(1 << PAGE_CACHE_SHIFT)
283 #define kthread_create(...)	__builtin_return_address(0)
284 #define wait_for_completion(...) do {} while (0)
285 
286 struct kref {int x; };
287 struct completion {int x; };
288 
289 struct fsg_dev;
290 struct fsg_common;
291 
292 /* Data shared by all the FSG instances. */
293 struct fsg_common {
294 	struct usb_gadget	*gadget;
295 	struct fsg_dev		*fsg, *new_fsg;
296 
297 	struct usb_ep		*ep0;		/* Copy of gadget->ep0 */
298 	struct usb_request	*ep0req;	/* Copy of cdev->req */
299 	unsigned int		ep0_req_tag;
300 
301 	struct fsg_buffhd	*next_buffhd_to_fill;
302 	struct fsg_buffhd	*next_buffhd_to_drain;
303 	struct fsg_buffhd	buffhds[FSG_NUM_BUFFERS];
304 
305 	int			cmnd_size;
306 	u8			cmnd[MAX_COMMAND_SIZE];
307 
308 	unsigned int		nluns;
309 	unsigned int		lun;
310 	struct fsg_lun          luns[FSG_MAX_LUNS];
311 
312 	unsigned int		bulk_out_maxpacket;
313 	enum fsg_state		state;		/* For exception handling */
314 	unsigned int		exception_req_tag;
315 
316 	enum data_direction	data_dir;
317 	u32			data_size;
318 	u32			data_size_from_cmnd;
319 	u32			tag;
320 	u32			residue;
321 	u32			usb_amount_left;
322 
323 	unsigned int		can_stall:1;
324 	unsigned int		free_storage_on_release:1;
325 	unsigned int		phase_error:1;
326 	unsigned int		short_packet_received:1;
327 	unsigned int		bad_lun_okay:1;
328 	unsigned int		running:1;
329 
330 	int			thread_wakeup_needed;
331 	struct completion	thread_notifier;
332 	struct task_struct	*thread_task;
333 
334 	/* Callback functions. */
335 	const struct fsg_operations	*ops;
336 	/* Gadget's private data. */
337 	void			*private_data;
338 
339 	const char *vendor_name;		/*  8 characters or less */
340 	const char *product_name;		/* 16 characters or less */
341 	u16 release;
342 
343 	/* Vendor (8 chars), product (16 chars), release (4
344 	 * hexadecimal digits) and NUL byte */
345 	char inquiry_string[8 + 16 + 4 + 1];
346 
347 	struct kref		ref;
348 };
349 
350 struct fsg_config {
351 	unsigned nluns;
352 	struct fsg_lun_config {
353 		const char *filename;
354 		char ro;
355 		char removable;
356 		char cdrom;
357 		char nofua;
358 	} luns[FSG_MAX_LUNS];
359 
360 	/* Callback functions. */
361 	const struct fsg_operations     *ops;
362 	/* Gadget's private data. */
363 	void			*private_data;
364 
365 	const char *vendor_name;		/*  8 characters or less */
366 	const char *product_name;		/* 16 characters or less */
367 
368 	char			can_stall;
369 };
370 
371 struct fsg_dev {
372 	struct usb_function	function;
373 	struct usb_gadget	*gadget;	/* Copy of cdev->gadget */
374 	struct fsg_common	*common;
375 
376 	u16			interface_number;
377 
378 	unsigned int		bulk_in_enabled:1;
379 	unsigned int		bulk_out_enabled:1;
380 
381 	unsigned long		atomic_bitflags;
382 #define IGNORE_BULK_OUT		0
383 
384 	struct usb_ep		*bulk_in;
385 	struct usb_ep		*bulk_out;
386 };
387 
388 
389 static inline int __fsg_is_set(struct fsg_common *common,
390 			       const char *func, unsigned line)
391 {
392 	if (common->fsg)
393 		return 1;
394 	ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
395 	WARN_ON(1);
396 	return 0;
397 }
398 
399 #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
400 
401 
402 static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
403 {
404 	return container_of(f, struct fsg_dev, function);
405 }
406 
407 
408 typedef void (*fsg_routine_t)(struct fsg_dev *);
409 
410 static int exception_in_progress(struct fsg_common *common)
411 {
412 	return common->state > FSG_STATE_IDLE;
413 }
414 
415 /* Make bulk-out requests be divisible by the maxpacket size */
416 static void set_bulk_out_req_length(struct fsg_common *common,
417 		struct fsg_buffhd *bh, unsigned int length)
418 {
419 	unsigned int	rem;
420 
421 	bh->bulk_out_intended_length = length;
422 	rem = length % common->bulk_out_maxpacket;
423 	if (rem > 0)
424 		length += common->bulk_out_maxpacket - rem;
425 	bh->outreq->length = length;
426 }
427 
428 /*-------------------------------------------------------------------------*/
429 
430 static struct ums *ums;
431 static int ums_count;
432 static struct fsg_common *the_fsg_common;
433 
434 static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
435 {
436 	const char	*name;
437 
438 	if (ep == fsg->bulk_in)
439 		name = "bulk-in";
440 	else if (ep == fsg->bulk_out)
441 		name = "bulk-out";
442 	else
443 		name = ep->name;
444 	DBG(fsg, "%s set halt\n", name);
445 	return usb_ep_set_halt(ep);
446 }
447 
448 /*-------------------------------------------------------------------------*/
449 
450 /* These routines may be called in process context or in_irq */
451 
452 /* Caller must hold fsg->lock */
453 static void wakeup_thread(struct fsg_common *common)
454 {
455 	common->thread_wakeup_needed = 1;
456 }
457 
458 static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
459 {
460 	/* Do nothing if a higher-priority exception is already in progress.
461 	 * If a lower-or-equal priority exception is in progress, preempt it
462 	 * and notify the main thread by sending it a signal. */
463 	if (common->state <= new_state) {
464 		common->exception_req_tag = common->ep0_req_tag;
465 		common->state = new_state;
466 		common->thread_wakeup_needed = 1;
467 	}
468 }
469 
470 /*-------------------------------------------------------------------------*/
471 
472 static int ep0_queue(struct fsg_common *common)
473 {
474 	int	rc;
475 
476 	rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
477 	common->ep0->driver_data = common;
478 	if (rc != 0 && rc != -ESHUTDOWN) {
479 		/* We can't do much more than wait for a reset */
480 		WARNING(common, "error in submission: %s --> %d\n",
481 			common->ep0->name, rc);
482 	}
483 	return rc;
484 }
485 
486 /*-------------------------------------------------------------------------*/
487 
488 /* Bulk and interrupt endpoint completion handlers.
489  * These always run in_irq. */
490 
491 static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
492 {
493 	struct fsg_common	*common = ep->driver_data;
494 	struct fsg_buffhd	*bh = req->context;
495 
496 	if (req->status || req->actual != req->length)
497 		DBG(common, "%s --> %d, %u/%u\n", __func__,
498 				req->status, req->actual, req->length);
499 	if (req->status == -ECONNRESET)		/* Request was cancelled */
500 		usb_ep_fifo_flush(ep);
501 
502 	/* Hold the lock while we update the request and buffer states */
503 	bh->inreq_busy = 0;
504 	bh->state = BUF_STATE_EMPTY;
505 	wakeup_thread(common);
506 }
507 
508 static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
509 {
510 	struct fsg_common	*common = ep->driver_data;
511 	struct fsg_buffhd	*bh = req->context;
512 
513 	dump_msg(common, "bulk-out", req->buf, req->actual);
514 	if (req->status || req->actual != bh->bulk_out_intended_length)
515 		DBG(common, "%s --> %d, %u/%u\n", __func__,
516 				req->status, req->actual,
517 				bh->bulk_out_intended_length);
518 	if (req->status == -ECONNRESET)		/* Request was cancelled */
519 		usb_ep_fifo_flush(ep);
520 
521 	/* Hold the lock while we update the request and buffer states */
522 	bh->outreq_busy = 0;
523 	bh->state = BUF_STATE_FULL;
524 	wakeup_thread(common);
525 }
526 
527 /*-------------------------------------------------------------------------*/
528 
529 /* Ep0 class-specific handlers.  These always run in_irq. */
530 
531 static int fsg_setup(struct usb_function *f,
532 		const struct usb_ctrlrequest *ctrl)
533 {
534 	struct fsg_dev		*fsg = fsg_from_func(f);
535 	struct usb_request	*req = fsg->common->ep0req;
536 	u16			w_index = get_unaligned_le16(&ctrl->wIndex);
537 	u16			w_value = get_unaligned_le16(&ctrl->wValue);
538 	u16			w_length = get_unaligned_le16(&ctrl->wLength);
539 
540 	if (!fsg_is_set(fsg->common))
541 		return -EOPNOTSUPP;
542 
543 	switch (ctrl->bRequest) {
544 
545 	case USB_BULK_RESET_REQUEST:
546 		if (ctrl->bRequestType !=
547 		    (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
548 			break;
549 		if (w_index != fsg->interface_number || w_value != 0)
550 			return -EDOM;
551 
552 		/* Raise an exception to stop the current operation
553 		 * and reinitialize our state. */
554 		DBG(fsg, "bulk reset request\n");
555 		raise_exception(fsg->common, FSG_STATE_RESET);
556 		return DELAYED_STATUS;
557 
558 	case USB_BULK_GET_MAX_LUN_REQUEST:
559 		if (ctrl->bRequestType !=
560 		    (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
561 			break;
562 		if (w_index != fsg->interface_number || w_value != 0)
563 			return -EDOM;
564 		VDBG(fsg, "get max LUN\n");
565 		*(u8 *) req->buf = fsg->common->nluns - 1;
566 
567 		/* Respond with data/status */
568 		req->length = min((u16)1, w_length);
569 		return ep0_queue(fsg->common);
570 	}
571 
572 	VDBG(fsg,
573 	     "unknown class-specific control req "
574 	     "%02x.%02x v%04x i%04x l%u\n",
575 	     ctrl->bRequestType, ctrl->bRequest,
576 	     get_unaligned_le16(&ctrl->wValue), w_index, w_length);
577 	return -EOPNOTSUPP;
578 }
579 
580 /*-------------------------------------------------------------------------*/
581 
582 /* All the following routines run in process context */
583 
584 /* Use this for bulk or interrupt transfers, not ep0 */
585 static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
586 		struct usb_request *req, int *pbusy,
587 		enum fsg_buffer_state *state)
588 {
589 	int	rc;
590 
591 	if (ep == fsg->bulk_in)
592 		dump_msg(fsg, "bulk-in", req->buf, req->length);
593 
594 	*pbusy = 1;
595 	*state = BUF_STATE_BUSY;
596 	rc = usb_ep_queue(ep, req, GFP_KERNEL);
597 	if (rc != 0) {
598 		*pbusy = 0;
599 		*state = BUF_STATE_EMPTY;
600 
601 		/* We can't do much more than wait for a reset */
602 
603 		/* Note: currently the net2280 driver fails zero-length
604 		 * submissions if DMA is enabled. */
605 		if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP &&
606 						req->length == 0))
607 			WARNING(fsg, "error in submission: %s --> %d\n",
608 					ep->name, rc);
609 	}
610 }
611 
612 #define START_TRANSFER_OR(common, ep_name, req, pbusy, state)		\
613 	if (fsg_is_set(common))						\
614 		start_transfer((common)->fsg, (common)->fsg->ep_name,	\
615 			       req, pbusy, state);			\
616 	else
617 
618 #define START_TRANSFER(common, ep_name, req, pbusy, state)		\
619 	START_TRANSFER_OR(common, ep_name, req, pbusy, state) (void)0
620 
621 static void busy_indicator(void)
622 {
623 	static int state;
624 
625 	switch (state) {
626 	case 0:
627 		puts("\r|"); break;
628 	case 1:
629 		puts("\r/"); break;
630 	case 2:
631 		puts("\r-"); break;
632 	case 3:
633 		puts("\r\\"); break;
634 	case 4:
635 		puts("\r|"); break;
636 	case 5:
637 		puts("\r/"); break;
638 	case 6:
639 		puts("\r-"); break;
640 	case 7:
641 		puts("\r\\"); break;
642 	default:
643 		state = 0;
644 	}
645 	if (state++ == 8)
646 		state = 0;
647 }
648 
649 static int sleep_thread(struct fsg_common *common)
650 {
651 	int	rc = 0;
652 	int i = 0, k = 0;
653 
654 	/* Wait until a signal arrives or we are woken up */
655 	for (;;) {
656 		if (common->thread_wakeup_needed)
657 			break;
658 
659 		if (++i == 20000) {
660 			busy_indicator();
661 			i = 0;
662 			k++;
663 		}
664 
665 		if (k == 10) {
666 			/* Handle CTRL+C */
667 			if (ctrlc())
668 				return -EPIPE;
669 
670 			/* Check cable connection */
671 			if (!g_dnl_board_usb_cable_connected())
672 				return -EIO;
673 
674 			k = 0;
675 		}
676 
677 #ifdef CONFIG_USB_DWC3_GADGET
678 		if (rkusb_usb3_capable() && !dwc3_gadget_is_connected())
679 			return -ENODEV;
680 #endif
681 
682 		usb_gadget_handle_interrupts(0);
683 	}
684 	common->thread_wakeup_needed = 0;
685 	return rc;
686 }
687 
688 /*-------------------------------------------------------------------------*/
689 
690 static int do_read(struct fsg_common *common)
691 {
692 	struct fsg_lun		*curlun = &common->luns[common->lun];
693 	u32			lba;
694 	struct fsg_buffhd	*bh;
695 	int			rc;
696 	u32			amount_left;
697 	loff_t			file_offset;
698 	unsigned int		amount;
699 	unsigned int		partial_page;
700 	ssize_t			nread;
701 
702 	/* Get the starting Logical Block Address and check that it's
703 	 * not too big */
704 	if (common->cmnd[0] == SC_READ_6)
705 		lba = get_unaligned_be24(&common->cmnd[1]);
706 	else {
707 		lba = get_unaligned_be32(&common->cmnd[2]);
708 
709 		/* We allow DPO (Disable Page Out = don't save data in the
710 		 * cache) and FUA (Force Unit Access = don't read from the
711 		 * cache), but we don't implement them. */
712 		if ((common->cmnd[1] & ~0x18) != 0) {
713 			curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
714 			return -EINVAL;
715 		}
716 	}
717 	if (lba >= curlun->num_sectors) {
718 		curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
719 		return -EINVAL;
720 	}
721 	file_offset = ((loff_t) lba) << 9;
722 
723 	/* Carry out the file reads */
724 	amount_left = common->data_size_from_cmnd;
725 	if (unlikely(amount_left == 0))
726 		return -EIO;		/* No default reply */
727 
728 	for (;;) {
729 
730 		/* Figure out how much we need to read:
731 		 * Try to read the remaining amount.
732 		 * But don't read more than the buffer size.
733 		 * And don't try to read past the end of the file.
734 		 * Finally, if we're not at a page boundary, don't read past
735 		 *	the next page.
736 		 * If this means reading 0 then we were asked to read past
737 		 *	the end of file. */
738 		amount = min(amount_left, FSG_BUFLEN);
739 		partial_page = file_offset & (PAGE_CACHE_SIZE - 1);
740 		if (partial_page > 0)
741 			amount = min(amount, (unsigned int) PAGE_CACHE_SIZE -
742 					partial_page);
743 
744 		/* Wait for the next buffer to become available */
745 		bh = common->next_buffhd_to_fill;
746 		while (bh->state != BUF_STATE_EMPTY) {
747 			rc = sleep_thread(common);
748 			if (rc)
749 				return rc;
750 		}
751 
752 		/* If we were asked to read past the end of file,
753 		 * end with an empty buffer. */
754 		if (amount == 0) {
755 			curlun->sense_data =
756 					SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
757 			curlun->info_valid = 1;
758 			bh->inreq->length = 0;
759 			bh->state = BUF_STATE_FULL;
760 			break;
761 		}
762 
763 		/* Perform the read */
764 		rc = ums[common->lun].read_sector(&ums[common->lun],
765 				      file_offset / SECTOR_SIZE,
766 				      amount / SECTOR_SIZE,
767 				      (char __user *)bh->buf);
768 		if (!rc)
769 			return -EIO;
770 
771 		nread = rc * SECTOR_SIZE;
772 
773 		VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
774 				(unsigned long long) file_offset,
775 				(int) nread);
776 
777 		if (nread < 0) {
778 			LDBG(curlun, "error in file read: %d\n",
779 					(int) nread);
780 			nread = 0;
781 		} else if (nread < amount) {
782 			LDBG(curlun, "partial file read: %d/%u\n",
783 					(int) nread, amount);
784 			nread -= (nread & 511);	/* Round down to a block */
785 		}
786 		file_offset  += nread;
787 		amount_left  -= nread;
788 		common->residue -= nread;
789 		bh->inreq->length = nread;
790 		bh->state = BUF_STATE_FULL;
791 
792 		/* If an error occurred, report it and its position */
793 		if (nread < amount) {
794 			curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
795 			curlun->info_valid = 1;
796 			break;
797 		}
798 
799 		if (amount_left == 0)
800 			break;		/* No more left to read */
801 
802 		/* Send this buffer and go read some more */
803 		bh->inreq->zero = 0;
804 		START_TRANSFER_OR(common, bulk_in, bh->inreq,
805 			       &bh->inreq_busy, &bh->state)
806 			/* Don't know what to do if
807 			 * common->fsg is NULL */
808 			return -EIO;
809 		common->next_buffhd_to_fill = bh->next;
810 	}
811 
812 	return -EIO;		/* No default reply */
813 }
814 
815 /*-------------------------------------------------------------------------*/
816 
817 static int do_write(struct fsg_common *common)
818 {
819 	struct fsg_lun		*curlun = &common->luns[common->lun];
820 	u32			lba;
821 	struct fsg_buffhd	*bh;
822 	int			get_some_more;
823 	u32			amount_left_to_req, amount_left_to_write;
824 	loff_t			usb_offset, file_offset;
825 	unsigned int		amount;
826 	unsigned int		partial_page;
827 	ssize_t			nwritten;
828 	int			rc;
829 	const char		*cdev_name __maybe_unused;
830 
831 	if (curlun->ro) {
832 		curlun->sense_data = SS_WRITE_PROTECTED;
833 		return -EINVAL;
834 	}
835 
836 	/* Get the starting Logical Block Address and check that it's
837 	 * not too big */
838 	if (common->cmnd[0] == SC_WRITE_6)
839 		lba = get_unaligned_be24(&common->cmnd[1]);
840 	else {
841 		lba = get_unaligned_be32(&common->cmnd[2]);
842 
843 		/* We allow DPO (Disable Page Out = don't save data in the
844 		 * cache) and FUA (Force Unit Access = write directly to the
845 		 * medium).  We don't implement DPO; we implement FUA by
846 		 * performing synchronous output. */
847 		if (common->cmnd[1] & ~0x18) {
848 			curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
849 			return -EINVAL;
850 		}
851 	}
852 	if (lba >= curlun->num_sectors) {
853 		curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
854 		return -EINVAL;
855 	}
856 
857 	/* Carry out the file writes */
858 	get_some_more = 1;
859 	file_offset = usb_offset = ((loff_t) lba) << 9;
860 	amount_left_to_req = common->data_size_from_cmnd;
861 	amount_left_to_write = common->data_size_from_cmnd;
862 
863 	while (amount_left_to_write > 0) {
864 
865 		/* Queue a request for more data from the host */
866 		bh = common->next_buffhd_to_fill;
867 		if (bh->state == BUF_STATE_EMPTY && get_some_more) {
868 
869 			/* Figure out how much we want to get:
870 			 * Try to get the remaining amount.
871 			 * But don't get more than the buffer size.
872 			 * And don't try to go past the end of the file.
873 			 * If we're not at a page boundary,
874 			 *	don't go past the next page.
875 			 * If this means getting 0, then we were asked
876 			 *	to write past the end of file.
877 			 * Finally, round down to a block boundary. */
878 			amount = min(amount_left_to_req, FSG_BUFLEN);
879 			partial_page = usb_offset & (PAGE_CACHE_SIZE - 1);
880 			if (partial_page > 0)
881 				amount = min(amount,
882 	(unsigned int) PAGE_CACHE_SIZE - partial_page);
883 
884 			if (amount == 0) {
885 				get_some_more = 0;
886 				curlun->sense_data =
887 					SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
888 				curlun->info_valid = 1;
889 				continue;
890 			}
891 			amount -= (amount & 511);
892 			if (amount == 0) {
893 
894 				/* Why were we were asked to transfer a
895 				 * partial block? */
896 				get_some_more = 0;
897 				continue;
898 			}
899 
900 			/* Get the next buffer */
901 			usb_offset += amount;
902 			common->usb_amount_left -= amount;
903 			amount_left_to_req -= amount;
904 			if (amount_left_to_req == 0)
905 				get_some_more = 0;
906 
907 			/* amount is always divisible by 512, hence by
908 			 * the bulk-out maxpacket size */
909 			bh->outreq->length = amount;
910 			bh->bulk_out_intended_length = amount;
911 			bh->outreq->short_not_ok = 1;
912 			START_TRANSFER_OR(common, bulk_out, bh->outreq,
913 					  &bh->outreq_busy, &bh->state)
914 				/* Don't know what to do if
915 				 * common->fsg is NULL */
916 				return -EIO;
917 			common->next_buffhd_to_fill = bh->next;
918 			continue;
919 		}
920 
921 		/* Write the received data to the backing file */
922 		bh = common->next_buffhd_to_drain;
923 		if (bh->state == BUF_STATE_EMPTY && !get_some_more)
924 			break;			/* We stopped early */
925 		if (bh->state == BUF_STATE_FULL) {
926 			common->next_buffhd_to_drain = bh->next;
927 			bh->state = BUF_STATE_EMPTY;
928 
929 			/* Did something go wrong with the transfer? */
930 			if (bh->outreq->status != 0) {
931 				curlun->sense_data = SS_COMMUNICATION_FAILURE;
932 				curlun->info_valid = 1;
933 				break;
934 			}
935 
936 			amount = bh->outreq->actual;
937 
938 			/* Perform the write */
939 			rc = ums[common->lun].write_sector(&ums[common->lun],
940 					       file_offset / SECTOR_SIZE,
941 					       amount / SECTOR_SIZE,
942 					       (char __user *)bh->buf);
943 			if (!rc)
944 				return -EIO;
945 			nwritten = rc * SECTOR_SIZE;
946 
947 			VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
948 					(unsigned long long) file_offset,
949 					(int) nwritten);
950 
951 			if (nwritten < 0) {
952 				LDBG(curlun, "error in file write: %d\n",
953 						(int) nwritten);
954 				nwritten = 0;
955 			} else if (nwritten < amount) {
956 				LDBG(curlun, "partial file write: %d/%u\n",
957 						(int) nwritten, amount);
958 				nwritten -= (nwritten & 511);
959 				/* Round down to a block */
960 			}
961 			file_offset += nwritten;
962 			amount_left_to_write -= nwritten;
963 			common->residue -= nwritten;
964 
965 			/* If an error occurred, report it and its position */
966 			if (nwritten < amount) {
967 				printf("nwritten:%zd amount:%u\n", nwritten,
968 				       amount);
969 				curlun->sense_data = SS_WRITE_ERROR;
970 				curlun->info_valid = 1;
971 				break;
972 			}
973 
974 			/* Did the host decide to stop early? */
975 			if (bh->outreq->actual != bh->outreq->length) {
976 				common->short_packet_received = 1;
977 				break;
978 			}
979 			continue;
980 		}
981 
982 		/* Wait for something to happen */
983 		rc = sleep_thread(common);
984 		if (rc)
985 			return rc;
986 	}
987 
988 	cdev_name = common->fsg->function.config->cdev->driver->name;
989 	if (IS_RKUSB_UMS_DNL(cdev_name))
990 		rkusb_do_check_parity(common);
991 
992 	return -EIO;		/* No default reply */
993 }
994 
995 /*-------------------------------------------------------------------------*/
996 
997 static int do_synchronize_cache(struct fsg_common *common)
998 {
999 	return 0;
1000 }
1001 
1002 /*-------------------------------------------------------------------------*/
1003 
1004 static int do_verify(struct fsg_common *common)
1005 {
1006 	struct fsg_lun		*curlun = &common->luns[common->lun];
1007 	u32			lba;
1008 	u32			verification_length;
1009 	struct fsg_buffhd	*bh = common->next_buffhd_to_fill;
1010 	loff_t			file_offset;
1011 	u32			amount_left;
1012 	unsigned int		amount;
1013 	ssize_t			nread;
1014 	int			rc;
1015 
1016 	/* Get the starting Logical Block Address and check that it's
1017 	 * not too big */
1018 	lba = get_unaligned_be32(&common->cmnd[2]);
1019 	if (lba >= curlun->num_sectors) {
1020 		curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1021 		return -EINVAL;
1022 	}
1023 
1024 	/* We allow DPO (Disable Page Out = don't save data in the
1025 	 * cache) but we don't implement it. */
1026 	if (common->cmnd[1] & ~0x10) {
1027 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1028 		return -EINVAL;
1029 	}
1030 
1031 	verification_length = get_unaligned_be16(&common->cmnd[7]);
1032 	if (unlikely(verification_length == 0))
1033 		return -EIO;		/* No default reply */
1034 
1035 	/* Prepare to carry out the file verify */
1036 	amount_left = verification_length << 9;
1037 	file_offset = ((loff_t) lba) << 9;
1038 
1039 	/* Write out all the dirty buffers before invalidating them */
1040 
1041 	/* Just try to read the requested blocks */
1042 	while (amount_left > 0) {
1043 
1044 		/* Figure out how much we need to read:
1045 		 * Try to read the remaining amount, but not more than
1046 		 * the buffer size.
1047 		 * And don't try to read past the end of the file.
1048 		 * If this means reading 0 then we were asked to read
1049 		 * past the end of file. */
1050 		amount = min(amount_left, FSG_BUFLEN);
1051 		if (amount == 0) {
1052 			curlun->sense_data =
1053 					SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1054 			curlun->info_valid = 1;
1055 			break;
1056 		}
1057 
1058 		/* Perform the read */
1059 		rc = ums[common->lun].read_sector(&ums[common->lun],
1060 				      file_offset / SECTOR_SIZE,
1061 				      amount / SECTOR_SIZE,
1062 				      (char __user *)bh->buf);
1063 		if (!rc)
1064 			return -EIO;
1065 		nread = rc * SECTOR_SIZE;
1066 
1067 		VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1068 				(unsigned long long) file_offset,
1069 				(int) nread);
1070 		if (nread < 0) {
1071 			LDBG(curlun, "error in file verify: %d\n",
1072 					(int) nread);
1073 			nread = 0;
1074 		} else if (nread < amount) {
1075 			LDBG(curlun, "partial file verify: %d/%u\n",
1076 					(int) nread, amount);
1077 			nread -= (nread & 511);	/* Round down to a sector */
1078 		}
1079 		if (nread == 0) {
1080 			curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1081 			curlun->info_valid = 1;
1082 			break;
1083 		}
1084 		file_offset += nread;
1085 		amount_left -= nread;
1086 	}
1087 	return 0;
1088 }
1089 
1090 /*-------------------------------------------------------------------------*/
1091 
1092 static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1093 {
1094 	struct fsg_lun *curlun = &common->luns[common->lun];
1095 	static const char vendor_id[] = "Linux   ";
1096 	u8	*buf = (u8 *) bh->buf;
1097 
1098 	if (!curlun) {		/* Unsupported LUNs are okay */
1099 		common->bad_lun_okay = 1;
1100 		memset(buf, 0, 36);
1101 		buf[0] = 0x7f;		/* Unsupported, no device-type */
1102 		buf[4] = 31;		/* Additional length */
1103 		return 36;
1104 	}
1105 
1106 	memset(buf, 0, 8);
1107 	buf[0] = TYPE_DISK;
1108 	buf[1] = curlun->removable ? 0x80 : 0;
1109 	buf[2] = 2;		/* ANSI SCSI level 2 */
1110 	buf[3] = 2;		/* SCSI-2 INQUIRY data format */
1111 	buf[4] = 31;		/* Additional length */
1112 				/* No special options */
1113 	sprintf((char *) (buf + 8), "%-8s%-16s%04x", (char*) vendor_id ,
1114 			ums[common->lun].name, (u16) 0xffff);
1115 
1116 	return 36;
1117 }
1118 
1119 
1120 static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1121 {
1122 	struct fsg_lun	*curlun = &common->luns[common->lun];
1123 	u8		*buf = (u8 *) bh->buf;
1124 	u32		sd, sdinfo;
1125 	int		valid;
1126 
1127 	/*
1128 	 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1129 	 *
1130 	 * If a REQUEST SENSE command is received from an initiator
1131 	 * with a pending unit attention condition (before the target
1132 	 * generates the contingent allegiance condition), then the
1133 	 * target shall either:
1134 	 *   a) report any pending sense data and preserve the unit
1135 	 *	attention condition on the logical unit, or,
1136 	 *   b) report the unit attention condition, may discard any
1137 	 *	pending sense data, and clear the unit attention
1138 	 *	condition on the logical unit for that initiator.
1139 	 *
1140 	 * FSG normally uses option a); enable this code to use option b).
1141 	 */
1142 #if 0
1143 	if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1144 		curlun->sense_data = curlun->unit_attention_data;
1145 		curlun->unit_attention_data = SS_NO_SENSE;
1146 	}
1147 #endif
1148 
1149 	if (!curlun) {		/* Unsupported LUNs are okay */
1150 		common->bad_lun_okay = 1;
1151 		sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1152 		sdinfo = 0;
1153 		valid = 0;
1154 	} else {
1155 		sd = curlun->sense_data;
1156 		valid = curlun->info_valid << 7;
1157 		curlun->sense_data = SS_NO_SENSE;
1158 		curlun->info_valid = 0;
1159 	}
1160 
1161 	memset(buf, 0, 18);
1162 	buf[0] = valid | 0x70;			/* Valid, current error */
1163 	buf[2] = SK(sd);
1164 	put_unaligned_be32(sdinfo, &buf[3]);	/* Sense information */
1165 	buf[7] = 18 - 8;			/* Additional sense length */
1166 	buf[12] = ASC(sd);
1167 	buf[13] = ASCQ(sd);
1168 	return 18;
1169 }
1170 
1171 static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1172 {
1173 	struct fsg_lun	*curlun = &common->luns[common->lun];
1174 	u32		lba = get_unaligned_be32(&common->cmnd[2]);
1175 	int		pmi = common->cmnd[8];
1176 	u8		*buf = (u8 *) bh->buf;
1177 
1178 	/* Check the PMI and LBA fields */
1179 	if (pmi > 1 || (pmi == 0 && lba != 0)) {
1180 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1181 		return -EINVAL;
1182 	}
1183 
1184 	put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1185 						/* Max logical block */
1186 	put_unaligned_be32(512, &buf[4]);	/* Block length */
1187 	return 8;
1188 }
1189 
1190 static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1191 {
1192 	struct fsg_lun	*curlun = &common->luns[common->lun];
1193 	int		msf = common->cmnd[1] & 0x02;
1194 	u32		lba = get_unaligned_be32(&common->cmnd[2]);
1195 	u8		*buf = (u8 *) bh->buf;
1196 
1197 	if (common->cmnd[1] & ~0x02) {		/* Mask away MSF */
1198 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1199 		return -EINVAL;
1200 	}
1201 	if (lba >= curlun->num_sectors) {
1202 		curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1203 		return -EINVAL;
1204 	}
1205 
1206 	memset(buf, 0, 8);
1207 	buf[0] = 0x01;		/* 2048 bytes of user data, rest is EC */
1208 	store_cdrom_address(&buf[4], msf, lba);
1209 	return 8;
1210 }
1211 
1212 
1213 static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1214 {
1215 	struct fsg_lun	*curlun = &common->luns[common->lun];
1216 	int		msf = common->cmnd[1] & 0x02;
1217 	int		start_track = common->cmnd[6];
1218 	u8		*buf = (u8 *) bh->buf;
1219 
1220 	if ((common->cmnd[1] & ~0x02) != 0 ||	/* Mask away MSF */
1221 			start_track > 1) {
1222 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1223 		return -EINVAL;
1224 	}
1225 
1226 	memset(buf, 0, 20);
1227 	buf[1] = (20-2);		/* TOC data length */
1228 	buf[2] = 1;			/* First track number */
1229 	buf[3] = 1;			/* Last track number */
1230 	buf[5] = 0x16;			/* Data track, copying allowed */
1231 	buf[6] = 0x01;			/* Only track is number 1 */
1232 	store_cdrom_address(&buf[8], msf, 0);
1233 
1234 	buf[13] = 0x16;			/* Lead-out track is data */
1235 	buf[14] = 0xAA;			/* Lead-out track number */
1236 	store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1237 
1238 	return 20;
1239 }
1240 
1241 static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1242 {
1243 	struct fsg_lun	*curlun = &common->luns[common->lun];
1244 	int		mscmnd = common->cmnd[0];
1245 	u8		*buf = (u8 *) bh->buf;
1246 	u8		*buf0 = buf;
1247 	int		pc, page_code;
1248 	int		changeable_values, all_pages;
1249 	int		valid_page = 0;
1250 	int		len, limit;
1251 
1252 	if ((common->cmnd[1] & ~0x08) != 0) {	/* Mask away DBD */
1253 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1254 		return -EINVAL;
1255 	}
1256 	pc = common->cmnd[2] >> 6;
1257 	page_code = common->cmnd[2] & 0x3f;
1258 	if (pc == 3) {
1259 		curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1260 		return -EINVAL;
1261 	}
1262 	changeable_values = (pc == 1);
1263 	all_pages = (page_code == 0x3f);
1264 
1265 	/* Write the mode parameter header.  Fixed values are: default
1266 	 * medium type, no cache control (DPOFUA), and no block descriptors.
1267 	 * The only variable value is the WriteProtect bit.  We will fill in
1268 	 * the mode data length later. */
1269 	memset(buf, 0, 8);
1270 	if (mscmnd == SC_MODE_SENSE_6) {
1271 		buf[2] = (curlun->ro ? 0x80 : 0x00);		/* WP, DPOFUA */
1272 		buf += 4;
1273 		limit = 255;
1274 	} else {			/* SC_MODE_SENSE_10 */
1275 		buf[3] = (curlun->ro ? 0x80 : 0x00);		/* WP, DPOFUA */
1276 		buf += 8;
1277 		limit = 65535;		/* Should really be FSG_BUFLEN */
1278 	}
1279 
1280 	/* No block descriptors */
1281 
1282 	/* The mode pages, in numerical order.  The only page we support
1283 	 * is the Caching page. */
1284 	if (page_code == 0x08 || all_pages) {
1285 		valid_page = 1;
1286 		buf[0] = 0x08;		/* Page code */
1287 		buf[1] = 10;		/* Page length */
1288 		memset(buf+2, 0, 10);	/* None of the fields are changeable */
1289 
1290 		if (!changeable_values) {
1291 			buf[2] = 0x04;	/* Write cache enable, */
1292 					/* Read cache not disabled */
1293 					/* No cache retention priorities */
1294 			put_unaligned_be16(0xffff, &buf[4]);
1295 					/* Don't disable prefetch */
1296 					/* Minimum prefetch = 0 */
1297 			put_unaligned_be16(0xffff, &buf[8]);
1298 					/* Maximum prefetch */
1299 			put_unaligned_be16(0xffff, &buf[10]);
1300 					/* Maximum prefetch ceiling */
1301 		}
1302 		buf += 12;
1303 	}
1304 
1305 	/* Check that a valid page was requested and the mode data length
1306 	 * isn't too long. */
1307 	len = buf - buf0;
1308 	if (!valid_page || len > limit) {
1309 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1310 		return -EINVAL;
1311 	}
1312 
1313 	/*  Store the mode data length */
1314 	if (mscmnd == SC_MODE_SENSE_6)
1315 		buf0[0] = len - 1;
1316 	else
1317 		put_unaligned_be16(len - 2, buf0);
1318 	return len;
1319 }
1320 
1321 
1322 static int do_start_stop(struct fsg_common *common)
1323 {
1324 	struct fsg_lun	*curlun = &common->luns[common->lun];
1325 
1326 	if (!curlun) {
1327 		return -EINVAL;
1328 	} else if (!curlun->removable) {
1329 		curlun->sense_data = SS_INVALID_COMMAND;
1330 		return -EINVAL;
1331 	}
1332 
1333 	return 0;
1334 }
1335 
1336 static int do_prevent_allow(struct fsg_common *common)
1337 {
1338 	struct fsg_lun	*curlun = &common->luns[common->lun];
1339 	int		prevent;
1340 
1341 	if (!curlun->removable) {
1342 		curlun->sense_data = SS_INVALID_COMMAND;
1343 		return -EINVAL;
1344 	}
1345 
1346 	prevent = common->cmnd[4] & 0x01;
1347 	if ((common->cmnd[4] & ~0x01) != 0) {	/* Mask away Prevent */
1348 		curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1349 		return -EINVAL;
1350 	}
1351 
1352 	if (curlun->prevent_medium_removal && !prevent)
1353 		fsg_lun_fsync_sub(curlun);
1354 	curlun->prevent_medium_removal = prevent;
1355 	return 0;
1356 }
1357 
1358 
1359 static int do_read_format_capacities(struct fsg_common *common,
1360 			struct fsg_buffhd *bh)
1361 {
1362 	struct fsg_lun	*curlun = &common->luns[common->lun];
1363 	u8		*buf = (u8 *) bh->buf;
1364 
1365 	buf[0] = buf[1] = buf[2] = 0;
1366 	buf[3] = 8;	/* Only the Current/Maximum Capacity Descriptor */
1367 	buf += 4;
1368 
1369 	put_unaligned_be32(curlun->num_sectors, &buf[0]);
1370 						/* Number of blocks */
1371 	put_unaligned_be32(512, &buf[4]);	/* Block length */
1372 	buf[4] = 0x02;				/* Current capacity */
1373 	return 12;
1374 }
1375 
1376 
1377 static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1378 {
1379 	struct fsg_lun	*curlun = &common->luns[common->lun];
1380 
1381 	/* We don't support MODE SELECT */
1382 	if (curlun)
1383 		curlun->sense_data = SS_INVALID_COMMAND;
1384 	return -EINVAL;
1385 }
1386 
1387 
1388 /*-------------------------------------------------------------------------*/
1389 
1390 static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1391 {
1392 	int	rc;
1393 
1394 	rc = fsg_set_halt(fsg, fsg->bulk_in);
1395 	if (rc == -EAGAIN)
1396 		VDBG(fsg, "delayed bulk-in endpoint halt\n");
1397 	while (rc != 0) {
1398 		if (rc != -EAGAIN) {
1399 			WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1400 			rc = 0;
1401 			break;
1402 		}
1403 
1404 		rc = usb_ep_set_halt(fsg->bulk_in);
1405 	}
1406 	return rc;
1407 }
1408 
1409 static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1410 {
1411 	int	rc;
1412 
1413 	DBG(fsg, "bulk-in set wedge\n");
1414 	rc = 0; /* usb_ep_set_wedge(fsg->bulk_in); */
1415 	if (rc == -EAGAIN)
1416 		VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1417 	while (rc != 0) {
1418 		if (rc != -EAGAIN) {
1419 			WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1420 			rc = 0;
1421 			break;
1422 		}
1423 	}
1424 	return rc;
1425 }
1426 
1427 static int pad_with_zeros(struct fsg_dev *fsg)
1428 {
1429 	struct fsg_buffhd	*bh = fsg->common->next_buffhd_to_fill;
1430 	u32			nkeep = bh->inreq->length;
1431 	u32			nsend;
1432 	int			rc;
1433 
1434 	bh->state = BUF_STATE_EMPTY;		/* For the first iteration */
1435 	fsg->common->usb_amount_left = nkeep + fsg->common->residue;
1436 	while (fsg->common->usb_amount_left > 0) {
1437 
1438 		/* Wait for the next buffer to be free */
1439 		while (bh->state != BUF_STATE_EMPTY) {
1440 			rc = sleep_thread(fsg->common);
1441 			if (rc)
1442 				return rc;
1443 		}
1444 
1445 		nsend = min(fsg->common->usb_amount_left, FSG_BUFLEN);
1446 		memset(bh->buf + nkeep, 0, nsend - nkeep);
1447 		bh->inreq->length = nsend;
1448 		bh->inreq->zero = 0;
1449 		start_transfer(fsg, fsg->bulk_in, bh->inreq,
1450 				&bh->inreq_busy, &bh->state);
1451 		bh = fsg->common->next_buffhd_to_fill = bh->next;
1452 		fsg->common->usb_amount_left -= nsend;
1453 		nkeep = 0;
1454 	}
1455 	return 0;
1456 }
1457 
1458 static int throw_away_data(struct fsg_common *common)
1459 {
1460 	struct fsg_buffhd	*bh;
1461 	u32			amount;
1462 	int			rc;
1463 
1464 	for (bh = common->next_buffhd_to_drain;
1465 	     bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1466 	     bh = common->next_buffhd_to_drain) {
1467 
1468 		/* Throw away the data in a filled buffer */
1469 		if (bh->state == BUF_STATE_FULL) {
1470 			bh->state = BUF_STATE_EMPTY;
1471 			common->next_buffhd_to_drain = bh->next;
1472 
1473 			/* A short packet or an error ends everything */
1474 			if (bh->outreq->actual != bh->outreq->length ||
1475 					bh->outreq->status != 0) {
1476 				raise_exception(common,
1477 						FSG_STATE_ABORT_BULK_OUT);
1478 				return -EINTR;
1479 			}
1480 			continue;
1481 		}
1482 
1483 		/* Try to submit another request if we need one */
1484 		bh = common->next_buffhd_to_fill;
1485 		if (bh->state == BUF_STATE_EMPTY
1486 		 && common->usb_amount_left > 0) {
1487 			amount = min(common->usb_amount_left, FSG_BUFLEN);
1488 
1489 			/* amount is always divisible by 512, hence by
1490 			 * the bulk-out maxpacket size */
1491 			bh->outreq->length = amount;
1492 			bh->bulk_out_intended_length = amount;
1493 			bh->outreq->short_not_ok = 1;
1494 			START_TRANSFER_OR(common, bulk_out, bh->outreq,
1495 					  &bh->outreq_busy, &bh->state)
1496 				/* Don't know what to do if
1497 				 * common->fsg is NULL */
1498 				return -EIO;
1499 			common->next_buffhd_to_fill = bh->next;
1500 			common->usb_amount_left -= amount;
1501 			continue;
1502 		}
1503 
1504 		/* Otherwise wait for something to happen */
1505 		rc = sleep_thread(common);
1506 		if (rc)
1507 			return rc;
1508 	}
1509 	return 0;
1510 }
1511 
1512 
1513 static int finish_reply(struct fsg_common *common)
1514 {
1515 	struct fsg_buffhd	*bh = common->next_buffhd_to_fill;
1516 	int			rc = 0;
1517 
1518 	switch (common->data_dir) {
1519 	case DATA_DIR_NONE:
1520 		break;			/* Nothing to send */
1521 
1522 	/* If we don't know whether the host wants to read or write,
1523 	 * this must be CB or CBI with an unknown command.  We mustn't
1524 	 * try to send or receive any data.  So stall both bulk pipes
1525 	 * if we can and wait for a reset. */
1526 	case DATA_DIR_UNKNOWN:
1527 		if (!common->can_stall) {
1528 			/* Nothing */
1529 		} else if (fsg_is_set(common)) {
1530 			fsg_set_halt(common->fsg, common->fsg->bulk_out);
1531 			rc = halt_bulk_in_endpoint(common->fsg);
1532 		} else {
1533 			/* Don't know what to do if common->fsg is NULL */
1534 			rc = -EIO;
1535 		}
1536 		break;
1537 
1538 	/* All but the last buffer of data must have already been sent */
1539 	case DATA_DIR_TO_HOST:
1540 		if (common->data_size == 0) {
1541 			/* Nothing to send */
1542 
1543 		/* If there's no residue, simply send the last buffer */
1544 		} else if (common->residue == 0) {
1545 			bh->inreq->zero = 0;
1546 			START_TRANSFER_OR(common, bulk_in, bh->inreq,
1547 					  &bh->inreq_busy, &bh->state)
1548 				return -EIO;
1549 			common->next_buffhd_to_fill = bh->next;
1550 
1551 		/* For Bulk-only, if we're allowed to stall then send the
1552 		 * short packet and halt the bulk-in endpoint.  If we can't
1553 		 * stall, pad out the remaining data with 0's. */
1554 		} else if (common->can_stall) {
1555 			bh->inreq->zero = 1;
1556 			START_TRANSFER_OR(common, bulk_in, bh->inreq,
1557 					  &bh->inreq_busy, &bh->state)
1558 				/* Don't know what to do if
1559 				 * common->fsg is NULL */
1560 				rc = -EIO;
1561 			common->next_buffhd_to_fill = bh->next;
1562 			if (common->fsg)
1563 				rc = halt_bulk_in_endpoint(common->fsg);
1564 		} else if (fsg_is_set(common)) {
1565 			rc = pad_with_zeros(common->fsg);
1566 		} else {
1567 			/* Don't know what to do if common->fsg is NULL */
1568 			rc = -EIO;
1569 		}
1570 		break;
1571 
1572 	/* We have processed all we want from the data the host has sent.
1573 	 * There may still be outstanding bulk-out requests. */
1574 	case DATA_DIR_FROM_HOST:
1575 		if (common->residue == 0) {
1576 			/* Nothing to receive */
1577 
1578 		/* Did the host stop sending unexpectedly early? */
1579 		} else if (common->short_packet_received) {
1580 			raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1581 			rc = -EINTR;
1582 
1583 		/* We haven't processed all the incoming data.  Even though
1584 		 * we may be allowed to stall, doing so would cause a race.
1585 		 * The controller may already have ACK'ed all the remaining
1586 		 * bulk-out packets, in which case the host wouldn't see a
1587 		 * STALL.  Not realizing the endpoint was halted, it wouldn't
1588 		 * clear the halt -- leading to problems later on. */
1589 #if 0
1590 		} else if (common->can_stall) {
1591 			if (fsg_is_set(common))
1592 				fsg_set_halt(common->fsg,
1593 					     common->fsg->bulk_out);
1594 			raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1595 			rc = -EINTR;
1596 #endif
1597 
1598 		/* We can't stall.  Read in the excess data and throw it
1599 		 * all away. */
1600 		} else {
1601 			rc = throw_away_data(common);
1602 		}
1603 		break;
1604 	}
1605 	return rc;
1606 }
1607 
1608 
1609 static int send_status(struct fsg_common *common)
1610 {
1611 	struct fsg_lun		*curlun = &common->luns[common->lun];
1612 	struct fsg_buffhd	*bh;
1613 	struct bulk_cs_wrap	*csw;
1614 	int			rc;
1615 	u8			status = USB_STATUS_PASS;
1616 	u32			sd, sdinfo = 0;
1617 
1618 	/* Wait for the next buffer to become available */
1619 	bh = common->next_buffhd_to_fill;
1620 	while (bh->state != BUF_STATE_EMPTY) {
1621 		rc = sleep_thread(common);
1622 		if (rc)
1623 			return rc;
1624 	}
1625 
1626 	if (curlun)
1627 		sd = curlun->sense_data;
1628 	else if (common->bad_lun_okay)
1629 		sd = SS_NO_SENSE;
1630 	else
1631 		sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1632 
1633 	if (common->phase_error) {
1634 		DBG(common, "sending phase-error status\n");
1635 		status = USB_STATUS_PHASE_ERROR;
1636 		sd = SS_INVALID_COMMAND;
1637 	} else if (sd != SS_NO_SENSE) {
1638 		DBG(common, "sending command-failure status\n");
1639 		status = USB_STATUS_FAIL;
1640 		VDBG(common, "  sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1641 			"  info x%x\n",
1642 			SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1643 	}
1644 
1645 	/* Store and send the Bulk-only CSW */
1646 	csw = (void *)bh->buf;
1647 
1648 	csw->Signature = cpu_to_le32(USB_BULK_CS_SIG);
1649 	csw->Tag = common->tag;
1650 	csw->Residue = cpu_to_le32(common->residue);
1651 	csw->Status = status;
1652 
1653 	bh->inreq->length = USB_BULK_CS_WRAP_LEN;
1654 	bh->inreq->zero = 0;
1655 	START_TRANSFER_OR(common, bulk_in, bh->inreq,
1656 			  &bh->inreq_busy, &bh->state)
1657 		/* Don't know what to do if common->fsg is NULL */
1658 		return -EIO;
1659 
1660 	common->next_buffhd_to_fill = bh->next;
1661 	return 0;
1662 }
1663 
1664 
1665 /*-------------------------------------------------------------------------*/
1666 #ifdef CONFIG_CMD_ROCKUSB
1667 #include "f_rockusb.c"
1668 #endif
1669 
1670 /* Check whether the command is properly formed and whether its data size
1671  * and direction agree with the values we already have. */
1672 static int check_command(struct fsg_common *common, int cmnd_size,
1673 		enum data_direction data_dir, unsigned int mask,
1674 		int needs_medium, const char *name)
1675 {
1676 	int			i;
1677 	int			lun = common->cmnd[1] >> 5;
1678 	static const char	dirletter[4] = {'u', 'o', 'i', 'n'};
1679 	char			hdlen[20];
1680 	struct fsg_lun		*curlun;
1681 
1682 	hdlen[0] = 0;
1683 	if (common->data_dir != DATA_DIR_UNKNOWN)
1684 		sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1685 				common->data_size);
1686 	VDBG(common, "SCSI command: %s;  Dc=%d, D%c=%u;  Hc=%d%s\n",
1687 	     name, cmnd_size, dirletter[(int) data_dir],
1688 	     common->data_size_from_cmnd, common->cmnd_size, hdlen);
1689 
1690 	/* We can't reply at all until we know the correct data direction
1691 	 * and size. */
1692 	if (common->data_size_from_cmnd == 0)
1693 		data_dir = DATA_DIR_NONE;
1694 	if (common->data_size < common->data_size_from_cmnd) {
1695 		/* Host data size < Device data size is a phase error.
1696 		 * Carry out the command, but only transfer as much as
1697 		 * we are allowed. */
1698 		common->data_size_from_cmnd = common->data_size;
1699 		common->phase_error = 1;
1700 	}
1701 	common->residue = common->data_size;
1702 	common->usb_amount_left = common->data_size;
1703 
1704 	/* Conflicting data directions is a phase error */
1705 	if (common->data_dir != data_dir
1706 	 && common->data_size_from_cmnd > 0) {
1707 		common->phase_error = 1;
1708 		return -EINVAL;
1709 	}
1710 
1711 	/* Verify the length of the command itself */
1712 	if (cmnd_size != common->cmnd_size) {
1713 
1714 		/* Special case workaround: There are plenty of buggy SCSI
1715 		 * implementations. Many have issues with cbw->Length
1716 		 * field passing a wrong command size. For those cases we
1717 		 * always try to work around the problem by using the length
1718 		 * sent by the host side provided it is at least as large
1719 		 * as the correct command length.
1720 		 * Examples of such cases would be MS-Windows, which issues
1721 		 * REQUEST SENSE with cbw->Length == 12 where it should
1722 		 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1723 		 * REQUEST SENSE with cbw->Length == 10 where it should
1724 		 * be 6 as well.
1725 		 */
1726 		if (cmnd_size <= common->cmnd_size) {
1727 			DBG(common, "%s is buggy! Expected length %d "
1728 			    "but we got %d\n", name,
1729 			    cmnd_size, common->cmnd_size);
1730 			cmnd_size = common->cmnd_size;
1731 		} else {
1732 			common->phase_error = 1;
1733 			return -EINVAL;
1734 		}
1735 	}
1736 
1737 	/* Check that the LUN values are consistent */
1738 	if (common->lun != lun)
1739 		DBG(common, "using LUN %d from CBW, not LUN %d from CDB\n",
1740 		    common->lun, lun);
1741 
1742 	/* Check the LUN */
1743 	if (common->lun < common->nluns) {
1744 		curlun = &common->luns[common->lun];
1745 		if (common->cmnd[0] != SC_REQUEST_SENSE) {
1746 			curlun->sense_data = SS_NO_SENSE;
1747 			curlun->info_valid = 0;
1748 		}
1749 	} else {
1750 		curlun = NULL;
1751 		common->bad_lun_okay = 0;
1752 
1753 		/* INQUIRY and REQUEST SENSE commands are explicitly allowed
1754 		 * to use unsupported LUNs; all others may not. */
1755 		if (common->cmnd[0] != SC_INQUIRY &&
1756 		    common->cmnd[0] != SC_REQUEST_SENSE) {
1757 			DBG(common, "unsupported LUN %d\n", common->lun);
1758 			return -EINVAL;
1759 		}
1760 	}
1761 #if 0
1762 	/* If a unit attention condition exists, only INQUIRY and
1763 	 * REQUEST SENSE commands are allowed; anything else must fail. */
1764 	if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1765 			common->cmnd[0] != SC_INQUIRY &&
1766 			common->cmnd[0] != SC_REQUEST_SENSE) {
1767 		curlun->sense_data = curlun->unit_attention_data;
1768 		curlun->unit_attention_data = SS_NO_SENSE;
1769 		return -EINVAL;
1770 	}
1771 #endif
1772 	/* Check that only command bytes listed in the mask are non-zero */
1773 	common->cmnd[1] &= 0x1f;			/* Mask away the LUN */
1774 	for (i = 1; i < cmnd_size; ++i) {
1775 		if (common->cmnd[i] && !(mask & (1 << i))) {
1776 			if (curlun)
1777 				curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1778 			return -EINVAL;
1779 		}
1780 	}
1781 
1782 	return 0;
1783 }
1784 
1785 
1786 static int do_scsi_command(struct fsg_common *common)
1787 {
1788 	struct fsg_buffhd	*bh;
1789 	int			rc;
1790 	int			reply = -EINVAL;
1791 	int			i;
1792 	static char		unknown[16];
1793 	struct fsg_lun		*curlun = &common->luns[common->lun];
1794 	const char		*cdev_name __maybe_unused;
1795 
1796 	dump_cdb(common);
1797 
1798 	/* Wait for the next buffer to become available for data or status */
1799 	bh = common->next_buffhd_to_fill;
1800 	common->next_buffhd_to_drain = bh;
1801 	while (bh->state != BUF_STATE_EMPTY) {
1802 		rc = sleep_thread(common);
1803 		if (rc)
1804 			return rc;
1805 	}
1806 	common->phase_error = 0;
1807 	common->short_packet_received = 0;
1808 
1809 	down_read(&common->filesem);	/* We're using the backing file */
1810 
1811 	cdev_name = common->fsg->function.config->cdev->driver->name;
1812 	if (IS_RKUSB_UMS_DNL(cdev_name)) {
1813 		rc = rkusb_cmd_process(common, bh, &reply);
1814 		if (rc == RKUSB_RC_FINISHED || rc == RKUSB_RC_ERROR)
1815 			goto finish;
1816 		else if (rc == RKUSB_RC_UNKNOWN_CMND)
1817 			goto unknown_cmnd;
1818 	}
1819 
1820 	switch (common->cmnd[0]) {
1821 
1822 	case SC_INQUIRY:
1823 		common->data_size_from_cmnd = common->cmnd[4];
1824 		reply = check_command(common, 6, DATA_DIR_TO_HOST,
1825 				      (1<<4), 0,
1826 				      "INQUIRY");
1827 		if (reply == 0)
1828 			reply = do_inquiry(common, bh);
1829 		break;
1830 
1831 	case SC_MODE_SELECT_6:
1832 		common->data_size_from_cmnd = common->cmnd[4];
1833 		reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1834 				      (1<<1) | (1<<4), 0,
1835 				      "MODE SELECT(6)");
1836 		if (reply == 0)
1837 			reply = do_mode_select(common, bh);
1838 		break;
1839 
1840 	case SC_MODE_SELECT_10:
1841 		common->data_size_from_cmnd =
1842 			get_unaligned_be16(&common->cmnd[7]);
1843 		reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1844 				      (1<<1) | (3<<7), 0,
1845 				      "MODE SELECT(10)");
1846 		if (reply == 0)
1847 			reply = do_mode_select(common, bh);
1848 		break;
1849 
1850 	case SC_MODE_SENSE_6:
1851 		common->data_size_from_cmnd = common->cmnd[4];
1852 		reply = check_command(common, 6, DATA_DIR_TO_HOST,
1853 				      (1<<1) | (1<<2) | (1<<4), 0,
1854 				      "MODE SENSE(6)");
1855 		if (reply == 0)
1856 			reply = do_mode_sense(common, bh);
1857 		break;
1858 
1859 	case SC_MODE_SENSE_10:
1860 		common->data_size_from_cmnd =
1861 			get_unaligned_be16(&common->cmnd[7]);
1862 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1863 				      (1<<1) | (1<<2) | (3<<7), 0,
1864 				      "MODE SENSE(10)");
1865 		if (reply == 0)
1866 			reply = do_mode_sense(common, bh);
1867 		break;
1868 
1869 	case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
1870 		common->data_size_from_cmnd = 0;
1871 		reply = check_command(common, 6, DATA_DIR_NONE,
1872 				      (1<<4), 0,
1873 				      "PREVENT-ALLOW MEDIUM REMOVAL");
1874 		if (reply == 0)
1875 			reply = do_prevent_allow(common);
1876 		break;
1877 
1878 	case SC_READ_6:
1879 		i = common->cmnd[4];
1880 		common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1881 		reply = check_command(common, 6, DATA_DIR_TO_HOST,
1882 				      (7<<1) | (1<<4), 1,
1883 				      "READ(6)");
1884 		if (reply == 0)
1885 			reply = do_read(common);
1886 		break;
1887 
1888 	case SC_READ_10:
1889 		common->data_size_from_cmnd =
1890 				get_unaligned_be16(&common->cmnd[7]) << 9;
1891 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1892 				      (1<<1) | (0xf<<2) | (3<<7), 1,
1893 				      "READ(10)");
1894 		if (reply == 0)
1895 			reply = do_read(common);
1896 		break;
1897 
1898 	case SC_READ_12:
1899 		common->data_size_from_cmnd =
1900 				get_unaligned_be32(&common->cmnd[6]) << 9;
1901 		reply = check_command(common, 12, DATA_DIR_TO_HOST,
1902 				      (1<<1) | (0xf<<2) | (0xf<<6), 1,
1903 				      "READ(12)");
1904 		if (reply == 0)
1905 			reply = do_read(common);
1906 		break;
1907 
1908 	case SC_READ_CAPACITY:
1909 		common->data_size_from_cmnd = 8;
1910 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1911 				      (0xf<<2) | (1<<8), 1,
1912 				      "READ CAPACITY");
1913 		if (reply == 0)
1914 			reply = do_read_capacity(common, bh);
1915 		break;
1916 
1917 	case SC_READ_HEADER:
1918 		if (!common->luns[common->lun].cdrom)
1919 			goto unknown_cmnd;
1920 		common->data_size_from_cmnd =
1921 			get_unaligned_be16(&common->cmnd[7]);
1922 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1923 				      (3<<7) | (0x1f<<1), 1,
1924 				      "READ HEADER");
1925 		if (reply == 0)
1926 			reply = do_read_header(common, bh);
1927 		break;
1928 
1929 	case SC_READ_TOC:
1930 		if (!common->luns[common->lun].cdrom)
1931 			goto unknown_cmnd;
1932 		common->data_size_from_cmnd =
1933 			get_unaligned_be16(&common->cmnd[7]);
1934 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1935 				      (7<<6) | (1<<1), 1,
1936 				      "READ TOC");
1937 		if (reply == 0)
1938 			reply = do_read_toc(common, bh);
1939 		break;
1940 
1941 	case SC_READ_FORMAT_CAPACITIES:
1942 		common->data_size_from_cmnd =
1943 			get_unaligned_be16(&common->cmnd[7]);
1944 		reply = check_command(common, 10, DATA_DIR_TO_HOST,
1945 				      (3<<7), 1,
1946 				      "READ FORMAT CAPACITIES");
1947 		if (reply == 0)
1948 			reply = do_read_format_capacities(common, bh);
1949 		break;
1950 
1951 	case SC_REQUEST_SENSE:
1952 		common->data_size_from_cmnd = common->cmnd[4];
1953 		reply = check_command(common, 6, DATA_DIR_TO_HOST,
1954 				      (1<<4), 0,
1955 				      "REQUEST SENSE");
1956 		if (reply == 0)
1957 			reply = do_request_sense(common, bh);
1958 		break;
1959 
1960 	case SC_START_STOP_UNIT:
1961 		common->data_size_from_cmnd = 0;
1962 		reply = check_command(common, 6, DATA_DIR_NONE,
1963 				      (1<<1) | (1<<4), 0,
1964 				      "START-STOP UNIT");
1965 		if (reply == 0)
1966 			reply = do_start_stop(common);
1967 		break;
1968 
1969 	case SC_SYNCHRONIZE_CACHE:
1970 		common->data_size_from_cmnd = 0;
1971 		reply = check_command(common, 10, DATA_DIR_NONE,
1972 				      (0xf<<2) | (3<<7), 1,
1973 				      "SYNCHRONIZE CACHE");
1974 		if (reply == 0)
1975 			reply = do_synchronize_cache(common);
1976 		break;
1977 
1978 	case SC_TEST_UNIT_READY:
1979 		common->data_size_from_cmnd = 0;
1980 		reply = check_command(common, 6, DATA_DIR_NONE,
1981 				0, 1,
1982 				"TEST UNIT READY");
1983 		break;
1984 
1985 	/* Although optional, this command is used by MS-Windows.  We
1986 	 * support a minimal version: BytChk must be 0. */
1987 	case SC_VERIFY:
1988 		common->data_size_from_cmnd = 0;
1989 		reply = check_command(common, 10, DATA_DIR_NONE,
1990 				      (1<<1) | (0xf<<2) | (3<<7), 1,
1991 				      "VERIFY");
1992 		if (reply == 0)
1993 			reply = do_verify(common);
1994 		break;
1995 
1996 	case SC_WRITE_6:
1997 		i = common->cmnd[4];
1998 		common->data_size_from_cmnd = (i == 0 ? 256 : i) << 9;
1999 		reply = check_command(common, 6, DATA_DIR_FROM_HOST,
2000 				      (7<<1) | (1<<4), 1,
2001 				      "WRITE(6)");
2002 		if (reply == 0)
2003 			reply = do_write(common);
2004 		break;
2005 
2006 	case SC_WRITE_10:
2007 		common->data_size_from_cmnd =
2008 				get_unaligned_be16(&common->cmnd[7]) << 9;
2009 
2010 		if (IS_RKUSB_UMS_DNL(cdev_name)) {
2011 			reply = check_command(common, common->cmnd_size, DATA_DIR_FROM_HOST,
2012 					      (1 << 1) | (0xf << 2) | (3 << 7) | (0xf << 9), 1,
2013 					      "WRITE(10)");
2014 		} else {
2015 			reply = check_command(common, 10, DATA_DIR_FROM_HOST,
2016 					      (1 << 1) | (0xf << 2) | (3 << 7), 1,
2017 					      "WRITE(10)");
2018 		}
2019 
2020 		if (reply == 0)
2021 			reply = do_write(common);
2022 		break;
2023 
2024 	case SC_WRITE_12:
2025 		common->data_size_from_cmnd =
2026 				get_unaligned_be32(&common->cmnd[6]) << 9;
2027 		reply = check_command(common, 12, DATA_DIR_FROM_HOST,
2028 				      (1<<1) | (0xf<<2) | (0xf<<6), 1,
2029 				      "WRITE(12)");
2030 		if (reply == 0)
2031 			reply = do_write(common);
2032 		break;
2033 
2034 	/* Some mandatory commands that we recognize but don't implement.
2035 	 * They don't mean much in this setting.  It's left as an exercise
2036 	 * for anyone interested to implement RESERVE and RELEASE in terms
2037 	 * of Posix locks. */
2038 	case SC_FORMAT_UNIT:
2039 	case SC_RELEASE:
2040 	case SC_RESERVE:
2041 	case SC_SEND_DIAGNOSTIC:
2042 		/* Fall through */
2043 
2044 	default:
2045 unknown_cmnd:
2046 		common->data_size_from_cmnd = 0;
2047 		sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2048 		reply = check_command(common, common->cmnd_size,
2049 				      DATA_DIR_UNKNOWN, 0xff, 0, unknown);
2050 		if (reply == 0) {
2051 			curlun->sense_data = SS_INVALID_COMMAND;
2052 			reply = -EINVAL;
2053 		}
2054 		break;
2055 	}
2056 
2057 finish:
2058 	up_read(&common->filesem);
2059 
2060 	if (reply == -EINTR)
2061 		return -EINTR;
2062 
2063 	/* Set up the single reply buffer for finish_reply() */
2064 	if (reply == -EINVAL)
2065 		reply = 0;		/* Error reply length */
2066 	if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2067 		reply = min((u32) reply, common->data_size_from_cmnd);
2068 		bh->inreq->length = reply;
2069 		bh->state = BUF_STATE_FULL;
2070 		common->residue -= reply;
2071 	}				/* Otherwise it's already set */
2072 
2073 	return 0;
2074 }
2075 
2076 /*-------------------------------------------------------------------------*/
2077 
2078 static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2079 {
2080 	struct usb_request	*req = bh->outreq;
2081 	struct fsg_bulk_cb_wrap	*cbw = req->buf;
2082 	struct fsg_common	*common = fsg->common;
2083 
2084 	/* Was this a real packet?  Should it be ignored? */
2085 	if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2086 		return -EINVAL;
2087 
2088 	/* Is the CBW valid? */
2089 	if (req->actual != USB_BULK_CB_WRAP_LEN ||
2090 			cbw->Signature != cpu_to_le32(
2091 				USB_BULK_CB_SIG)) {
2092 		DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2093 				req->actual,
2094 				le32_to_cpu(cbw->Signature));
2095 
2096 		/* The Bulk-only spec says we MUST stall the IN endpoint
2097 		 * (6.6.1), so it's unavoidable.  It also says we must
2098 		 * retain this state until the next reset, but there's
2099 		 * no way to tell the controller driver it should ignore
2100 		 * Clear-Feature(HALT) requests.
2101 		 *
2102 		 * We aren't required to halt the OUT endpoint; instead
2103 		 * we can simply accept and discard any data received
2104 		 * until the next reset. */
2105 		wedge_bulk_in_endpoint(fsg);
2106 		generic_set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2107 		return -EINVAL;
2108 	}
2109 
2110 	/* Is the CBW meaningful? */
2111 	if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~USB_BULK_IN_FLAG ||
2112 			cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2113 		DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2114 				"cmdlen %u\n",
2115 				cbw->Lun, cbw->Flags, cbw->Length);
2116 
2117 		/* We can do anything we want here, so let's stall the
2118 		 * bulk pipes if we are allowed to. */
2119 		if (common->can_stall) {
2120 			fsg_set_halt(fsg, fsg->bulk_out);
2121 			halt_bulk_in_endpoint(fsg);
2122 		}
2123 		return -EINVAL;
2124 	}
2125 
2126 	/* Save the command for later */
2127 	common->cmnd_size = cbw->Length;
2128 	memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2129 	if (cbw->Flags & USB_BULK_IN_FLAG)
2130 		common->data_dir = DATA_DIR_TO_HOST;
2131 	else
2132 		common->data_dir = DATA_DIR_FROM_HOST;
2133 	common->data_size = le32_to_cpu(cbw->DataTransferLength);
2134 	if (common->data_size == 0)
2135 		common->data_dir = DATA_DIR_NONE;
2136 	common->lun = cbw->Lun;
2137 	common->tag = cbw->Tag;
2138 	return 0;
2139 }
2140 
2141 
2142 static int get_next_command(struct fsg_common *common)
2143 {
2144 	struct fsg_buffhd	*bh;
2145 	int			rc = 0;
2146 
2147 	/* Wait for the next buffer to become available */
2148 	bh = common->next_buffhd_to_fill;
2149 	while (bh->state != BUF_STATE_EMPTY) {
2150 		rc = sleep_thread(common);
2151 		if (rc)
2152 			return rc;
2153 	}
2154 
2155 	/* Queue a request to read a Bulk-only CBW */
2156 	set_bulk_out_req_length(common, bh, USB_BULK_CB_WRAP_LEN);
2157 	bh->outreq->short_not_ok = 1;
2158 	START_TRANSFER_OR(common, bulk_out, bh->outreq,
2159 			  &bh->outreq_busy, &bh->state)
2160 		/* Don't know what to do if common->fsg is NULL */
2161 		return -EIO;
2162 
2163 	/* We will drain the buffer in software, which means we
2164 	 * can reuse it for the next filling.  No need to advance
2165 	 * next_buffhd_to_fill. */
2166 
2167 	/* Wait for the CBW to arrive */
2168 	while (bh->state != BUF_STATE_FULL) {
2169 		rc = sleep_thread(common);
2170 		if (rc)
2171 			return rc;
2172 	}
2173 
2174 	rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2175 	bh->state = BUF_STATE_EMPTY;
2176 
2177 	return rc;
2178 }
2179 
2180 
2181 /*-------------------------------------------------------------------------*/
2182 
2183 static int enable_endpoint(struct fsg_common *common, struct usb_ep *ep,
2184 		const struct usb_endpoint_descriptor *d)
2185 {
2186 	int	rc;
2187 
2188 	ep->driver_data = common;
2189 	rc = usb_ep_enable(ep, d);
2190 	if (rc)
2191 		ERROR(common, "can't enable %s, result %d\n", ep->name, rc);
2192 	return rc;
2193 }
2194 
2195 static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2196 		struct usb_request **preq)
2197 {
2198 	*preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2199 	if (*preq)
2200 		return 0;
2201 	ERROR(common, "can't allocate request for %s\n", ep->name);
2202 	return -ENOMEM;
2203 }
2204 
2205 /* Reset interface setting and re-init endpoint state (toggle etc). */
2206 static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2207 {
2208 	const struct usb_endpoint_descriptor *d;
2209 	struct fsg_dev *fsg;
2210 	int i, rc = 0;
2211 
2212 	if (common->running)
2213 		DBG(common, "reset interface\n");
2214 
2215 reset:
2216 	/* Deallocate the requests */
2217 	if (common->fsg) {
2218 		fsg = common->fsg;
2219 
2220 		for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2221 			struct fsg_buffhd *bh = &common->buffhds[i];
2222 
2223 			if (bh->inreq) {
2224 				usb_ep_free_request(fsg->bulk_in, bh->inreq);
2225 				bh->inreq = NULL;
2226 			}
2227 			if (bh->outreq) {
2228 				usb_ep_free_request(fsg->bulk_out, bh->outreq);
2229 				bh->outreq = NULL;
2230 			}
2231 		}
2232 
2233 		/* Disable the endpoints */
2234 		if (fsg->bulk_in_enabled) {
2235 			usb_ep_disable(fsg->bulk_in);
2236 			fsg->bulk_in_enabled = 0;
2237 		}
2238 		if (fsg->bulk_out_enabled) {
2239 			usb_ep_disable(fsg->bulk_out);
2240 			fsg->bulk_out_enabled = 0;
2241 		}
2242 
2243 		common->fsg = NULL;
2244 		/* wake_up(&common->fsg_wait); */
2245 	}
2246 
2247 	common->running = 0;
2248 	if (!new_fsg || rc)
2249 		return rc;
2250 
2251 	common->fsg = new_fsg;
2252 	fsg = common->fsg;
2253 
2254 	/* Enable the endpoints */
2255 	d = fsg_ep_desc(common->gadget,
2256 			&fsg_fs_bulk_in_desc, &fsg_hs_bulk_in_desc,
2257 			&fsg_ss_bulk_in_desc, &fsg_ss_bulk_in_comp_desc,
2258 			fsg->bulk_in);
2259 	rc = enable_endpoint(common, fsg->bulk_in, d);
2260 	if (rc)
2261 		goto reset;
2262 	fsg->bulk_in_enabled = 1;
2263 
2264 	d = fsg_ep_desc(common->gadget,
2265 			&fsg_fs_bulk_out_desc, &fsg_hs_bulk_out_desc,
2266 			&fsg_ss_bulk_out_desc, &fsg_ss_bulk_out_comp_desc,
2267 			fsg->bulk_out);
2268 	rc = enable_endpoint(common, fsg->bulk_out, d);
2269 	if (rc)
2270 		goto reset;
2271 	fsg->bulk_out_enabled = 1;
2272 	common->bulk_out_maxpacket =
2273 				le16_to_cpu(get_unaligned(&d->wMaxPacketSize));
2274 	generic_clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2275 
2276 	/* Allocate the requests */
2277 	for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2278 		struct fsg_buffhd	*bh = &common->buffhds[i];
2279 
2280 		rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2281 		if (rc)
2282 			goto reset;
2283 		rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2284 		if (rc)
2285 			goto reset;
2286 		bh->inreq->buf = bh->outreq->buf = bh->buf;
2287 		bh->inreq->context = bh->outreq->context = bh;
2288 		bh->inreq->complete = bulk_in_complete;
2289 		bh->outreq->complete = bulk_out_complete;
2290 	}
2291 
2292 	common->running = 1;
2293 
2294 	return rc;
2295 }
2296 
2297 
2298 /****************************** ALT CONFIGS ******************************/
2299 
2300 
2301 static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2302 {
2303 	struct fsg_dev *fsg = fsg_from_func(f);
2304 	fsg->common->new_fsg = fsg;
2305 	raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2306 	return 0;
2307 }
2308 
2309 static void fsg_disable(struct usb_function *f)
2310 {
2311 	struct fsg_dev *fsg = fsg_from_func(f);
2312 	fsg->common->new_fsg = NULL;
2313 	raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2314 }
2315 
2316 /*-------------------------------------------------------------------------*/
2317 
2318 static void handle_exception(struct fsg_common *common)
2319 {
2320 	int			i;
2321 	struct fsg_buffhd	*bh;
2322 	enum fsg_state		old_state;
2323 	struct fsg_lun		*curlun;
2324 	unsigned int		exception_req_tag;
2325 
2326 	/* Cancel all the pending transfers */
2327 	if (common->fsg) {
2328 		for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2329 			bh = &common->buffhds[i];
2330 			if (bh->inreq_busy)
2331 				usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2332 			if (bh->outreq_busy)
2333 				usb_ep_dequeue(common->fsg->bulk_out,
2334 					       bh->outreq);
2335 		}
2336 
2337 		/* Wait until everything is idle */
2338 		for (;;) {
2339 			int num_active = 0;
2340 			for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2341 				bh = &common->buffhds[i];
2342 				num_active += bh->inreq_busy + bh->outreq_busy;
2343 			}
2344 			if (num_active == 0)
2345 				break;
2346 			if (sleep_thread(common))
2347 				return;
2348 		}
2349 
2350 		/* Clear out the controller's fifos */
2351 		if (common->fsg->bulk_in_enabled)
2352 			usb_ep_fifo_flush(common->fsg->bulk_in);
2353 		if (common->fsg->bulk_out_enabled)
2354 			usb_ep_fifo_flush(common->fsg->bulk_out);
2355 	}
2356 
2357 	/* Reset the I/O buffer states and pointers, the SCSI
2358 	 * state, and the exception.  Then invoke the handler. */
2359 
2360 	for (i = 0; i < FSG_NUM_BUFFERS; ++i) {
2361 		bh = &common->buffhds[i];
2362 		bh->state = BUF_STATE_EMPTY;
2363 	}
2364 	common->next_buffhd_to_fill = &common->buffhds[0];
2365 	common->next_buffhd_to_drain = &common->buffhds[0];
2366 	exception_req_tag = common->exception_req_tag;
2367 	old_state = common->state;
2368 
2369 	if (old_state == FSG_STATE_ABORT_BULK_OUT)
2370 		common->state = FSG_STATE_STATUS_PHASE;
2371 	else {
2372 		for (i = 0; i < common->nluns; ++i) {
2373 			curlun = &common->luns[i];
2374 			curlun->sense_data = SS_NO_SENSE;
2375 			curlun->info_valid = 0;
2376 		}
2377 		common->state = FSG_STATE_IDLE;
2378 	}
2379 
2380 	/* Carry out any extra actions required for the exception */
2381 	switch (old_state) {
2382 	case FSG_STATE_ABORT_BULK_OUT:
2383 		send_status(common);
2384 
2385 		if (common->state == FSG_STATE_STATUS_PHASE)
2386 			common->state = FSG_STATE_IDLE;
2387 		break;
2388 
2389 	case FSG_STATE_RESET:
2390 		/* In case we were forced against our will to halt a
2391 		 * bulk endpoint, clear the halt now.  (The SuperH UDC
2392 		 * requires this.) */
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 		break;
2403 
2404 	case FSG_STATE_CONFIG_CHANGE:
2405 		do_set_interface(common, common->new_fsg);
2406 		break;
2407 
2408 	case FSG_STATE_EXIT:
2409 	case FSG_STATE_TERMINATED:
2410 		do_set_interface(common, NULL);		/* Free resources */
2411 		common->state = FSG_STATE_TERMINATED;	/* Stop the thread */
2412 		break;
2413 
2414 	case FSG_STATE_INTERFACE_CHANGE:
2415 	case FSG_STATE_DISCONNECT:
2416 	case FSG_STATE_COMMAND_PHASE:
2417 	case FSG_STATE_DATA_PHASE:
2418 	case FSG_STATE_STATUS_PHASE:
2419 	case FSG_STATE_IDLE:
2420 		break;
2421 	}
2422 }
2423 
2424 /*-------------------------------------------------------------------------*/
2425 
2426 int fsg_main_thread(void *common_)
2427 {
2428 	int ret;
2429 	struct fsg_common	*common = the_fsg_common;
2430 	/* The main loop */
2431 	do {
2432 		if (exception_in_progress(common)) {
2433 			handle_exception(common);
2434 			continue;
2435 		}
2436 
2437 		if (!common->running) {
2438 			ret = sleep_thread(common);
2439 			if (ret)
2440 				return ret;
2441 
2442 			continue;
2443 		}
2444 
2445 		ret = get_next_command(common);
2446 		if (ret)
2447 			return ret;
2448 
2449 		if (!exception_in_progress(common))
2450 			common->state = FSG_STATE_DATA_PHASE;
2451 
2452 		if (do_scsi_command(common) || finish_reply(common))
2453 			continue;
2454 
2455 		if (!exception_in_progress(common))
2456 			common->state = FSG_STATE_STATUS_PHASE;
2457 
2458 		if (send_status(common))
2459 			continue;
2460 
2461 		if (!exception_in_progress(common))
2462 			common->state = FSG_STATE_IDLE;
2463 	} while (0);
2464 
2465 	common->thread_task = NULL;
2466 
2467 	return 0;
2468 }
2469 
2470 static void fsg_common_release(struct kref *ref);
2471 
2472 static struct fsg_common *fsg_common_init(struct fsg_common *common,
2473 					  struct usb_composite_dev *cdev)
2474 {
2475 	struct usb_gadget *gadget = cdev->gadget;
2476 	struct fsg_buffhd *bh;
2477 	struct fsg_lun *curlun;
2478 	int nluns, i, rc;
2479 
2480 	/* Find out how many LUNs there should be */
2481 	nluns = ums_count;
2482 	if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2483 		printf("invalid number of LUNs: %u\n", nluns);
2484 		return ERR_PTR(-EINVAL);
2485 	}
2486 
2487 	/* Allocate? */
2488 	if (!common) {
2489 		common = calloc(sizeof(*common), 1);
2490 		if (!common)
2491 			return ERR_PTR(-ENOMEM);
2492 		common->free_storage_on_release = 1;
2493 	} else {
2494 		memset(common, 0, sizeof(*common));
2495 		common->free_storage_on_release = 0;
2496 	}
2497 
2498 	common->ops = NULL;
2499 	common->private_data = NULL;
2500 
2501 	common->gadget = gadget;
2502 	common->ep0 = gadget->ep0;
2503 	common->ep0req = cdev->req;
2504 
2505 	/* Maybe allocate device-global string IDs, and patch descriptors */
2506 	if (fsg_strings[FSG_STRING_INTERFACE].id == 0) {
2507 		rc = usb_string_id(cdev);
2508 		if (unlikely(rc < 0))
2509 			goto error_release;
2510 		fsg_strings[FSG_STRING_INTERFACE].id = rc;
2511 		fsg_intf_desc.iInterface = rc;
2512 	}
2513 
2514 	/* Create the LUNs, open their backing files, and register the
2515 	 * LUN devices in sysfs. */
2516 	curlun = calloc(nluns, sizeof *curlun);
2517 	if (!curlun) {
2518 		rc = -ENOMEM;
2519 		goto error_release;
2520 	}
2521 	common->nluns = nluns;
2522 
2523 	for (i = 0; i < nluns; i++) {
2524 		common->luns[i].removable = 1;
2525 
2526 		rc = fsg_lun_open(&common->luns[i], ums[i].num_sectors, "");
2527 		if (rc)
2528 			goto error_luns;
2529 	}
2530 	common->lun = 0;
2531 
2532 	/* Data buffers cyclic list */
2533 	bh = common->buffhds;
2534 
2535 	i = FSG_NUM_BUFFERS;
2536 	goto buffhds_first_it;
2537 	do {
2538 		bh->next = bh + 1;
2539 		++bh;
2540 buffhds_first_it:
2541 		bh->inreq_busy = 0;
2542 		bh->outreq_busy = 0;
2543 		bh->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, FSG_BUFLEN);
2544 		if (unlikely(!bh->buf)) {
2545 			rc = -ENOMEM;
2546 			goto error_release;
2547 		}
2548 	} while (--i);
2549 	bh->next = common->buffhds;
2550 
2551 	snprintf(common->inquiry_string, sizeof common->inquiry_string,
2552 		 "%-8s%-16s%04x",
2553 		 "Linux   ",
2554 		 "File-Store Gadget",
2555 		 0xffff);
2556 
2557 	/* Some peripheral controllers are known not to be able to
2558 	 * halt bulk endpoints correctly.  If one of them is present,
2559 	 * disable stalls.
2560 	 */
2561 
2562 	/* Tell the thread to start working */
2563 	common->thread_task =
2564 		kthread_create(fsg_main_thread, common,
2565 			       OR(cfg->thread_name, "file-storage"));
2566 	if (IS_ERR(common->thread_task)) {
2567 		rc = PTR_ERR(common->thread_task);
2568 		goto error_release;
2569 	}
2570 
2571 #undef OR
2572 	/* Information */
2573 	INFO(common, FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
2574 	INFO(common, "Number of LUNs=%d\n", common->nluns);
2575 
2576 	return common;
2577 
2578 error_luns:
2579 	common->nluns = i + 1;
2580 error_release:
2581 	common->state = FSG_STATE_TERMINATED;	/* The thread is dead */
2582 	/* Call fsg_common_release() directly, ref might be not
2583 	 * initialised */
2584 	fsg_common_release(&common->ref);
2585 	return ERR_PTR(rc);
2586 }
2587 
2588 static void fsg_common_release(struct kref *ref)
2589 {
2590 	struct fsg_common *common = container_of(ref, struct fsg_common, ref);
2591 
2592 	/* If the thread isn't already dead, tell it to exit now */
2593 	if (common->state != FSG_STATE_TERMINATED) {
2594 		raise_exception(common, FSG_STATE_EXIT);
2595 		wait_for_completion(&common->thread_notifier);
2596 	}
2597 
2598 	if (likely(common->luns)) {
2599 		struct fsg_lun *lun = common->luns;
2600 		unsigned i = common->nluns;
2601 
2602 		/* In error recovery common->nluns may be zero. */
2603 		for (; i; --i, ++lun)
2604 			fsg_lun_close(lun);
2605 
2606 		kfree(common->luns);
2607 	}
2608 
2609 	{
2610 		struct fsg_buffhd *bh = common->buffhds;
2611 		unsigned i = FSG_NUM_BUFFERS;
2612 		do {
2613 			kfree(bh->buf);
2614 		} while (++bh, --i);
2615 	}
2616 
2617 	if (common->free_storage_on_release)
2618 		kfree(common);
2619 }
2620 
2621 
2622 /*-------------------------------------------------------------------------*/
2623 
2624 /**
2625  * usb_copy_descriptors - copy a vector of USB descriptors
2626  * @src: null-terminated vector to copy
2627  * Context: initialization code, which may sleep
2628  *
2629  * This makes a copy of a vector of USB descriptors.  Its primary use
2630  * is to support usb_function objects which can have multiple copies,
2631  * each needing different descriptors.  Functions may have static
2632  * tables of descriptors, which are used as templates and customized
2633  * with identifiers (for interfaces, strings, endpoints, and more)
2634  * as needed by a given function instance.
2635  */
2636 struct usb_descriptor_header **
2637 usb_copy_descriptors(struct usb_descriptor_header **src)
2638 {
2639 	struct usb_descriptor_header **tmp;
2640 	unsigned bytes;
2641 	unsigned n_desc;
2642 	void *mem;
2643 	struct usb_descriptor_header **ret;
2644 
2645 	/* count descriptors and their sizes; then add vector size */
2646 	for (bytes = 0, n_desc = 0, tmp = src; *tmp; tmp++, n_desc++)
2647 		bytes += (*tmp)->bLength;
2648 	bytes += (n_desc + 1) * sizeof(*tmp);
2649 
2650 	mem = memalign(CONFIG_SYS_CACHELINE_SIZE, bytes);
2651 	if (!mem)
2652 		return NULL;
2653 
2654 	/* fill in pointers starting at "tmp",
2655 	 * to descriptors copied starting at "mem";
2656 	 * and return "ret"
2657 	 */
2658 	tmp = mem;
2659 	ret = mem;
2660 	mem += (n_desc + 1) * sizeof(*tmp);
2661 	while (*src) {
2662 		memcpy(mem, *src, (*src)->bLength);
2663 		*tmp = mem;
2664 		tmp++;
2665 		mem += (*src)->bLength;
2666 		src++;
2667 	}
2668 	*tmp = NULL;
2669 
2670 	return ret;
2671 }
2672 
2673 static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
2674 {
2675 	struct fsg_dev		*fsg = fsg_from_func(f);
2676 
2677 	DBG(fsg, "unbind\n");
2678 	if (fsg->common->fsg == fsg) {
2679 		fsg->common->new_fsg = NULL;
2680 		raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2681 	}
2682 
2683 	free(fsg->function.descriptors);
2684 	free(fsg->function.hs_descriptors);
2685 	kfree(fsg);
2686 }
2687 
2688 static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
2689 {
2690 	struct fsg_dev		*fsg = fsg_from_func(f);
2691 	struct usb_gadget	*gadget = c->cdev->gadget;
2692 	int			i;
2693 	struct usb_ep		*ep;
2694 	fsg->gadget = gadget;
2695 
2696 	/* New interface */
2697 	i = usb_interface_id(c, f);
2698 	if (i < 0)
2699 		return i;
2700 	fsg_intf_desc.bInterfaceNumber = i;
2701 	fsg->interface_number = i;
2702 
2703 	/* Find all the endpoints we will use */
2704 	ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
2705 	if (!ep)
2706 		goto autoconf_fail;
2707 	ep->driver_data = fsg->common;	/* claim the endpoint */
2708 	fsg->bulk_in = ep;
2709 
2710 	ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
2711 	if (!ep)
2712 		goto autoconf_fail;
2713 	ep->driver_data = fsg->common;	/* claim the endpoint */
2714 	fsg->bulk_out = ep;
2715 
2716 	/* Copy descriptors */
2717 	if (IS_RKUSB_UMS_DNL(c->cdev->driver->name))
2718 		f->descriptors = usb_copy_descriptors(rkusb_fs_function);
2719 	else
2720 		f->descriptors = usb_copy_descriptors(fsg_fs_function);
2721 	if (unlikely(!f->descriptors))
2722 		return -ENOMEM;
2723 
2724 	if (gadget_is_dualspeed(gadget)) {
2725 		/* Assume endpoint addresses are the same for both speeds */
2726 		fsg_hs_bulk_in_desc.bEndpointAddress =
2727 			fsg_fs_bulk_in_desc.bEndpointAddress;
2728 		fsg_hs_bulk_out_desc.bEndpointAddress =
2729 			fsg_fs_bulk_out_desc.bEndpointAddress;
2730 
2731 		if (IS_RKUSB_UMS_DNL(c->cdev->driver->name))
2732 			f->hs_descriptors =
2733 				usb_copy_descriptors(rkusb_hs_function);
2734 		else
2735 			f->hs_descriptors =
2736 				usb_copy_descriptors(fsg_hs_function);
2737 		if (unlikely(!f->hs_descriptors)) {
2738 			free(f->descriptors);
2739 			return -ENOMEM;
2740 		}
2741 	}
2742 
2743 	if (gadget_is_superspeed(gadget)) {
2744 		/* Assume endpoint addresses are the same as full speed */
2745 		fsg_ss_bulk_in_desc.bEndpointAddress =
2746 			fsg_fs_bulk_in_desc.bEndpointAddress;
2747 		fsg_ss_bulk_out_desc.bEndpointAddress =
2748 			fsg_fs_bulk_out_desc.bEndpointAddress;
2749 
2750 #ifdef CONFIG_CMD_ROCKUSB
2751 		if (IS_RKUSB_UMS_DNL(c->cdev->driver->name))
2752 			f->ss_descriptors =
2753 				usb_copy_descriptors(rkusb_ss_function);
2754 #endif
2755 
2756 		if (unlikely(!f->ss_descriptors)) {
2757 			free(f->descriptors);
2758 			return -ENOMEM;
2759 		}
2760 	}
2761 	return 0;
2762 
2763 autoconf_fail:
2764 	ERROR(fsg, "unable to autoconfigure all endpoints\n");
2765 	return -ENOTSUPP;
2766 }
2767 
2768 
2769 /****************************** ADD FUNCTION ******************************/
2770 
2771 static struct usb_gadget_strings *fsg_strings_array[] = {
2772 	&fsg_stringtab,
2773 	NULL,
2774 };
2775 
2776 static int fsg_bind_config(struct usb_composite_dev *cdev,
2777 			   struct usb_configuration *c,
2778 			   struct fsg_common *common)
2779 {
2780 	struct fsg_dev *fsg;
2781 	int rc;
2782 
2783 	fsg = calloc(1, sizeof *fsg);
2784 	if (!fsg)
2785 		return -ENOMEM;
2786 	fsg->function.name        = FSG_DRIVER_DESC;
2787 	fsg->function.strings     = fsg_strings_array;
2788 	fsg->function.bind        = fsg_bind;
2789 	fsg->function.unbind      = fsg_unbind;
2790 	fsg->function.setup       = fsg_setup;
2791 	fsg->function.set_alt     = fsg_set_alt;
2792 	fsg->function.disable     = fsg_disable;
2793 
2794 	fsg->common               = common;
2795 	common->fsg               = fsg;
2796 	/* Our caller holds a reference to common structure so we
2797 	 * don't have to be worry about it being freed until we return
2798 	 * from this function.  So instead of incrementing counter now
2799 	 * and decrement in error recovery we increment it only when
2800 	 * call to usb_add_function() was successful. */
2801 
2802 	rc = usb_add_function(c, &fsg->function);
2803 
2804 	if (rc)
2805 		kfree(fsg);
2806 
2807 	return rc;
2808 }
2809 
2810 int fsg_add(struct usb_configuration *c)
2811 {
2812 	struct fsg_common *fsg_common;
2813 
2814 	fsg_common = fsg_common_init(NULL, c->cdev);
2815 
2816 	fsg_common->vendor_name = 0;
2817 	fsg_common->product_name = 0;
2818 	fsg_common->release = 0xffff;
2819 
2820 	fsg_common->ops = NULL;
2821 	fsg_common->private_data = NULL;
2822 
2823 	the_fsg_common = fsg_common;
2824 
2825 	return fsg_bind_config(c->cdev, c, fsg_common);
2826 }
2827 
2828 int fsg_init(struct ums *ums_devs, int count)
2829 {
2830 	ums = ums_devs;
2831 	ums_count = count;
2832 
2833 	return 0;
2834 }
2835 
2836 DECLARE_GADGET_BIND_CALLBACK(usb_dnl_ums, fsg_add);
2837