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