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