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