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