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