f_fs.c 90.4 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0+
2
/*
3
 * f_fs.c -- user mode file system API for USB composite function controllers
4 5
 *
 * Copyright (C) 2010 Samsung Electronics
6
 * Author: Michal Nazarewicz <mina86@mina86.com>
7
 *
8
 * Based on inode.c (GadgetFS) which was:
9 10 11 12 13 14 15 16 17
 * Copyright (C) 2003-2004 David Brownell
 * Copyright (C) 2003 Agilent Technologies
 */


/* #define DEBUG */
/* #define VERBOSE_DEBUG */

#include <linux/blkdev.h>
18
#include <linux/pagemap.h>
19
#include <linux/export.h>
20
#include <linux/fs_parser.h>
21
#include <linux/hid.h>
22
#include <linux/mm.h>
23
#include <linux/module.h>
24
#include <linux/scatterlist.h>
25
#include <linux/sched/signal.h>
26
#include <linux/uio.h>
27
#include <linux/vmalloc.h>
28 29
#include <asm/unaligned.h>

30
#include <linux/usb/ccid.h>
31 32 33
#include <linux/usb/composite.h>
#include <linux/usb/functionfs.h>

34
#include <linux/aio.h>
35
#include <linux/kthread.h>
36
#include <linux/poll.h>
37
#include <linux/eventfd.h>
38

39
#include "u_fs.h"
40
#include "u_f.h"
41
#include "u_os_desc.h"
42
#include "configfs.h"
43 44 45 46 47 48 49

#define FUNCTIONFS_MAGIC	0xa647361 /* Chosen by a honest dice roll ;) */

/* Reference counter handling */
static void ffs_data_get(struct ffs_data *ffs);
static void ffs_data_put(struct ffs_data *ffs);
/* Creates new ffs_data object. */
50 51
static struct ffs_data *__must_check ffs_data_new(const char *dev_name)
	__attribute__((malloc));
52 53 54 55 56

/* Opened counter handling. */
static void ffs_data_opened(struct ffs_data *ffs);
static void ffs_data_closed(struct ffs_data *ffs);

57
/* Called with ffs->mutex held; take over ownership of data. */
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
static int __must_check
__ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
static int __must_check
__ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);


/* The function structure ***************************************************/

struct ffs_ep;

struct ffs_function {
	struct usb_configuration	*conf;
	struct usb_gadget		*gadget;
	struct ffs_data			*ffs;

	struct ffs_ep			*eps;
	u8				eps_revmap[16];
	short				*interfaces_nums;

	struct usb_function		function;
};


static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
{
	return container_of(f, struct ffs_function, function);
}


87 88 89 90 91 92 93 94
static inline enum ffs_setup_state
ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
{
	return (enum ffs_setup_state)
		cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
}


95 96 97 98 99 100 101 102 103
static void ffs_func_eps_disable(struct ffs_function *func);
static int __must_check ffs_func_eps_enable(struct ffs_function *func);

static int ffs_func_bind(struct usb_configuration *,
			 struct usb_function *);
static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
static void ffs_func_disable(struct usb_function *);
static int ffs_func_setup(struct usb_function *,
			  const struct usb_ctrlrequest *);
104
static bool ffs_func_req_match(struct usb_function *,
105 106
			       const struct usb_ctrlrequest *,
			       bool config0);
107 108 109 110 111 112 113 114 115 116 117 118 119 120
static void ffs_func_suspend(struct usb_function *);
static void ffs_func_resume(struct usb_function *);


static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);


/* The endpoints structures *************************************************/

struct ffs_ep {
	struct usb_ep			*ep;	/* P: ffs->eps_lock */
	struct usb_request		*req;	/* P: epfile->mutex */

121 122
	/* [0]: full speed, [1]: high speed, [2]: super speed */
	struct usb_endpoint_descriptor	*descs[3];
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

	u8				num;

	int				status;	/* P: epfile->mutex */
};

struct ffs_epfile {
	/* Protects ep->ep and ep->req. */
	struct mutex			mutex;

	struct ffs_data			*ffs;
	struct ffs_ep			*ep;	/* P: ffs->eps_lock */

	struct dentry			*dentry;

138 139 140
	/*
	 * Buffer for holding data from partial reads which may happen since
	 * we’re rounding user read requests to a multiple of a max packet size.
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
	 *
	 * The pointer is initialised with NULL value and may be set by
	 * __ffs_epfile_read_data function to point to a temporary buffer.
	 *
	 * In normal operation, calls to __ffs_epfile_read_buffered will consume
	 * data from said buffer and eventually free it.  Importantly, while the
	 * function is using the buffer, it sets the pointer to NULL.  This is
	 * all right since __ffs_epfile_read_data and __ffs_epfile_read_buffered
	 * can never run concurrently (they are synchronised by epfile->mutex)
	 * so the latter will not assign a new value to the pointer.
	 *
	 * Meanwhile ffs_func_eps_disable frees the buffer (if the pointer is
	 * valid) and sets the pointer to READ_BUFFER_DROP value.  This special
	 * value is crux of the synchronisation between ffs_func_eps_disable and
	 * __ffs_epfile_read_data.
	 *
	 * Once __ffs_epfile_read_data is about to finish it will try to set the
	 * pointer back to its old value (as described above), but seeing as the
	 * pointer is not-NULL (namely READ_BUFFER_DROP) it will instead free
	 * the buffer.
	 *
	 * == State transitions ==
	 *
	 * • ptr == NULL:  (initial state)
	 *   ◦ __ffs_epfile_read_buffer_free: go to ptr == DROP
	 *   ◦ __ffs_epfile_read_buffered:    nop
	 *   ◦ __ffs_epfile_read_data allocates temp buffer: go to ptr == buf
	 *   ◦ reading finishes:              n/a, not in ‘and reading’ state
	 * • ptr == DROP:
	 *   ◦ __ffs_epfile_read_buffer_free: nop
	 *   ◦ __ffs_epfile_read_buffered:    go to ptr == NULL
	 *   ◦ __ffs_epfile_read_data allocates temp buffer: free buf, nop
	 *   ◦ reading finishes:              n/a, not in ‘and reading’ state
	 * • ptr == buf:
	 *   ◦ __ffs_epfile_read_buffer_free: free buf, go to ptr == DROP
	 *   ◦ __ffs_epfile_read_buffered:    go to ptr == NULL and reading
	 *   ◦ __ffs_epfile_read_data:        n/a, __ffs_epfile_read_buffered
	 *                                    is always called first
	 *   ◦ reading finishes:              n/a, not in ‘and reading’ state
	 * • ptr == NULL and reading:
	 *   ◦ __ffs_epfile_read_buffer_free: go to ptr == DROP and reading
	 *   ◦ __ffs_epfile_read_buffered:    n/a, mutex is held
	 *   ◦ __ffs_epfile_read_data:        n/a, mutex is held
	 *   ◦ reading finishes and …
	 *     … all data read:               free buf, go to ptr == NULL
	 *     … otherwise:                   go to ptr == buf and reading
	 * • ptr == DROP and reading:
	 *   ◦ __ffs_epfile_read_buffer_free: nop
	 *   ◦ __ffs_epfile_read_buffered:    n/a, mutex is held
	 *   ◦ __ffs_epfile_read_data:        n/a, mutex is held
	 *   ◦ reading finishes:              free buf, go to ptr == DROP
192
	 */
193 194
	struct ffs_buffer		*read_buffer;
#define READ_BUFFER_DROP ((struct ffs_buffer *)ERR_PTR(-ESHUTDOWN))
195

196 197 198 199 200 201 202 203
	char				name[5];

	unsigned char			in;	/* P: ffs->eps_lock */
	unsigned char			isoc;	/* P: ffs->eps_lock */

	unsigned char			_pad;
};

204 205 206 207 208 209
struct ffs_buffer {
	size_t length;
	char *data;
	char storage[];
};

210 211 212 213 214 215 216
/*  ffs_io_data structure ***************************************************/

struct ffs_io_data {
	bool aio;
	bool read;

	struct kiocb *kiocb;
217 218 219
	struct iov_iter data;
	const void *to_free;
	char *buf;
220 221 222 223 224 225

	struct mm_struct *mm;
	struct work_struct work;

	struct usb_ep *ep;
	struct usb_request *req;
226 227
	struct sg_table sgt;
	bool use_sg;
228 229

	struct ffs_data *ffs;
230 231
};

232 233 234 235 236 237
struct ffs_desc_helper {
	struct ffs_data *ffs;
	unsigned interfaces_count;
	unsigned eps_count;
};

238 239 240
static int  __must_check ffs_epfiles_create(struct ffs_data *ffs);
static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);

A
Al Viro 已提交
241
static struct dentry *
242
ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
A
Al Viro 已提交
243
		   const struct file_operations *fops);
244

245 246 247
/* Devices management *******************************************************/

DEFINE_MUTEX(ffs_lock);
248
EXPORT_SYMBOL_GPL(ffs_lock);
249

250 251 252
static struct ffs_dev *_ffs_find_dev(const char *name);
static struct ffs_dev *_ffs_alloc_dev(void);
static void _ffs_free_dev(struct ffs_dev *dev);
253 254 255 256
static void *ffs_acquire_dev(const char *dev_name);
static void ffs_release_dev(struct ffs_data *ffs_data);
static int ffs_ready(struct ffs_data *ffs);
static void ffs_closed(struct ffs_data *ffs);
257 258 259 260 261

/* Misc helper functions ****************************************************/

static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
	__attribute__((warn_unused_result, nonnull));
A
Al Viro 已提交
262
static char *ffs_prepare_buffer(const char __user *buf, size_t len)
263 264 265 266 267 268 269 270 271
	__attribute__((warn_unused_result, nonnull));


/* Control file aka ep0 *****************************************************/

static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct ffs_data *ffs = req->context;

272
	complete(&ffs->ep0req_completion);
273 274 275
}

static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
276
	__releases(&ffs->ev.waitq.lock)
277 278 279 280 281 282 283 284 285 286 287
{
	struct usb_request *req = ffs->ep0req;
	int ret;

	req->zero     = len < le16_to_cpu(ffs->ev.setup.wLength);

	spin_unlock_irq(&ffs->ev.waitq.lock);

	req->buf      = data;
	req->length   = len;

288 289 290 291 292 293 294 295
	/*
	 * UDC layer requires to provide a buffer even for ZLP, but should
	 * not use it at all. Let's provide some poisoned pointer to catch
	 * possible bug in the driver.
	 */
	if (req->buf == NULL)
		req->buf = (void *)0xDEADBABE;

296
	reinit_completion(&ffs->ep0req_completion);
297 298 299 300 301 302 303 304 305 306 307 308

	ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
	if (unlikely(ret < 0))
		return ret;

	ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
	if (unlikely(ret)) {
		usb_ep_dequeue(ffs->gadget->ep0, req);
		return -EINTR;
	}

	ffs->setup_state = FFS_NO_SETUP;
309
	return req->status ? req->status : req->actual;
310 311 312 313 314
}

static int __ffs_ep0_stall(struct ffs_data *ffs)
{
	if (ffs->ev.can_stall) {
315
		pr_vdebug("ep0 stall\n");
316 317 318 319
		usb_ep_set_halt(ffs->gadget->ep0);
		ffs->setup_state = FFS_NO_SETUP;
		return -EL2HLT;
	} else {
320
		pr_debug("bogus ep0 stall!\n");
321 322 323 324 325 326 327 328 329 330 331 332 333 334
		return -ESRCH;
	}
}

static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
			     size_t len, loff_t *ptr)
{
	struct ffs_data *ffs = file->private_data;
	ssize_t ret;
	char *data;

	ENTER();

	/* Fast check if setup was canceled */
335
	if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
		return -EIDRM;

	/* Acquire mutex */
	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
	if (unlikely(ret < 0))
		return ret;

	/* Check state */
	switch (ffs->state) {
	case FFS_READ_DESCRIPTORS:
	case FFS_READ_STRINGS:
		/* Copy data */
		if (unlikely(len < 16)) {
			ret = -EINVAL;
			break;
		}

		data = ffs_prepare_buffer(buf, len);
354
		if (IS_ERR(data)) {
355 356 357 358 359 360
			ret = PTR_ERR(data);
			break;
		}

		/* Handle data */
		if (ffs->state == FFS_READ_DESCRIPTORS) {
361
			pr_info("read descriptors\n");
362 363 364 365 366 367 368
			ret = __ffs_data_got_descs(ffs, data, len);
			if (unlikely(ret < 0))
				break;

			ffs->state = FFS_READ_STRINGS;
			ret = len;
		} else {
369
			pr_info("read strings\n");
370 371 372 373 374 375 376 377 378 379 380 381 382
			ret = __ffs_data_got_strings(ffs, data, len);
			if (unlikely(ret < 0))
				break;

			ret = ffs_epfiles_create(ffs);
			if (unlikely(ret)) {
				ffs->state = FFS_CLOSING;
				break;
			}

			ffs->state = FFS_ACTIVE;
			mutex_unlock(&ffs->mutex);

383
			ret = ffs_ready(ffs);
384 385 386 387 388 389 390 391 392 393 394
			if (unlikely(ret < 0)) {
				ffs->state = FFS_CLOSING;
				return ret;
			}

			return len;
		}
		break;

	case FFS_ACTIVE:
		data = NULL;
395 396 397 398
		/*
		 * We're called from user space, we can use _irq
		 * rather then _irqsave
		 */
399
		spin_lock_irq(&ffs->ev.waitq.lock);
400
		switch (ffs_setup_state_clear_cancelled(ffs)) {
401
		case FFS_SETUP_CANCELLED:
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
			ret = -EIDRM;
			goto done_spin;

		case FFS_NO_SETUP:
			ret = -ESRCH;
			goto done_spin;

		case FFS_SETUP_PENDING:
			break;
		}

		/* FFS_SETUP_PENDING */
		if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
			spin_unlock_irq(&ffs->ev.waitq.lock);
			ret = __ffs_ep0_stall(ffs);
			break;
		}

		/* FFS_SETUP_PENDING and not stall */
		len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));

		spin_unlock_irq(&ffs->ev.waitq.lock);

		data = ffs_prepare_buffer(buf, len);
426
		if (IS_ERR(data)) {
427 428 429 430 431 432
			ret = PTR_ERR(data);
			break;
		}

		spin_lock_irq(&ffs->ev.waitq.lock);

433 434
		/*
		 * We are guaranteed to be still in FFS_ACTIVE state
435
		 * but the state of setup could have changed from
436
		 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
437
		 * to check for that.  If that happened we copied data
438 439 440
		 * from user space in vain but it's unlikely.
		 *
		 * For sure we are not in FFS_NO_SETUP since this is
441 442
		 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
		 * transition can be performed and it's protected by
443 444
		 * mutex.
		 */
445 446
		if (ffs_setup_state_clear_cancelled(ffs) ==
		    FFS_SETUP_CANCELLED) {
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
			ret = -EIDRM;
done_spin:
			spin_unlock_irq(&ffs->ev.waitq.lock);
		} else {
			/* unlocks spinlock */
			ret = __ffs_ep0_queue_wait(ffs, data, len);
		}
		kfree(data);
		break;

	default:
		ret = -EBADFD;
		break;
	}

	mutex_unlock(&ffs->mutex);
	return ret;
}

466
/* Called with ffs->ev.waitq.lock and ffs->mutex held, both released on exit. */
467 468
static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
				     size_t n)
469
	__releases(&ffs->ev.waitq.lock)
470
{
471
	/*
472 473 474
	 * n cannot be bigger than ffs->ev.count, which cannot be bigger than
	 * size of ffs->ev.types array (which is four) so that's how much space
	 * we reserve.
475
	 */
476 477
	struct usb_functionfs_event events[ARRAY_SIZE(ffs->ev.types)];
	const size_t size = n * sizeof *events;
478 479
	unsigned i = 0;

480
	memset(events, 0, size);
481 482 483 484 485 486 487 488 489

	do {
		events[i].type = ffs->ev.types[i];
		if (events[i].type == FUNCTIONFS_SETUP) {
			events[i].u.setup = ffs->ev.setup;
			ffs->setup_state = FFS_SETUP_PENDING;
		}
	} while (++i < n);

490 491
	ffs->ev.count -= n;
	if (ffs->ev.count)
492 493 494 495 496 497
		memmove(ffs->ev.types, ffs->ev.types + n,
			ffs->ev.count * sizeof *ffs->ev.types);

	spin_unlock_irq(&ffs->ev.waitq.lock);
	mutex_unlock(&ffs->mutex);

498
	return unlikely(copy_to_user(buf, events, size)) ? -EFAULT : size;
499 500 501 502 503 504 505 506 507 508 509 510 511
}

static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
			    size_t len, loff_t *ptr)
{
	struct ffs_data *ffs = file->private_data;
	char *data = NULL;
	size_t n;
	int ret;

	ENTER();

	/* Fast check if setup was canceled */
512
	if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
513 514 515 516 517 518 519 520 521 522 523 524 525
		return -EIDRM;

	/* Acquire mutex */
	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
	if (unlikely(ret < 0))
		return ret;

	/* Check state */
	if (ffs->state != FFS_ACTIVE) {
		ret = -EBADFD;
		goto done_mutex;
	}

526 527 528 529
	/*
	 * We're called from user space, we can use _irq rather then
	 * _irqsave
	 */
530 531
	spin_lock_irq(&ffs->ev.waitq.lock);

532
	switch (ffs_setup_state_clear_cancelled(ffs)) {
533
	case FFS_SETUP_CANCELLED:
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
		ret = -EIDRM;
		break;

	case FFS_NO_SETUP:
		n = len / sizeof(struct usb_functionfs_event);
		if (unlikely(!n)) {
			ret = -EINVAL;
			break;
		}

		if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
			ret = -EAGAIN;
			break;
		}

549 550
		if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
							ffs->ev.count)) {
551 552 553 554
			ret = -EINTR;
			break;
		}

555
		/* unlocks spinlock */
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
		return __ffs_ep0_read_events(ffs, buf,
					     min(n, (size_t)ffs->ev.count));

	case FFS_SETUP_PENDING:
		if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
			spin_unlock_irq(&ffs->ev.waitq.lock);
			ret = __ffs_ep0_stall(ffs);
			goto done_mutex;
		}

		len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));

		spin_unlock_irq(&ffs->ev.waitq.lock);

		if (likely(len)) {
			data = kmalloc(len, GFP_KERNEL);
			if (unlikely(!data)) {
				ret = -ENOMEM;
				goto done_mutex;
			}
		}

		spin_lock_irq(&ffs->ev.waitq.lock);

		/* See ffs_ep0_write() */
581 582
		if (ffs_setup_state_clear_cancelled(ffs) ==
		    FFS_SETUP_CANCELLED) {
583 584 585 586 587 588
			ret = -EIDRM;
			break;
		}

		/* unlocks spinlock */
		ret = __ffs_ep0_queue_wait(ffs, data, len);
589
		if (likely(ret > 0) && unlikely(copy_to_user(buf, data, len)))
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
			ret = -EFAULT;
		goto done_mutex;

	default:
		ret = -EBADFD;
		break;
	}

	spin_unlock_irq(&ffs->ev.waitq.lock);
done_mutex:
	mutex_unlock(&ffs->mutex);
	kfree(data);
	return ret;
}

static int ffs_ep0_open(struct inode *inode, struct file *file)
{
	struct ffs_data *ffs = inode->i_private;

	ENTER();

	if (unlikely(ffs->state == FFS_CLOSING))
		return -EBUSY;

	file->private_data = ffs;
	ffs_data_opened(ffs);

	return 0;
}

static int ffs_ep0_release(struct inode *inode, struct file *file)
{
	struct ffs_data *ffs = file->private_data;

	ENTER();

	ffs_data_closed(ffs);

	return 0;
}

static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
{
	struct ffs_data *ffs = file->private_data;
	struct usb_gadget *gadget = ffs->gadget;
	long ret;

	ENTER();

	if (code == FUNCTIONFS_INTERFACE_REVMAP) {
		struct ffs_function *func = ffs->func;
		ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
642
	} else if (gadget && gadget->ops->ioctl) {
643 644 645 646 647 648 649 650
		ret = gadget->ops->ioctl(gadget, code, value);
	} else {
		ret = -ENOTTY;
	}

	return ret;
}

651
static __poll_t ffs_ep0_poll(struct file *file, poll_table *wait)
652 653
{
	struct ffs_data *ffs = file->private_data;
654
	__poll_t mask = EPOLLWRNORM;
655 656 657 658 659 660 661 662 663 664 665
	int ret;

	poll_wait(file, &ffs->ev.waitq, wait);

	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
	if (unlikely(ret < 0))
		return mask;

	switch (ffs->state) {
	case FFS_READ_DESCRIPTORS:
	case FFS_READ_STRINGS:
666
		mask |= EPOLLOUT;
667 668 669 670 671 672
		break;

	case FFS_ACTIVE:
		switch (ffs->setup_state) {
		case FFS_NO_SETUP:
			if (ffs->ev.count)
673
				mask |= EPOLLIN;
674 675 676 677
			break;

		case FFS_SETUP_PENDING:
		case FFS_SETUP_CANCELLED:
678
			mask |= (EPOLLIN | EPOLLOUT);
679 680
			break;
		}
681 682
		break;

683 684
	case FFS_CLOSING:
		break;
685 686
	case FFS_DEACTIVATED:
		break;
687 688 689 690 691 692 693
	}

	mutex_unlock(&ffs->mutex);

	return mask;
}

694 695 696 697 698 699 700 701
static const struct file_operations ffs_ep0_operations = {
	.llseek =	no_llseek,

	.open =		ffs_ep0_open,
	.write =	ffs_ep0_write,
	.read =		ffs_ep0_read,
	.release =	ffs_ep0_release,
	.unlocked_ioctl =	ffs_ep0_ioctl,
702
	.poll =		ffs_ep0_poll,
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
};


/* "Normal" endpoints operations ********************************************/

static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
{
	ENTER();
	if (likely(req->context)) {
		struct ffs_ep *ep = _ep->driver_data;
		ep->status = req->status ? req->status : req->actual;
		complete(req->context);
	}
}

718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
static ssize_t ffs_copy_to_iter(void *data, int data_len, struct iov_iter *iter)
{
	ssize_t ret = copy_to_iter(data, data_len, iter);
	if (likely(ret == data_len))
		return ret;

	if (unlikely(iov_iter_count(iter)))
		return -EFAULT;

	/*
	 * Dear user space developer!
	 *
	 * TL;DR: To stop getting below error message in your kernel log, change
	 * user space code using functionfs to align read buffers to a max
	 * packet size.
	 *
	 * Some UDCs (e.g. dwc3) require request sizes to be a multiple of a max
	 * packet size.  When unaligned buffer is passed to functionfs, it
	 * internally uses a larger, aligned buffer so that such UDCs are happy.
	 *
	 * Unfortunately, this means that host may send more data than was
	 * requested in read(2) system call.  f_fs doesn’t know what to do with
	 * that excess data so it simply drops it.
	 *
	 * Was the buffer aligned in the first place, no such problem would
	 * happen.
	 *
745 746 747 748 749
	 * Data may be dropped only in AIO reads.  Synchronous reads are handled
	 * by splitting a request into multiple parts.  This splitting may still
	 * be a problem though so it’s likely best to align the buffer
	 * regardless of it being AIO or not..
	 *
750 751 752 753 754 755 756 757 758 759 760
	 * This only affects OUT endpoints, i.e. reading data with a read(2),
	 * aio_read(2) etc. system calls.  Writing data to an IN endpoint is not
	 * affected.
	 */
	pr_err("functionfs read size %d > requested size %zd, dropping excess data. "
	       "Align read buffer size to max packet size to avoid the problem.\n",
	       data_len, ret);

	return ret;
}

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
/*
 * allocate a virtually contiguous buffer and create a scatterlist describing it
 * @sg_table	- pointer to a place to be filled with sg_table contents
 * @size	- required buffer size
 */
static void *ffs_build_sg_list(struct sg_table *sgt, size_t sz)
{
	struct page **pages;
	void *vaddr, *ptr;
	unsigned int n_pages;
	int i;

	vaddr = vmalloc(sz);
	if (!vaddr)
		return NULL;

	n_pages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
	pages = kvmalloc_array(n_pages, sizeof(struct page *), GFP_KERNEL);
	if (!pages) {
		vfree(vaddr);

		return NULL;
	}
	for (i = 0, ptr = vaddr; i < n_pages; ++i, ptr += PAGE_SIZE)
		pages[i] = vmalloc_to_page(ptr);

	if (sg_alloc_table_from_pages(sgt, pages, n_pages, 0, sz, GFP_KERNEL)) {
		kvfree(pages);
		vfree(vaddr);

		return NULL;
	}
	kvfree(pages);

	return vaddr;
}

static inline void *ffs_alloc_buffer(struct ffs_io_data *io_data,
	size_t data_len)
{
	if (io_data->use_sg)
		return ffs_build_sg_list(&io_data->sgt, data_len);

	return kmalloc(data_len, GFP_KERNEL);
}

static inline void ffs_free_buffer(struct ffs_io_data *io_data)
{
	if (!io_data->buf)
		return;

	if (io_data->use_sg) {
		sg_free_table(&io_data->sgt);
		vfree(io_data->buf);
	} else {
		kfree(io_data->buf);
	}
}

820 821 822 823 824 825
static void ffs_user_copy_worker(struct work_struct *work)
{
	struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
						   work);
	int ret = io_data->req->status ? io_data->req->status :
					 io_data->req->actual;
826
	bool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;
827 828

	if (io_data->read && ret > 0) {
829
		kthread_use_mm(io_data->mm);
830
		ret = ffs_copy_to_iter(io_data->buf, ret, &io_data->data);
831
		kthread_unuse_mm(io_data->mm);
832 833
	}

834
	io_data->kiocb->ki_complete(io_data->kiocb, ret, ret);
835

836
	if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd)
837 838
		eventfd_signal(io_data->ffs->ffs_eventfd, 1);

839 840 841
	usb_ep_free_request(io_data->ep, io_data->req);

	if (io_data->read)
842
		kfree(io_data->to_free);
843
	ffs_free_buffer(io_data);
844 845 846 847 848 849 850
	kfree(io_data);
}

static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
					 struct usb_request *req)
{
	struct ffs_io_data *io_data = req->context;
851
	struct ffs_data *ffs = io_data->ffs;
852 853 854 855

	ENTER();

	INIT_WORK(&io_data->work, ffs_user_copy_worker);
856
	queue_work(ffs->io_completion_wq, &io_data->work);
857 858
}

859 860 861 862 863 864 865 866 867 868 869
static void __ffs_epfile_read_buffer_free(struct ffs_epfile *epfile)
{
	/*
	 * See comment in struct ffs_epfile for full read_buffer pointer
	 * synchronisation story.
	 */
	struct ffs_buffer *buf = xchg(&epfile->read_buffer, READ_BUFFER_DROP);
	if (buf && buf != READ_BUFFER_DROP)
		kfree(buf);
}

870 871 872 873
/* Assumes epfile->mutex is held. */
static ssize_t __ffs_epfile_read_buffered(struct ffs_epfile *epfile,
					  struct iov_iter *iter)
{
874 875 876 877 878 879
	/*
	 * Null out epfile->read_buffer so ffs_func_eps_disable does not free
	 * the buffer while we are using it.  See comment in struct ffs_epfile
	 * for full read_buffer pointer synchronisation story.
	 */
	struct ffs_buffer *buf = xchg(&epfile->read_buffer, NULL);
880
	ssize_t ret;
881
	if (!buf || buf == READ_BUFFER_DROP)
882 883 884 885 886
		return 0;

	ret = copy_to_iter(buf->data, buf->length, iter);
	if (buf->length == ret) {
		kfree(buf);
887 888 889 890
		return ret;
	}

	if (unlikely(iov_iter_count(iter))) {
891 892 893 894 895
		ret = -EFAULT;
	} else {
		buf->length -= ret;
		buf->data += ret;
	}
896 897 898 899

	if (cmpxchg(&epfile->read_buffer, NULL, buf))
		kfree(buf);

900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	return ret;
}

/* Assumes epfile->mutex is held. */
static ssize_t __ffs_epfile_read_data(struct ffs_epfile *epfile,
				      void *data, int data_len,
				      struct iov_iter *iter)
{
	struct ffs_buffer *buf;

	ssize_t ret = copy_to_iter(data, data_len, iter);
	if (likely(data_len == ret))
		return ret;

	if (unlikely(iov_iter_count(iter)))
		return -EFAULT;

	/* See ffs_copy_to_iter for more context. */
	pr_warn("functionfs read size %d > requested size %zd, splitting request into multiple reads.",
		data_len, ret);

	data_len -= ret;
	buf = kmalloc(sizeof(*buf) + data_len, GFP_KERNEL);
923 924
	if (!buf)
		return -ENOMEM;
925 926 927
	buf->length = data_len;
	buf->data = buf->storage;
	memcpy(buf->storage, data + ret, data_len);
928 929 930 931 932 933 934 935 936

	/*
	 * At this point read_buffer is NULL or READ_BUFFER_DROP (if
	 * ffs_func_eps_disable has been called in the meanwhile).  See comment
	 * in struct ffs_epfile for full read_buffer pointer synchronisation
	 * story.
	 */
	if (unlikely(cmpxchg(&epfile->read_buffer, NULL, buf)))
		kfree(buf);
937 938 939 940

	return ret;
}

941
static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
942 943
{
	struct ffs_epfile *epfile = file->private_data;
944
	struct usb_request *req;
945 946
	struct ffs_ep *ep;
	char *data = NULL;
947
	ssize_t ret, data_len = -EINVAL;
948 949
	int halt;

950
	/* Are we still active? */
951 952
	if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
		return -ENODEV;
953

954 955 956
	/* Wait for endpoint to be enabled */
	ep = epfile->ep;
	if (!ep) {
957 958
		if (file->f_flags & O_NONBLOCK)
			return -EAGAIN;
959

960 961
		ret = wait_event_interruptible(
				epfile->ffs->wait, (ep = epfile->ep));
962 963
		if (ret)
			return -EINTR;
964
	}
965

966
	/* Do we halt? */
967
	halt = (!io_data->read == !epfile->in);
968 969
	if (halt && epfile->isoc)
		return -EINVAL;
970

971 972 973 974 975
	/* We will be using request and read_buffer */
	ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
	if (unlikely(ret))
		goto error;

976 977
	/* Allocate & copy */
	if (!halt) {
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
		struct usb_gadget *gadget;

		/*
		 * Do we have buffered data from previous partial read?  Check
		 * that for synchronous case only because we do not have
		 * facility to ‘wake up’ a pending asynchronous read and push
		 * buffered data to it which we would need to make things behave
		 * consistently.
		 */
		if (!io_data->aio && io_data->read) {
			ret = __ffs_epfile_read_buffered(epfile, &io_data->data);
			if (ret)
				goto error_mutex;
		}

993 994
		/*
		 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
995 996
		 * before the waiting completes, so do not assign to 'gadget'
		 * earlier
997
		 */
998
		gadget = epfile->ffs->gadget;
999

1000 1001 1002
		spin_lock_irq(&epfile->ffs->eps_lock);
		/* In the meantime, endpoint got disabled or changed. */
		if (epfile->ep != ep) {
1003 1004
			ret = -ESHUTDOWN;
			goto error_lock;
1005
		}
1006
		data_len = iov_iter_count(&io_data->data);
1007 1008 1009 1010
		/*
		 * Controller may require buffer size to be aligned to
		 * maxpacketsize of an out endpoint.
		 */
1011 1012
		if (io_data->read)
			data_len = usb_ep_align_maybe(gadget, ep->ep, data_len);
1013 1014

		io_data->use_sg = gadget->sg_supported && data_len > PAGE_SIZE;
1015
		spin_unlock_irq(&epfile->ffs->eps_lock);
1016

1017
		data = ffs_alloc_buffer(io_data, data_len);
1018 1019 1020 1021 1022
		if (unlikely(!data)) {
			ret = -ENOMEM;
			goto error_mutex;
		}
		if (!io_data->read &&
1023
		    !copy_from_iter_full(data, data_len, &io_data->data)) {
1024 1025
			ret = -EFAULT;
			goto error_mutex;
1026 1027
		}
	}
1028

1029
	spin_lock_irq(&epfile->ffs->eps_lock);
1030

1031 1032 1033 1034
	if (epfile->ep != ep) {
		/* In the meantime, endpoint got disabled or changed. */
		ret = -ESHUTDOWN;
	} else if (halt) {
1035 1036 1037
		ret = usb_ep_set_halt(ep->ep);
		if (!ret)
			ret = -EBADMSG;
1038
	} else if (unlikely(data_len == -EINVAL)) {
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
		/*
		 * Sanity Check: even though data_len can't be used
		 * uninitialized at the time I write this comment, some
		 * compilers complain about this situation.
		 * In order to keep the code clean from warnings, data_len is
		 * being initialized to -EINVAL during its declaration, which
		 * means we can't rely on compiler anymore to warn no future
		 * changes won't result in data_len being used uninitialized.
		 * For such reason, we're adding this redundant sanity check
		 * here.
		 */
1050 1051 1052 1053
		WARN(1, "%s: data_len == -EINVAL\n", __func__);
		ret = -EINVAL;
	} else if (!io_data->aio) {
		DECLARE_COMPLETION_ONSTACK(done);
1054
		bool interrupted = false;
1055

1056
		req = ep->req;
1057 1058 1059 1060 1061 1062
		if (io_data->use_sg) {
			req->buf = NULL;
			req->sg	= io_data->sgt.sgl;
			req->num_sgs = io_data->sgt.nents;
		} else {
			req->buf = data;
1063
			req->num_sgs = 0;
1064 1065 1066 1067
		}
		req->length = data_len;

		io_data->buf = data;
1068

1069 1070
		req->context  = &done;
		req->complete = ffs_epfile_io_complete;
1071

1072 1073 1074
		ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
		if (unlikely(ret < 0))
			goto error_lock;
1075

1076
		spin_unlock_irq(&epfile->ffs->eps_lock);
1077

1078
		if (unlikely(wait_for_completion_interruptible(&done))) {
1079 1080 1081 1082 1083 1084
			/*
			 * To avoid race condition with ffs_epfile_io_complete,
			 * dequeue the request first then check
			 * status. usb_ep_dequeue API should guarantee no race
			 * condition with req->complete callback.
			 */
1085
			usb_ep_dequeue(ep->ep, req);
1086
			wait_for_completion(&done);
1087
			interrupted = ep->status < 0;
1088
		}
1089

1090 1091 1092
		if (interrupted)
			ret = -EINTR;
		else if (io_data->read && ep->status > 0)
1093 1094
			ret = __ffs_epfile_read_data(epfile, data, ep->status,
						     &io_data->data);
1095 1096
		else
			ret = ep->status;
1097
		goto error_mutex;
1098
	} else if (!(req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC))) {
1099 1100
		ret = -ENOMEM;
	} else {
1101 1102 1103 1104 1105 1106
		if (io_data->use_sg) {
			req->buf = NULL;
			req->sg	= io_data->sgt.sgl;
			req->num_sgs = io_data->sgt.nents;
		} else {
			req->buf = data;
1107
			req->num_sgs = 0;
1108 1109
		}
		req->length = data_len;
1110

1111 1112 1113 1114
		io_data->buf = data;
		io_data->ep = ep->ep;
		io_data->req = req;
		io_data->ffs = epfile->ffs;
1115

1116 1117
		req->context  = io_data;
		req->complete = ffs_epfile_async_io_complete;
1118

1119 1120
		ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
		if (unlikely(ret)) {
1121
			io_data->req = NULL;
1122 1123
			usb_ep_free_request(ep->ep, req);
			goto error_lock;
1124 1125
		}

1126 1127 1128 1129 1130 1131 1132
		ret = -EIOCBQUEUED;
		/*
		 * Do not kfree the buffer in this function.  It will be freed
		 * by ffs_user_copy_worker.
		 */
		data = NULL;
	}
1133 1134 1135

error_lock:
	spin_unlock_irq(&epfile->ffs->eps_lock);
1136
error_mutex:
1137
	mutex_unlock(&epfile->mutex);
1138
error:
1139 1140
	if (ret != -EIOCBQUEUED) /* don't free if there is iocb queued */
		ffs_free_buffer(io_data);
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
	return ret;
}

static int
ffs_epfile_open(struct inode *inode, struct file *file)
{
	struct ffs_epfile *epfile = inode->i_private;

	ENTER();

	if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
		return -ENODEV;

	file->private_data = epfile;
	ffs_data_opened(epfile->ffs);

	return 0;
}

1160 1161 1162
static int ffs_aio_cancel(struct kiocb *kiocb)
{
	struct ffs_io_data *io_data = kiocb->private;
1163
	struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
1164
	unsigned long flags;
1165 1166 1167 1168
	int value;

	ENTER();

1169
	spin_lock_irqsave(&epfile->ffs->eps_lock, flags);
1170 1171 1172 1173

	if (likely(io_data && io_data->ep && io_data->req))
		value = usb_ep_dequeue(io_data->ep, io_data->req);
	else
1174
		value = -EINVAL;
1175

1176
	spin_unlock_irqrestore(&epfile->ffs->eps_lock, flags);
1177 1178 1179 1180

	return value;
}

1181
static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
1182
{
1183
	struct ffs_io_data io_data, *p = &io_data;
A
Al Viro 已提交
1184
	ssize_t res;
1185 1186 1187

	ENTER();

1188
	if (!is_sync_kiocb(kiocb)) {
1189
		p = kzalloc(sizeof(io_data), GFP_KERNEL);
1190 1191 1192 1193
		if (unlikely(!p))
			return -ENOMEM;
		p->aio = true;
	} else {
1194
		memset(p, 0, sizeof(*p));
1195 1196
		p->aio = false;
	}
1197

1198 1199 1200 1201
	p->read = false;
	p->kiocb = kiocb;
	p->data = *from;
	p->mm = current->mm;
1202

1203
	kiocb->private = p;
1204

1205 1206
	if (p->aio)
		kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1207

1208 1209 1210 1211 1212 1213 1214
	res = ffs_epfile_io(kiocb->ki_filp, p);
	if (res == -EIOCBQUEUED)
		return res;
	if (p->aio)
		kfree(p);
	else
		*from = p->data;
A
Al Viro 已提交
1215
	return res;
1216 1217
}

1218
static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
1219
{
1220
	struct ffs_io_data io_data, *p = &io_data;
A
Al Viro 已提交
1221
	ssize_t res;
1222 1223 1224

	ENTER();

1225
	if (!is_sync_kiocb(kiocb)) {
1226
		p = kzalloc(sizeof(io_data), GFP_KERNEL);
1227 1228 1229 1230
		if (unlikely(!p))
			return -ENOMEM;
		p->aio = true;
	} else {
1231
		memset(p, 0, sizeof(*p));
1232
		p->aio = false;
1233 1234
	}

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
	p->read = true;
	p->kiocb = kiocb;
	if (p->aio) {
		p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
		if (!p->to_free) {
			kfree(p);
			return -ENOMEM;
		}
	} else {
		p->data = *to;
		p->to_free = NULL;
	}
	p->mm = current->mm;
1248

1249
	kiocb->private = p;
1250

1251 1252
	if (p->aio)
		kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1253

1254 1255 1256 1257 1258 1259 1260 1261 1262
	res = ffs_epfile_io(kiocb->ki_filp, p);
	if (res == -EIOCBQUEUED)
		return res;

	if (p->aio) {
		kfree(p->to_free);
		kfree(p);
	} else {
		*to = p->data;
A
Al Viro 已提交
1263 1264
	}
	return res;
1265 1266
}

1267 1268 1269 1270 1271 1272 1273
static int
ffs_epfile_release(struct inode *inode, struct file *file)
{
	struct ffs_epfile *epfile = inode->i_private;

	ENTER();

1274
	__ffs_epfile_read_buffer_free(epfile);
1275 1276 1277 1278 1279 1280 1281 1282 1283
	ffs_data_closed(epfile->ffs);

	return 0;
}

static long ffs_epfile_ioctl(struct file *file, unsigned code,
			     unsigned long value)
{
	struct ffs_epfile *epfile = file->private_data;
1284
	struct ffs_ep *ep;
1285 1286 1287 1288 1289 1290 1291
	int ret;

	ENTER();

	if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
		return -ENODEV;

1292 1293 1294 1295 1296 1297
	/* Wait for endpoint to be enabled */
	ep = epfile->ep;
	if (!ep) {
		if (file->f_flags & O_NONBLOCK)
			return -EAGAIN;

1298 1299
		ret = wait_event_interruptible(
				epfile->ffs->wait, (ep = epfile->ep));
1300 1301 1302 1303
		if (ret)
			return -EINTR;
	}

1304
	spin_lock_irq(&epfile->ffs->eps_lock);
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328

	/* In the meantime, endpoint got disabled or changed. */
	if (epfile->ep != ep) {
		spin_unlock_irq(&epfile->ffs->eps_lock);
		return -ESHUTDOWN;
	}

	switch (code) {
	case FUNCTIONFS_FIFO_STATUS:
		ret = usb_ep_fifo_status(epfile->ep->ep);
		break;
	case FUNCTIONFS_FIFO_FLUSH:
		usb_ep_fifo_flush(epfile->ep->ep);
		ret = 0;
		break;
	case FUNCTIONFS_CLEAR_HALT:
		ret = usb_ep_clear_halt(epfile->ep->ep);
		break;
	case FUNCTIONFS_ENDPOINT_REVMAP:
		ret = epfile->ep->num;
		break;
	case FUNCTIONFS_ENDPOINT_DESC:
	{
		int desc_idx;
1329
		struct usb_endpoint_descriptor desc1, *desc;
1330 1331 1332

		switch (epfile->ffs->gadget->speed) {
		case USB_SPEED_SUPER:
1333
		case USB_SPEED_SUPER_PLUS:
1334
			desc_idx = 2;
1335
			break;
1336 1337
		case USB_SPEED_HIGH:
			desc_idx = 1;
1338 1339
			break;
		default:
1340
			desc_idx = 0;
1341
		}
1342

1343
		desc = epfile->ep->descs[desc_idx];
1344
		memcpy(&desc1, desc, desc->bLength);
1345 1346

		spin_unlock_irq(&epfile->ffs->eps_lock);
1347
		ret = copy_to_user((void __user *)value, &desc1, desc1.bLength);
1348 1349 1350 1351 1352 1353
		if (ret)
			ret = -EFAULT;
		return ret;
	}
	default:
		ret = -ENOTTY;
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
	}
	spin_unlock_irq(&epfile->ffs->eps_lock);

	return ret;
}

static const struct file_operations ffs_epfile_operations = {
	.llseek =	no_llseek,

	.open =		ffs_epfile_open,
1364 1365
	.write_iter =	ffs_epfile_write_iter,
	.read_iter =	ffs_epfile_read_iter,
1366 1367
	.release =	ffs_epfile_release,
	.unlocked_ioctl =	ffs_epfile_ioctl,
1368
	.compat_ioctl = compat_ptr_ioctl,
1369 1370 1371 1372 1373 1374
};


/* File system and super block operations ***********************************/

/*
1375
 * Mounting the file system creates a controller file, used first for
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
 * function configuration then later for event monitoring.
 */

static struct inode *__must_check
ffs_sb_make_inode(struct super_block *sb, void *data,
		  const struct file_operations *fops,
		  const struct inode_operations *iops,
		  struct ffs_file_perms *perms)
{
	struct inode *inode;

	ENTER();

	inode = new_inode(sb);

	if (likely(inode)) {
1392
		struct timespec64 ts = current_time(inode);
1393

1394
		inode->i_ino	 = get_next_ino();
1395 1396 1397
		inode->i_mode    = perms->mode;
		inode->i_uid     = perms->uid;
		inode->i_gid     = perms->gid;
1398 1399 1400
		inode->i_atime   = ts;
		inode->i_mtime   = ts;
		inode->i_ctime   = ts;
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
		inode->i_private = data;
		if (fops)
			inode->i_fop = fops;
		if (iops)
			inode->i_op  = iops;
	}

	return inode;
}

/* Create "regular" file */
A
Al Viro 已提交
1412
static struct dentry *ffs_sb_create_file(struct super_block *sb,
1413
					const char *name, void *data,
A
Al Viro 已提交
1414
					const struct file_operations *fops)
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
{
	struct ffs_data	*ffs = sb->s_fs_info;
	struct dentry	*dentry;
	struct inode	*inode;

	ENTER();

	dentry = d_alloc_name(sb->s_root, name);
	if (unlikely(!dentry))
		return NULL;

	inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
	if (unlikely(!inode)) {
		dput(dentry);
		return NULL;
	}

	d_add(dentry, inode);
A
Al Viro 已提交
1433
	return dentry;
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
}

/* Super block */
static const struct super_operations ffs_sb_operations = {
	.statfs =	simple_statfs,
	.drop_inode =	generic_delete_inode,
};

struct ffs_sb_fill_data {
	struct ffs_file_perms perms;
	umode_t root_mode;
	const char *dev_name;
1446
	bool no_disconnect;
A
Al Viro 已提交
1447
	struct ffs_data *ffs_data;
1448 1449
};

1450
static int ffs_sb_fill(struct super_block *sb, struct fs_context *fc)
1451
{
1452
	struct ffs_sb_fill_data *data = fc->fs_private;
1453
	struct inode	*inode;
A
Al Viro 已提交
1454
	struct ffs_data	*ffs = data->ffs_data;
1455 1456 1457 1458

	ENTER();

	ffs->sb              = sb;
A
Al Viro 已提交
1459
	data->ffs_data       = NULL;
1460
	sb->s_fs_info        = ffs;
1461 1462
	sb->s_blocksize      = PAGE_SIZE;
	sb->s_blocksize_bits = PAGE_SHIFT;
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
	sb->s_magic          = FUNCTIONFS_MAGIC;
	sb->s_op             = &ffs_sb_operations;
	sb->s_time_gran      = 1;

	/* Root inode */
	data->perms.mode = data->root_mode;
	inode = ffs_sb_make_inode(sb, NULL,
				  &simple_dir_operations,
				  &simple_dir_inode_operations,
				  &data->perms);
1473 1474
	sb->s_root = d_make_root(inode);
	if (unlikely(!sb->s_root))
A
Al Viro 已提交
1475
		return -ENOMEM;
1476 1477 1478

	/* EP0 file */
	if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
A
Al Viro 已提交
1479
					 &ffs_ep0_operations)))
A
Al Viro 已提交
1480
		return -ENOMEM;
1481 1482 1483 1484

	return 0;
}

1485 1486 1487 1488 1489 1490 1491 1492
enum {
	Opt_no_disconnect,
	Opt_rmode,
	Opt_fmode,
	Opt_mode,
	Opt_uid,
	Opt_gid,
};
1493

1494
static const struct fs_parameter_spec ffs_fs_fs_parameters[] = {
1495 1496 1497 1498 1499 1500 1501 1502
	fsparam_bool	("no_disconnect",	Opt_no_disconnect),
	fsparam_u32	("rmode",		Opt_rmode),
	fsparam_u32	("fmode",		Opt_fmode),
	fsparam_u32	("mode",		Opt_mode),
	fsparam_u32	("uid",			Opt_uid),
	fsparam_u32	("gid",			Opt_gid),
	{}
};
1503

1504 1505 1506 1507 1508
static int ffs_fs_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
	struct ffs_sb_fill_data *data = fc->fs_private;
	struct fs_parse_result result;
	int opt;
1509

1510
	ENTER();
1511

1512
	opt = fs_parse(fc, ffs_fs_fs_parameters, param, &result);
1513 1514
	if (opt < 0)
		return opt;
1515

1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
	switch (opt) {
	case Opt_no_disconnect:
		data->no_disconnect = result.boolean;
		break;
	case Opt_rmode:
		data->root_mode  = (result.uint_32 & 0555) | S_IFDIR;
		break;
	case Opt_fmode:
		data->perms.mode = (result.uint_32 & 0666) | S_IFREG;
		break;
	case Opt_mode:
		data->root_mode  = (result.uint_32 & 0555) | S_IFDIR;
		data->perms.mode = (result.uint_32 & 0666) | S_IFREG;
		break;
1530

1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
	case Opt_uid:
		data->perms.uid = make_kuid(current_user_ns(), result.uint_32);
		if (!uid_valid(data->perms.uid))
			goto unmapped_value;
		break;
	case Opt_gid:
		data->perms.gid = make_kgid(current_user_ns(), result.uint_32);
		if (!gid_valid(data->perms.gid))
			goto unmapped_value;
		break;
1541

1542 1543
	default:
		return -ENOPARAM;
1544 1545 1546 1547
	}

	return 0;

1548 1549 1550
unmapped_value:
	return invalf(fc, "%s: unmapped value: %u", param->key, result.uint_32);
}
1551

1552 1553 1554 1555
/*
 * Set up the superblock for a mount.
 */
static int ffs_fs_get_tree(struct fs_context *fc)
1556
{
1557
	struct ffs_sb_fill_data *ctx = fc->fs_private;
1558
	void *ffs_dev;
A
Al Viro 已提交
1559
	struct ffs_data	*ffs;
1560 1561 1562

	ENTER();

1563 1564
	if (!fc->source)
		return invalf(fc, "No source specified");
1565

1566
	ffs = ffs_data_new(fc->source);
A
Al Viro 已提交
1567
	if (unlikely(!ffs))
1568 1569 1570
		return -ENOMEM;
	ffs->file_perms = ctx->perms;
	ffs->no_disconnect = ctx->no_disconnect;
A
Al Viro 已提交
1571

1572
	ffs->dev_name = kstrdup(fc->source, GFP_KERNEL);
A
Al Viro 已提交
1573 1574
	if (unlikely(!ffs->dev_name)) {
		ffs_data_put(ffs);
1575
		return -ENOMEM;
A
Al Viro 已提交
1576 1577
	}

1578
	ffs_dev = ffs_acquire_dev(ffs->dev_name);
A
Al Viro 已提交
1579 1580
	if (IS_ERR(ffs_dev)) {
		ffs_data_put(ffs);
1581
		return PTR_ERR(ffs_dev);
A
Al Viro 已提交
1582
	}
1583

A
Al Viro 已提交
1584
	ffs->private_data = ffs_dev;
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
	ctx->ffs_data = ffs;
	return get_tree_nodev(fc, ffs_sb_fill);
}

static void ffs_fs_free_fc(struct fs_context *fc)
{
	struct ffs_sb_fill_data *ctx = fc->fs_private;

	if (ctx) {
		if (ctx->ffs_data) {
			ffs_release_dev(ctx->ffs_data);
			ffs_data_put(ctx->ffs_data);
		}
1598

1599
		kfree(ctx);
A
Al Viro 已提交
1600
	}
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
}

static const struct fs_context_operations ffs_fs_context_ops = {
	.free		= ffs_fs_free_fc,
	.parse_param	= ffs_fs_parse_param,
	.get_tree	= ffs_fs_get_tree,
};

static int ffs_fs_init_fs_context(struct fs_context *fc)
{
	struct ffs_sb_fill_data *ctx;

	ctx = kzalloc(sizeof(struct ffs_sb_fill_data), GFP_KERNEL);
	if (!ctx)
		return -ENOMEM;

	ctx->perms.mode = S_IFREG | 0600;
	ctx->perms.uid = GLOBAL_ROOT_UID;
	ctx->perms.gid = GLOBAL_ROOT_GID;
	ctx->root_mode = S_IFDIR | 0500;
	ctx->no_disconnect = false;

	fc->fs_private = ctx;
	fc->ops = &ffs_fs_context_ops;
	return 0;
1626 1627 1628 1629 1630 1631 1632 1633
}

static void
ffs_fs_kill_sb(struct super_block *sb)
{
	ENTER();

	kill_litter_super(sb);
1634
	if (sb->s_fs_info) {
1635
		ffs_release_dev(sb->s_fs_info);
1636
		ffs_data_closed(sb->s_fs_info);
1637
	}
1638 1639 1640 1641 1642
}

static struct file_system_type ffs_fs_type = {
	.owner		= THIS_MODULE,
	.name		= "functionfs",
1643
	.init_fs_context = ffs_fs_init_fs_context,
1644
	.parameters	= ffs_fs_fs_parameters,
1645 1646
	.kill_sb	= ffs_fs_kill_sb,
};
1647
MODULE_ALIAS_FS("functionfs");
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659


/* Driver's main init/cleanup functions *************************************/

static int functionfs_init(void)
{
	int ret;

	ENTER();

	ret = register_filesystem(&ffs_fs_type);
	if (likely(!ret))
1660
		pr_info("file system registered\n");
1661
	else
1662
		pr_err("failed registering file system (%d)\n", ret);
1663 1664 1665 1666 1667 1668 1669 1670

	return ret;
}

static void functionfs_cleanup(void)
{
	ENTER();

1671
	pr_info("unloading\n");
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
	unregister_filesystem(&ffs_fs_type);
}


/* ffs_data and ffs_function construction and destruction code **************/

static void ffs_data_clear(struct ffs_data *ffs);
static void ffs_data_reset(struct ffs_data *ffs);

static void ffs_data_get(struct ffs_data *ffs)
{
	ENTER();

1685
	refcount_inc(&ffs->ref);
1686 1687 1688 1689 1690 1691
}

static void ffs_data_opened(struct ffs_data *ffs)
{
	ENTER();

1692
	refcount_inc(&ffs->ref);
1693 1694 1695 1696 1697
	if (atomic_add_return(1, &ffs->opened) == 1 &&
			ffs->state == FFS_DEACTIVATED) {
		ffs->state = FFS_CLOSING;
		ffs_data_reset(ffs);
	}
1698 1699 1700 1701 1702 1703
}

static void ffs_data_put(struct ffs_data *ffs)
{
	ENTER();

1704
	if (unlikely(refcount_dec_and_test(&ffs->ref))) {
1705
		pr_info("%s(): freeing\n", __func__);
1706
		ffs_data_clear(ffs);
1707
		BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1708
		       swait_active(&ffs->ep0req_completion.wait) ||
1709
		       waitqueue_active(&ffs->wait));
1710
		destroy_workqueue(ffs->io_completion_wq);
1711
		kfree(ffs->dev_name);
1712 1713 1714 1715 1716 1717 1718 1719 1720
		kfree(ffs);
	}
}

static void ffs_data_closed(struct ffs_data *ffs)
{
	ENTER();

	if (atomic_dec_and_test(&ffs->opened)) {
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
		if (ffs->no_disconnect) {
			ffs->state = FFS_DEACTIVATED;
			if (ffs->epfiles) {
				ffs_epfiles_destroy(ffs->epfiles,
						   ffs->eps_count);
				ffs->epfiles = NULL;
			}
			if (ffs->setup_state == FFS_SETUP_PENDING)
				__ffs_ep0_stall(ffs);
		} else {
			ffs->state = FFS_CLOSING;
			ffs_data_reset(ffs);
		}
	}
	if (atomic_read(&ffs->opened) < 0) {
1736 1737 1738 1739 1740 1741 1742
		ffs->state = FFS_CLOSING;
		ffs_data_reset(ffs);
	}

	ffs_data_put(ffs);
}

1743
static struct ffs_data *ffs_data_new(const char *dev_name)
1744 1745 1746
{
	struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
	if (unlikely(!ffs))
1747
		return NULL;
1748 1749 1750

	ENTER();

1751 1752 1753 1754 1755 1756
	ffs->io_completion_wq = alloc_ordered_workqueue("%s", 0, dev_name);
	if (!ffs->io_completion_wq) {
		kfree(ffs);
		return NULL;
	}

1757
	refcount_set(&ffs->ref, 1);
1758 1759 1760 1761 1762
	atomic_set(&ffs->opened, 0);
	ffs->state = FFS_READ_DESCRIPTORS;
	mutex_init(&ffs->mutex);
	spin_lock_init(&ffs->eps_lock);
	init_waitqueue_head(&ffs->ev.waitq);
1763
	init_waitqueue_head(&ffs->wait);
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
	init_completion(&ffs->ep0req_completion);

	/* XXX REVISIT need to update it in some places, or do we? */
	ffs->ev.can_stall = 1;

	return ffs;
}

static void ffs_data_clear(struct ffs_data *ffs)
{
	ENTER();

1776
	ffs_closed(ffs);
1777 1778 1779 1780 1781 1782

	BUG_ON(ffs->gadget);

	if (ffs->epfiles)
		ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);

1783 1784 1785
	if (ffs->ffs_eventfd)
		eventfd_ctx_put(ffs->ffs_eventfd);

1786
	kfree(ffs->raw_descs_data);
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
	kfree(ffs->raw_strings);
	kfree(ffs->stringtabs);
}

static void ffs_data_reset(struct ffs_data *ffs)
{
	ENTER();

	ffs_data_clear(ffs);

	ffs->epfiles = NULL;
1798
	ffs->raw_descs_data = NULL;
1799 1800 1801 1802 1803 1804 1805
	ffs->raw_descs = NULL;
	ffs->raw_strings = NULL;
	ffs->stringtabs = NULL;

	ffs->raw_descs_length = 0;
	ffs->fs_descs_count = 0;
	ffs->hs_descs_count = 0;
1806
	ffs->ss_descs_count = 0;
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816

	ffs->strings_count = 0;
	ffs->interfaces_count = 0;
	ffs->eps_count = 0;

	ffs->ev.count = 0;

	ffs->state = FFS_READ_DESCRIPTORS;
	ffs->setup_state = FFS_NO_SETUP;
	ffs->flags = 0;
1817 1818 1819 1820

	ffs->ms_os_descs_ext_prop_count = 0;
	ffs->ms_os_descs_ext_prop_name_len = 0;
	ffs->ms_os_descs_ext_prop_data_len = 0;
1821 1822 1823 1824 1825
}


static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
{
1826 1827
	struct usb_gadget_strings **lang;
	int first_id;
1828 1829 1830 1831 1832 1833 1834

	ENTER();

	if (WARN_ON(ffs->state != FFS_ACTIVE
		 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
		return -EBADFD;

1835 1836 1837
	first_id = usb_string_ids_n(cdev, ffs->strings_count);
	if (unlikely(first_id < 0))
		return first_id;
1838 1839 1840 1841 1842 1843 1844

	ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
	if (unlikely(!ffs->ep0req))
		return -ENOMEM;
	ffs->ep0req->complete = ffs_ep0_complete;
	ffs->ep0req->context = ffs;

1845
	lang = ffs->stringtabs;
1846 1847 1848 1849 1850 1851 1852
	if (lang) {
		for (; *lang; ++lang) {
			struct usb_string *str = (*lang)->strings;
			int id = first_id;
			for (; str->s; ++id, ++str)
				str->id = id;
		}
1853 1854 1855
	}

	ffs->gadget = cdev->gadget;
1856
	ffs_data_get(ffs);
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
	return 0;
}

static void functionfs_unbind(struct ffs_data *ffs)
{
	ENTER();

	if (!WARN_ON(!ffs->gadget)) {
		usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
		ffs->ep0req = NULL;
		ffs->gadget = NULL;
1868
		clear_bit(FFS_FL_BOUND, &ffs->flags);
1869
		ffs_data_put(ffs);
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
	}
}

static int ffs_epfiles_create(struct ffs_data *ffs)
{
	struct ffs_epfile *epfile, *epfiles;
	unsigned i, count;

	ENTER();

	count = ffs->eps_count;
1881
	epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1882 1883 1884 1885 1886 1887 1888
	if (!epfiles)
		return -ENOMEM;

	epfile = epfiles;
	for (i = 1; i <= count; ++i, ++epfile) {
		epfile->ffs = ffs;
		mutex_init(&epfile->mutex);
1889
		if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1890
			sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1891
		else
1892 1893
			sprintf(epfile->name, "ep%u", i);
		epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
A
Al Viro 已提交
1894 1895 1896
						 epfile,
						 &ffs_epfile_operations);
		if (unlikely(!epfile->dentry)) {
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
			ffs_epfiles_destroy(epfiles, i - 1);
			return -ENOMEM;
		}
	}

	ffs->epfiles = epfiles;
	return 0;
}

static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
{
	struct ffs_epfile *epfile = epfiles;

	ENTER();

	for (; count; --count, ++epfile) {
1913
		BUG_ON(mutex_is_locked(&epfile->mutex));
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
		if (epfile->dentry) {
			d_delete(epfile->dentry);
			dput(epfile->dentry);
			epfile->dentry = NULL;
		}
	}

	kfree(epfiles);
}

static void ffs_func_eps_disable(struct ffs_function *func)
{
	struct ffs_ep *ep         = func->eps;
	struct ffs_epfile *epfile = func->ffs->epfiles;
	unsigned count            = func->ffs->eps_count;
	unsigned long flags;

1931
	spin_lock_irqsave(&func->ffs->eps_lock, flags);
1932
	while (count--) {
1933 1934 1935 1936
		/* pending requests get nuked */
		if (likely(ep->ep))
			usb_ep_disable(ep->ep);
		++ep;
1937 1938

		if (epfile) {
1939 1940
			epfile->ep = NULL;
			__ffs_epfile_read_buffer_free(epfile);
1941 1942
			++epfile;
		}
1943
	}
1944
	spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
}

static int ffs_func_eps_enable(struct ffs_function *func)
{
	struct ffs_data *ffs      = func->ffs;
	struct ffs_ep *ep         = func->eps;
	struct ffs_epfile *epfile = ffs->epfiles;
	unsigned count            = ffs->eps_count;
	unsigned long flags;
	int ret = 0;

	spin_lock_irqsave(&func->ffs->eps_lock, flags);
1957
	while(count--) {
1958
		ep->ep->driver_data = ep;
1959

1960 1961 1962 1963 1964
		ret = config_ep_by_speed(func->gadget, &func->function, ep->ep);
		if (ret) {
			pr_err("%s: config_ep_by_speed(%s) returned %d\n",
					__func__, ep->ep->name, ret);
			break;
1965
		}
1966

1967
		ret = usb_ep_enable(ep->ep);
1968 1969
		if (likely(!ret)) {
			epfile->ep = ep;
1970 1971
			epfile->in = usb_endpoint_dir_in(ep->ep->desc);
			epfile->isoc = usb_endpoint_xfer_isoc(ep->ep->desc);
1972 1973 1974 1975 1976 1977
		} else {
			break;
		}

		++ep;
		++epfile;
1978
	}
1979 1980

	wake_up_interruptible(&ffs->wait);
1981 1982 1983 1984 1985 1986 1987 1988
	spin_unlock_irqrestore(&func->ffs->eps_lock, flags);

	return ret;
}


/* Parsing and building descriptors and strings *****************************/

1989 1990
/*
 * This validates if data pointed by data is a valid USB descriptor as
1991
 * well as record how many interfaces, endpoints and strings are
1992 1993 1994
 * required by given configuration.  Returns address after the
 * descriptor or NULL if data is invalid.
 */
1995 1996 1997 1998 1999

enum ffs_entity_type {
	FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
};

2000 2001 2002 2003
enum ffs_os_desc_type {
	FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
};

2004 2005 2006 2007 2008
typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
				   u8 *valuep,
				   struct usb_descriptor_header *desc,
				   void *priv);

2009 2010 2011 2012
typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
				    struct usb_os_desc_header *h, void *data,
				    unsigned len, void *priv);

2013 2014
static int __must_check ffs_do_single_desc(char *data, unsigned len,
					   ffs_entity_callback entity,
2015
					   void *priv, int *current_class)
2016 2017 2018 2019 2020 2021 2022 2023 2024
{
	struct usb_descriptor_header *_ds = (void *)data;
	u8 length;
	int ret;

	ENTER();

	/* At least two bytes are required: length and type */
	if (len < 2) {
2025
		pr_vdebug("descriptor too short\n");
2026 2027 2028 2029 2030 2031
		return -EINVAL;
	}

	/* If we have at least as many bytes as the descriptor takes? */
	length = _ds->bLength;
	if (len < length) {
2032
		pr_vdebug("descriptor longer then available data\n");
2033 2034 2035 2036 2037 2038 2039
		return -EINVAL;
	}

#define __entity_check_INTERFACE(val)  1
#define __entity_check_STRING(val)     (val)
#define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
#define __entity(type, val) do {					\
2040
		pr_vdebug("entity " #type "(%02x)\n", (val));		\
2041
		if (unlikely(!__entity_check_ ##type(val))) {		\
2042
			pr_vdebug("invalid entity's value\n");		\
2043 2044 2045 2046
			return -EINVAL;					\
		}							\
		ret = entity(FFS_ ##type, &val, _ds, priv);		\
		if (unlikely(ret < 0)) {				\
2047
			pr_debug("entity " #type "(%02x); ret = %d\n",	\
2048
				 (val), ret);				\
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
			return ret;					\
		}							\
	} while (0)

	/* Parse descriptor depending on type. */
	switch (_ds->bDescriptorType) {
	case USB_DT_DEVICE:
	case USB_DT_CONFIG:
	case USB_DT_STRING:
	case USB_DT_DEVICE_QUALIFIER:
		/* function can't have any of those */
2060
		pr_vdebug("descriptor reserved for gadget: %d\n",
2061
		      _ds->bDescriptorType);
2062 2063 2064 2065
		return -EINVAL;

	case USB_DT_INTERFACE: {
		struct usb_interface_descriptor *ds = (void *)_ds;
2066
		pr_vdebug("interface descriptor\n");
2067 2068 2069 2070 2071 2072
		if (length != sizeof *ds)
			goto inv_length;

		__entity(INTERFACE, ds->bInterfaceNumber);
		if (ds->iInterface)
			__entity(STRING, ds->iInterface);
2073
		*current_class = ds->bInterfaceClass;
2074 2075 2076 2077 2078
	}
		break;

	case USB_DT_ENDPOINT: {
		struct usb_endpoint_descriptor *ds = (void *)_ds;
2079
		pr_vdebug("endpoint descriptor\n");
2080 2081 2082 2083 2084 2085 2086
		if (length != USB_DT_ENDPOINT_SIZE &&
		    length != USB_DT_ENDPOINT_AUDIO_SIZE)
			goto inv_length;
		__entity(ENDPOINT, ds->bEndpointAddress);
	}
		break;

2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
	case USB_TYPE_CLASS | 0x01:
                if (*current_class == USB_INTERFACE_CLASS_HID) {
			pr_vdebug("hid descriptor\n");
			if (length != sizeof(struct hid_descriptor))
				goto inv_length;
			break;
		} else if (*current_class == USB_INTERFACE_CLASS_CCID) {
			pr_vdebug("ccid descriptor\n");
			if (length != sizeof(struct ccid_descriptor))
				goto inv_length;
			break;
		} else {
			pr_vdebug("unknown descriptor: %d for class %d\n",
			      _ds->bDescriptorType, *current_class);
			return -EINVAL;
		}
2103

2104 2105 2106 2107 2108 2109 2110
	case USB_DT_OTG:
		if (length != sizeof(struct usb_otg_descriptor))
			goto inv_length;
		break;

	case USB_DT_INTERFACE_ASSOCIATION: {
		struct usb_interface_assoc_descriptor *ds = (void *)_ds;
2111
		pr_vdebug("interface association descriptor\n");
2112 2113 2114 2115 2116 2117 2118
		if (length != sizeof *ds)
			goto inv_length;
		if (ds->iFunction)
			__entity(STRING, ds->iFunction);
	}
		break;

2119 2120 2121 2122 2123 2124
	case USB_DT_SS_ENDPOINT_COMP:
		pr_vdebug("EP SS companion descriptor\n");
		if (length != sizeof(struct usb_ss_ep_comp_descriptor))
			goto inv_length;
		break;

2125 2126 2127 2128 2129 2130
	case USB_DT_OTHER_SPEED_CONFIG:
	case USB_DT_INTERFACE_POWER:
	case USB_DT_DEBUG:
	case USB_DT_SECURITY:
	case USB_DT_CS_RADIO_CONTROL:
		/* TODO */
2131
		pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
2132 2133 2134 2135
		return -EINVAL;

	default:
		/* We should never be here */
2136
		pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
2137 2138
		return -EINVAL;

2139
inv_length:
2140
		pr_vdebug("invalid length: %d (descriptor %d)\n",
2141
			  _ds->bLength, _ds->bDescriptorType);
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
		return -EINVAL;
	}

#undef __entity
#undef __entity_check_DESCRIPTOR
#undef __entity_check_INTERFACE
#undef __entity_check_STRING
#undef __entity_check_ENDPOINT

	return length;
}

static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
				     ffs_entity_callback entity, void *priv)
{
	const unsigned _len = len;
	unsigned long num = 0;
2159
	int current_class = -1;
2160 2161 2162 2163 2164 2165 2166 2167 2168

	ENTER();

	for (;;) {
		int ret;

		if (num == count)
			data = NULL;

2169
		/* Record "descriptor" entity */
2170 2171
		ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
		if (unlikely(ret < 0)) {
2172
			pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
2173
				 num, ret);
2174 2175 2176 2177 2178 2179
			return ret;
		}

		if (!data)
			return _len - len;

2180 2181
		ret = ffs_do_single_desc(data, len, entity, priv,
			&current_class);
2182
		if (unlikely(ret < 0)) {
2183
			pr_debug("%s returns %d\n", __func__, ret);
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
			return ret;
		}

		len -= ret;
		data += ret;
		++num;
	}
}

static int __ffs_data_do_entity(enum ffs_entity_type type,
				u8 *valuep, struct usb_descriptor_header *desc,
				void *priv)
{
2197 2198
	struct ffs_desc_helper *helper = priv;
	struct usb_endpoint_descriptor *d;
2199 2200 2201 2202 2203 2204 2205 2206

	ENTER();

	switch (type) {
	case FFS_DESCRIPTOR:
		break;

	case FFS_INTERFACE:
2207 2208
		/*
		 * Interfaces are indexed from zero so if we
2209
		 * encountered interface "n" then there are at least
2210 2211
		 * "n+1" interfaces.
		 */
2212 2213
		if (*valuep >= helper->interfaces_count)
			helper->interfaces_count = *valuep + 1;
2214 2215 2216
		break;

	case FFS_STRING:
2217
		/*
2218 2219
		 * Strings are indexed from 1 (0 is reserved
		 * for languages list)
2220
		 */
2221 2222
		if (*valuep > helper->ffs->strings_count)
			helper->ffs->strings_count = *valuep;
2223 2224 2225
		break;

	case FFS_ENDPOINT:
2226 2227
		d = (void *)desc;
		helper->eps_count++;
2228
		if (helper->eps_count >= FFS_MAX_EPS_COUNT)
2229 2230 2231 2232 2233 2234 2235 2236
			return -EINVAL;
		/* Check if descriptors for any speed were already parsed */
		if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
			helper->ffs->eps_addrmap[helper->eps_count] =
				d->bEndpointAddress;
		else if (helper->ffs->eps_addrmap[helper->eps_count] !=
				d->bEndpointAddress)
			return -EINVAL;
2237 2238 2239 2240 2241 2242
		break;
	}

	return 0;
}

2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
				   struct usb_os_desc_header *desc)
{
	u16 bcd_version = le16_to_cpu(desc->bcdVersion);
	u16 w_index = le16_to_cpu(desc->wIndex);

	if (bcd_version != 1) {
		pr_vdebug("unsupported os descriptors version: %d",
			  bcd_version);
		return -EINVAL;
	}
	switch (w_index) {
	case 0x4:
		*next_type = FFS_OS_DESC_EXT_COMPAT;
		break;
	case 0x5:
		*next_type = FFS_OS_DESC_EXT_PROP;
		break;
	default:
		pr_vdebug("unsupported os descriptor type: %d", w_index);
		return -EINVAL;
	}

	return sizeof(*desc);
}

/*
 * Process all extended compatibility/extended property descriptors
 * of a feature descriptor
 */
static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
					      enum ffs_os_desc_type type,
					      u16 feature_count,
					      ffs_os_desc_callback entity,
					      void *priv,
					      struct usb_os_desc_header *h)
{
	int ret;
	const unsigned _len = len;

	ENTER();

	/* loop over all ext compat/ext prop descriptors */
	while (feature_count--) {
		ret = entity(type, h, data, len, priv);
		if (unlikely(ret < 0)) {
			pr_debug("bad OS descriptor, type: %d\n", type);
			return ret;
		}
		data += ret;
		len -= ret;
	}
	return _len - len;
}

/* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
static int __must_check ffs_do_os_descs(unsigned count,
					char *data, unsigned len,
					ffs_os_desc_callback entity, void *priv)
{
	const unsigned _len = len;
	unsigned long num = 0;

	ENTER();

	for (num = 0; num < count; ++num) {
		int ret;
		enum ffs_os_desc_type type;
		u16 feature_count;
		struct usb_os_desc_header *desc = (void *)data;

		if (len < sizeof(*desc))
			return -EINVAL;

		/*
		 * Record "descriptor" entity.
		 * Process dwLength, bcdVersion, wIndex, get b/wCount.
		 * Move the data pointer to the beginning of extended
		 * compatibilities proper or extended properties proper
		 * portions of the data
		 */
		if (le32_to_cpu(desc->dwLength) > len)
			return -EINVAL;

		ret = __ffs_do_os_desc_header(&type, desc);
		if (unlikely(ret < 0)) {
			pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
				 num, ret);
			return ret;
		}
		/*
		 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
		 */
		feature_count = le16_to_cpu(desc->wCount);
		if (type == FFS_OS_DESC_EXT_COMPAT &&
		    (feature_count > 255 || desc->Reserved))
				return -EINVAL;
		len -= ret;
		data += ret;

		/*
		 * Process all function/property descriptors
		 * of this Feature Descriptor
		 */
		ret = ffs_do_single_os_desc(data, len, type,
					    feature_count, entity, priv, desc);
		if (unlikely(ret < 0)) {
			pr_debug("%s returns %d\n", __func__, ret);
			return ret;
		}

		len -= ret;
		data += ret;
	}
	return _len - len;
}

2360
/*
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
 * Validate contents of the buffer from userspace related to OS descriptors.
 */
static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
				 struct usb_os_desc_header *h, void *data,
				 unsigned len, void *priv)
{
	struct ffs_data *ffs = priv;
	u8 length;

	ENTER();

	switch (type) {
	case FFS_OS_DESC_EXT_COMPAT: {
		struct usb_ext_compat_desc *d = data;
		int i;

		if (len < sizeof(*d) ||
2378
		    d->bFirstInterfaceNumber >= ffs->interfaces_count)
2379
			return -EINVAL;
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
		if (d->Reserved1 != 1) {
			/*
			 * According to the spec, Reserved1 must be set to 1
			 * but older kernels incorrectly rejected non-zero
			 * values.  We fix it here to avoid returning EINVAL
			 * in response to values we used to accept.
			 */
			pr_debug("usb_ext_compat_desc::Reserved1 forced to 1\n");
			d->Reserved1 = 1;
		}
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
		for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
			if (d->Reserved2[i])
				return -EINVAL;

		length = sizeof(struct usb_ext_compat_desc);
	}
		break;
	case FFS_OS_DESC_EXT_PROP: {
		struct usb_ext_prop_desc *d = data;
		u32 type, pdl;
		u16 pnl;

		if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
			return -EINVAL;
		length = le32_to_cpu(d->dwSize);
2405 2406
		if (len < length)
			return -EINVAL;
2407 2408 2409 2410 2411 2412 2413 2414
		type = le32_to_cpu(d->dwPropertyDataType);
		if (type < USB_EXT_PROP_UNICODE ||
		    type > USB_EXT_PROP_UNICODE_MULTI) {
			pr_vdebug("unsupported os descriptor property type: %d",
				  type);
			return -EINVAL;
		}
		pnl = le16_to_cpu(d->wPropertyNameLength);
2415 2416 2417 2418 2419
		if (length < 14 + pnl) {
			pr_vdebug("invalid os descriptor length: %d pnl:%d (descriptor %d)\n",
				  length, pnl, type);
			return -EINVAL;
		}
2420
		pdl = le32_to_cpu(*(__le32 *)((u8 *)data + 10 + pnl));
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
		if (length != 14 + pnl + pdl) {
			pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
				  length, pnl, pdl, type);
			return -EINVAL;
		}
		++ffs->ms_os_descs_ext_prop_count;
		/* property name reported to the host as "WCHAR"s */
		ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
		ffs->ms_os_descs_ext_prop_data_len += pdl;
	}
		break;
	default:
		pr_vdebug("unknown descriptor: %d\n", type);
		return -EINVAL;
	}
	return length;
}

2439 2440 2441
static int __ffs_data_got_descs(struct ffs_data *ffs,
				char *const _data, size_t len)
{
2442
	char *data = _data, *raw_descs;
2443
	unsigned os_descs_count = 0, counts[3], flags;
2444
	int ret = -EINVAL, i;
2445
	struct ffs_desc_helper helper;
2446 2447 2448

	ENTER();

2449
	if (get_unaligned_le32(data + 4) != len)
2450 2451
		goto error;

2452 2453 2454 2455 2456 2457 2458 2459
	switch (get_unaligned_le32(data)) {
	case FUNCTIONFS_DESCRIPTORS_MAGIC:
		flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
		data += 8;
		len  -= 8;
		break;
	case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
		flags = get_unaligned_le32(data + 8);
2460
		ffs->user_flags = flags;
2461 2462
		if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
			      FUNCTIONFS_HAS_HS_DESC |
2463
			      FUNCTIONFS_HAS_SS_DESC |
2464
			      FUNCTIONFS_HAS_MS_OS_DESC |
2465
			      FUNCTIONFS_VIRTUAL_ADDR |
2466
			      FUNCTIONFS_EVENTFD |
2467 2468
			      FUNCTIONFS_ALL_CTRL_RECIP |
			      FUNCTIONFS_CONFIG0_SETUP)) {
2469
			ret = -ENOSYS;
2470 2471
			goto error;
		}
2472 2473 2474 2475 2476
		data += 12;
		len  -= 12;
		break;
	default:
		goto error;
2477 2478
	}

2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
	if (flags & FUNCTIONFS_EVENTFD) {
		if (len < 4)
			goto error;
		ffs->ffs_eventfd =
			eventfd_ctx_fdget((int)get_unaligned_le32(data));
		if (IS_ERR(ffs->ffs_eventfd)) {
			ret = PTR_ERR(ffs->ffs_eventfd);
			ffs->ffs_eventfd = NULL;
			goto error;
		}
		data += 4;
		len  -= 4;
	}

2493 2494 2495 2496 2497
	/* Read fs_count, hs_count and ss_count (if present) */
	for (i = 0; i < 3; ++i) {
		if (!(flags & (1 << i))) {
			counts[i] = 0;
		} else if (len < 4) {
2498
			goto error;
2499 2500 2501 2502
		} else {
			counts[i] = get_unaligned_le32(data);
			data += 4;
			len  -= 4;
2503
		}
2504
	}
2505
	if (flags & (1 << i)) {
2506 2507 2508
		if (len < 4) {
			goto error;
		}
2509 2510 2511
		os_descs_count = get_unaligned_le32(data);
		data += 4;
		len -= 4;
2512
	}
2513

2514 2515
	/* Read descriptors */
	raw_descs = data;
2516
	helper.ffs = ffs;
2517 2518 2519
	for (i = 0; i < 3; ++i) {
		if (!counts[i])
			continue;
2520 2521
		helper.interfaces_count = 0;
		helper.eps_count = 0;
2522
		ret = ffs_do_descs(counts[i], data, len,
2523
				   __ffs_data_do_entity, &helper);
2524
		if (ret < 0)
2525
			goto error;
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
		if (!ffs->eps_count && !ffs->interfaces_count) {
			ffs->eps_count = helper.eps_count;
			ffs->interfaces_count = helper.interfaces_count;
		} else {
			if (ffs->eps_count != helper.eps_count) {
				ret = -EINVAL;
				goto error;
			}
			if (ffs->interfaces_count != helper.interfaces_count) {
				ret = -EINVAL;
				goto error;
			}
		}
2539 2540
		data += ret;
		len  -= ret;
2541
	}
2542 2543 2544 2545 2546 2547 2548 2549
	if (os_descs_count) {
		ret = ffs_do_os_descs(os_descs_count, data, len,
				      __ffs_data_do_os_desc, ffs);
		if (ret < 0)
			goto error;
		data += ret;
		len -= ret;
	}
2550

2551 2552 2553 2554
	if (raw_descs == data || len) {
		ret = -EINVAL;
		goto error;
	}
2555

2556 2557 2558 2559 2560 2561
	ffs->raw_descs_data	= _data;
	ffs->raw_descs		= raw_descs;
	ffs->raw_descs_length	= data - raw_descs;
	ffs->fs_descs_count	= counts[0];
	ffs->hs_descs_count	= counts[1];
	ffs->ss_descs_count	= counts[2];
2562
	ffs->ms_os_descs_count	= os_descs_count;
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576

	return 0;

error:
	kfree(_data);
	return ret;
}

static int __ffs_data_got_strings(struct ffs_data *ffs,
				  char *const _data, size_t len)
{
	u32 str_count, needed_count, lang_count;
	struct usb_gadget_strings **stringtabs, *t;
	const char *data = _data;
2577
	struct usb_string *s;
2578 2579 2580

	ENTER();

2581 2582
	if (unlikely(len < 16 ||
		     get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
		     get_unaligned_le32(data + 4) != len))
		goto error;
	str_count  = get_unaligned_le32(data + 8);
	lang_count = get_unaligned_le32(data + 12);

	/* if one is zero the other must be zero */
	if (unlikely(!str_count != !lang_count))
		goto error;

	/* Do we have at least as many strings as descriptors need? */
	needed_count = ffs->strings_count;
	if (unlikely(str_count < needed_count))
		goto error;

2597 2598 2599 2600
	/*
	 * If we don't need any strings just return and free all
	 * memory.
	 */
2601 2602 2603 2604 2605
	if (!needed_count) {
		kfree(_data);
		return 0;
	}

2606
	/* Allocate everything in one chunk so there's less maintenance. */
2607 2608
	{
		unsigned i = 0;
2609 2610 2611 2612 2613 2614
		vla_group(d);
		vla_item(d, struct usb_gadget_strings *, stringtabs,
			lang_count + 1);
		vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
		vla_item(d, struct usb_string, strings,
			lang_count*(needed_count+1));
2615

2616 2617 2618
		char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);

		if (unlikely(!vlabuf)) {
2619 2620 2621 2622
			kfree(_data);
			return -ENOMEM;
		}

2623 2624 2625
		/* Initialize the VLA pointers */
		stringtabs = vla_ptr(vlabuf, d, stringtabs);
		t = vla_ptr(vlabuf, d, stringtab);
2626 2627 2628 2629 2630 2631
		i = lang_count;
		do {
			*stringtabs++ = t++;
		} while (--i);
		*stringtabs = NULL;

2632 2633 2634 2635
		/* stringtabs = vlabuf = d_stringtabs for later kfree */
		stringtabs = vla_ptr(vlabuf, d, stringtabs);
		t = vla_ptr(vlabuf, d, stringtab);
		s = vla_ptr(vlabuf, d, strings);
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
	}

	/* For each language */
	data += 16;
	len -= 16;

	do { /* lang_count > 0 so we can use do-while */
		unsigned needed = needed_count;

		if (unlikely(len < 3))
			goto error_free;
		t->language = get_unaligned_le16(data);
		t->strings  = s;
		++t;

		data += 2;
		len -= 2;

		/* For each string */
		do { /* str_count > 0 so we can use do-while */
			size_t length = strnlen(data, len);

			if (unlikely(length == len))
				goto error_free;

2661 2662 2663 2664 2665
			/*
			 * User may provide more strings then we need,
			 * if that's the case we simply ignore the
			 * rest
			 */
2666
			if (likely(needed)) {
2667 2668
				/*
				 * s->id will be set while adding
2669
				 * function to configuration so for
2670 2671
				 * now just leave garbage here.
				 */
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
				s->s = data;
				--needed;
				++s;
			}

			data += length + 1;
			len -= length + 1;
		} while (--str_count);

		s->id = 0;   /* terminator */
		s->s = NULL;
		++s;

	} while (--lang_count);

	/* Some garbage left? */
	if (unlikely(len))
		goto error_free;

	/* Done! */
	ffs->stringtabs = stringtabs;
	ffs->raw_strings = _data;

	return 0;

error_free:
	kfree(stringtabs);
error:
	kfree(_data);
	return -EINVAL;
}


/* Events handling and management *******************************************/

static void __ffs_event_add(struct ffs_data *ffs,
			    enum usb_functionfs_event_type type)
{
	enum usb_functionfs_event_type rem_type1, rem_type2 = type;
	int neg = 0;

2713 2714 2715 2716
	/*
	 * Abort any unhandled setup
	 *
	 * We do not need to worry about some cmpxchg() changing value
2717 2718
	 * of ffs->setup_state without holding the lock because when
	 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2719 2720
	 * the source does nothing.
	 */
2721
	if (ffs->setup_state == FFS_SETUP_PENDING)
2722
		ffs->setup_state = FFS_SETUP_CANCELLED;
2723

2724 2725 2726 2727 2728 2729 2730
	/*
	 * Logic of this function guarantees that there are at most four pending
	 * evens on ffs->ev.types queue.  This is important because the queue
	 * has space for four elements only and __ffs_ep0_read_events function
	 * depends on that limit as well.  If more event types are added, those
	 * limits have to be revisited or guaranteed to still hold.
	 */
2731 2732 2733
	switch (type) {
	case FUNCTIONFS_RESUME:
		rem_type2 = FUNCTIONFS_SUSPEND;
2734
		fallthrough;
2735 2736 2737
	case FUNCTIONFS_SUSPEND:
	case FUNCTIONFS_SETUP:
		rem_type1 = type;
2738
		/* Discard all similar events */
2739 2740 2741 2742 2743 2744
		break;

	case FUNCTIONFS_BIND:
	case FUNCTIONFS_UNBIND:
	case FUNCTIONFS_DISABLE:
	case FUNCTIONFS_ENABLE:
2745
		/* Discard everything other then power management. */
2746 2747 2748 2749 2750 2751
		rem_type1 = FUNCTIONFS_SUSPEND;
		rem_type2 = FUNCTIONFS_RESUME;
		neg = 1;
		break;

	default:
2752 2753
		WARN(1, "%d: unknown event, this should not happen\n", type);
		return;
2754 2755 2756 2757 2758 2759 2760 2761 2762
	}

	{
		u8 *ev  = ffs->ev.types, *out = ev;
		unsigned n = ffs->ev.count;
		for (; n; --n, ++ev)
			if ((*ev == rem_type1 || *ev == rem_type2) == neg)
				*out++ = *ev;
			else
2763
				pr_vdebug("purging event %d\n", *ev);
2764 2765 2766
		ffs->ev.count = out - ffs->ev.types;
	}

2767
	pr_vdebug("adding event %d\n", type);
2768 2769
	ffs->ev.types[ffs->ev.count++] = type;
	wake_up_locked(&ffs->ev.waitq);
2770 2771
	if (ffs->ffs_eventfd)
		eventfd_signal(ffs->ffs_eventfd, 1);
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
}

static void ffs_event_add(struct ffs_data *ffs,
			  enum usb_functionfs_event_type type)
{
	unsigned long flags;
	spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
	__ffs_event_add(ffs, type);
	spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
}

/* Bind/unbind USB function hooks *******************************************/

2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
{
	int i;

	for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
		if (ffs->eps_addrmap[i] == endpoint_address)
			return i;
	return -ENOENT;
}

2795 2796 2797 2798 2799 2800 2801
static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
				    struct usb_descriptor_header *desc,
				    void *priv)
{
	struct usb_endpoint_descriptor *ds = (void *)desc;
	struct ffs_function *func = priv;
	struct ffs_ep *ffs_ep;
2802 2803
	unsigned ep_desc_id;
	int idx;
2804
	static const char *speed_names[] = { "full", "high", "super" };
2805 2806 2807 2808

	if (type != FFS_DESCRIPTOR)
		return 0;

2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
	/*
	 * If ss_descriptors is not NULL, we are reading super speed
	 * descriptors; if hs_descriptors is not NULL, we are reading high
	 * speed descriptors; otherwise, we are reading full speed
	 * descriptors.
	 */
	if (func->function.ss_descriptors) {
		ep_desc_id = 2;
		func->function.ss_descriptors[(long)valuep] = desc;
	} else if (func->function.hs_descriptors) {
		ep_desc_id = 1;
2820
		func->function.hs_descriptors[(long)valuep] = desc;
2821 2822
	} else {
		ep_desc_id = 0;
2823
		func->function.fs_descriptors[(long)valuep]    = desc;
2824
	}
2825 2826 2827 2828

	if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
		return 0;

2829 2830 2831 2832
	idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
	if (idx < 0)
		return idx;

2833 2834
	ffs_ep = func->eps + idx;

2835 2836 2837
	if (unlikely(ffs_ep->descs[ep_desc_id])) {
		pr_err("two %sspeed descriptors for EP %d\n",
			  speed_names[ep_desc_id],
2838
			  ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2839 2840
		return -EINVAL;
	}
2841
	ffs_ep->descs[ep_desc_id] = ds;
2842 2843 2844 2845 2846 2847 2848 2849 2850

	ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
	if (ffs_ep->ep) {
		ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
		if (!ds->wMaxPacketSize)
			ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
	} else {
		struct usb_request *req;
		struct usb_ep *ep;
2851
		u8 bEndpointAddress;
2852
		u16 wMaxPacketSize;
2853

2854 2855 2856 2857 2858
		/*
		 * We back up bEndpointAddress because autoconfig overwrites
		 * it with physical endpoint address.
		 */
		bEndpointAddress = ds->bEndpointAddress;
2859 2860 2861 2862 2863
		/*
		 * We back up wMaxPacketSize because autoconfig treats
		 * endpoint descriptors as if they were full speed.
		 */
		wMaxPacketSize = ds->wMaxPacketSize;
2864
		pr_vdebug("autoconfig\n");
2865 2866 2867
		ep = usb_ep_autoconfig(func->gadget, ds);
		if (unlikely(!ep))
			return -ENOTSUPP;
2868
		ep->driver_data = func->eps + idx;
2869 2870 2871 2872 2873 2874 2875 2876 2877

		req = usb_ep_alloc_request(ep, GFP_KERNEL);
		if (unlikely(!req))
			return -ENOMEM;

		ffs_ep->ep  = ep;
		ffs_ep->req = req;
		func->eps_revmap[ds->bEndpointAddress &
				 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2878 2879 2880 2881 2882 2883
		/*
		 * If we use virtual address mapping, we restore
		 * original bEndpointAddress value.
		 */
		if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
			ds->bEndpointAddress = bEndpointAddress;
2884 2885 2886 2887 2888
		/*
		 * Restore wMaxPacketSize which was potentially
		 * overwritten by autoconfig.
		 */
		ds->wMaxPacketSize = wMaxPacketSize;
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
	}
	ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);

	return 0;
}

static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
				   struct usb_descriptor_header *desc,
				   void *priv)
{
	struct ffs_function *func = priv;
	unsigned idx;
	u8 newValue;

	switch (type) {
	default:
	case FFS_DESCRIPTOR:
		/* Handled in previous pass by __ffs_func_bind_do_descs() */
		return 0;

	case FFS_INTERFACE:
		idx = *valuep;
		if (func->interfaces_nums[idx] < 0) {
			int id = usb_interface_id(func->conf, &func->function);
			if (unlikely(id < 0))
				return id;
			func->interfaces_nums[idx] = id;
		}
		newValue = func->interfaces_nums[idx];
		break;

	case FFS_STRING:
		/* String' IDs are allocated when fsf_data is bound to cdev */
		newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
		break;

	case FFS_ENDPOINT:
2926 2927 2928 2929
		/*
		 * USB_DT_ENDPOINT are handled in
		 * __ffs_func_bind_do_descs().
		 */
2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
		if (desc->bDescriptorType == USB_DT_ENDPOINT)
			return 0;

		idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
		if (unlikely(!func->eps[idx].ep))
			return -EINVAL;

		{
			struct usb_endpoint_descriptor **descs;
			descs = func->eps[idx].descs;
			newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
		}
		break;
	}

2945
	pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2946 2947 2948 2949
	*valuep = newValue;
	return 0;
}

2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
				      struct usb_os_desc_header *h, void *data,
				      unsigned len, void *priv)
{
	struct ffs_function *func = priv;
	u8 length = 0;

	switch (type) {
	case FFS_OS_DESC_EXT_COMPAT: {
		struct usb_ext_compat_desc *desc = data;
		struct usb_os_desc_table *t;

		t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
		t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
		memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
		       ARRAY_SIZE(desc->CompatibleID) +
		       ARRAY_SIZE(desc->SubCompatibleID));
		length = sizeof(*desc);
	}
		break;
	case FFS_OS_DESC_EXT_PROP: {
		struct usb_ext_prop_desc *desc = data;
		struct usb_os_desc_table *t;
		struct usb_os_desc_ext_prop *ext_prop;
		char *ext_prop_name;
		char *ext_prop_data;

		t = &func->function.os_desc_table[h->interface];
		t->if_id = func->interfaces_nums[h->interface];

		ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
		func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);

		ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
		ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2985
		ext_prop->data_len = le32_to_cpu(*(__le32 *)
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
			usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
		length = ext_prop->name_len + ext_prop->data_len + 14;

		ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
		func->ffs->ms_os_descs_ext_prop_name_avail +=
			ext_prop->name_len;

		ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
		func->ffs->ms_os_descs_ext_prop_data_avail +=
			ext_prop->data_len;
		memcpy(ext_prop_data,
		       usb_ext_prop_data_ptr(data, ext_prop->name_len),
		       ext_prop->data_len);
		/* unicode data reported to the host as "WCHAR"s */
		switch (ext_prop->type) {
		case USB_EXT_PROP_UNICODE:
		case USB_EXT_PROP_UNICODE_ENV:
		case USB_EXT_PROP_UNICODE_LINK:
		case USB_EXT_PROP_UNICODE_MULTI:
			ext_prop->data_len *= 2;
			break;
		}
		ext_prop->data = ext_prop_data;

		memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
		       ext_prop->name_len);
		/* property name reported to the host as "WCHAR"s */
		ext_prop->name_len *= 2;
		ext_prop->name = ext_prop_name;

		t->os_desc->ext_prop_len +=
			ext_prop->name_len + ext_prop->data_len + 14;
		++t->os_desc->ext_prop_count;
		list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
	}
		break;
	default:
		pr_vdebug("unknown descriptor: %d\n", type);
	}

	return length;
}

3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
						struct usb_configuration *c)
{
	struct ffs_function *func = ffs_func_from_usb(f);
	struct f_fs_opts *ffs_opts =
		container_of(f->fi, struct f_fs_opts, func_inst);
	int ret;

	ENTER();

	/*
	 * Legacy gadget triggers binding in functionfs_ready_callback,
	 * which already uses locking; taking the same lock here would
	 * cause a deadlock.
	 *
	 * Configfs-enabled gadgets however do need ffs_dev_lock.
	 */
	if (!ffs_opts->no_configfs)
		ffs_dev_lock();
	ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
	func->ffs = ffs_opts->dev->ffs_data;
	if (!ffs_opts->no_configfs)
		ffs_dev_unlock();
	if (ret)
		return ERR_PTR(ret);

	func->conf = c;
	func->gadget = c->cdev->gadget;

	/*
	 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
	 * configurations are bound in sequence with list_for_each_entry,
	 * in each configuration its functions are bound in sequence
	 * with list_for_each_entry, so we assume no race condition
	 * with regard to ffs_opts->bound access
	 */
	if (!ffs_opts->refcnt) {
		ret = functionfs_bind(func->ffs, c->cdev);
		if (ret)
			return ERR_PTR(ret);
	}
	ffs_opts->refcnt++;
	func->function.strings = func->ffs->stringtabs;

	return ffs_opts;
}

static int _ffs_func_bind(struct usb_configuration *c,
			  struct usb_function *f)
3078 3079 3080 3081 3082
{
	struct ffs_function *func = ffs_func_from_usb(f);
	struct ffs_data *ffs = func->ffs;

	const int full = !!func->ffs->fs_descs_count;
3083 3084
	const int high = !!func->ffs->hs_descs_count;
	const int super = !!func->ffs->ss_descs_count;
3085

3086
	int fs_len, hs_len, ss_len, ret, i;
3087
	struct ffs_ep *eps_ptr;
3088 3089

	/* Make it a single chunk, less management later on */
3090 3091 3092 3093 3094 3095
	vla_group(d);
	vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
	vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
		full ? ffs->fs_descs_count + 1 : 0);
	vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
		high ? ffs->hs_descs_count + 1 : 0);
3096 3097
	vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
		super ? ffs->ss_descs_count + 1 : 0);
3098
	vla_item_with_sz(d, short, inums, ffs->interfaces_count);
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
	vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
			 c->cdev->use_os_string ? ffs->interfaces_count : 0);
	vla_item_with_sz(d, char[16], ext_compat,
			 c->cdev->use_os_string ? ffs->interfaces_count : 0);
	vla_item_with_sz(d, struct usb_os_desc, os_desc,
			 c->cdev->use_os_string ? ffs->interfaces_count : 0);
	vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
			 ffs->ms_os_descs_ext_prop_count);
	vla_item_with_sz(d, char, ext_prop_name,
			 ffs->ms_os_descs_ext_prop_name_len);
	vla_item_with_sz(d, char, ext_prop_data,
			 ffs->ms_os_descs_ext_prop_data_len);
3111
	vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
3112
	char *vlabuf;
3113 3114 3115

	ENTER();

3116 3117
	/* Has descriptors only for speeds gadget does not support */
	if (unlikely(!(full | high | super)))
3118 3119
		return -ENOTSUPP;

3120
	/* Allocate a single chunk, less management later on */
3121
	vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
3122
	if (unlikely(!vlabuf))
3123 3124
		return -ENOMEM;

3125 3126 3127 3128 3129 3130
	ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
	ffs->ms_os_descs_ext_prop_name_avail =
		vla_ptr(vlabuf, d, ext_prop_name);
	ffs->ms_os_descs_ext_prop_data_avail =
		vla_ptr(vlabuf, d, ext_prop_data);

3131 3132 3133
	/* Copy descriptors  */
	memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
	       ffs->raw_descs_length);
3134

3135
	memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
3136 3137 3138
	eps_ptr = vla_ptr(vlabuf, d, eps);
	for (i = 0; i < ffs->eps_count; i++)
		eps_ptr[i].num = -1;
3139

3140 3141 3142 3143 3144
	/* Save pointers
	 * d_eps == vlabuf, func->eps used to kfree vlabuf later
	*/
	func->eps             = vla_ptr(vlabuf, d, eps);
	func->interfaces_nums = vla_ptr(vlabuf, d, inums);
3145

3146 3147
	/*
	 * Go through all the endpoint descriptors and allocate
3148
	 * endpoints first, so that later we can rewrite the endpoint
3149 3150
	 * numbers without worrying that it may be described later on.
	 */
3151
	if (likely(full)) {
3152
		func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
3153 3154 3155 3156 3157 3158
		fs_len = ffs_do_descs(ffs->fs_descs_count,
				      vla_ptr(vlabuf, d, raw_descs),
				      d_raw_descs__sz,
				      __ffs_func_bind_do_descs, func);
		if (unlikely(fs_len < 0)) {
			ret = fs_len;
3159
			goto error;
3160
		}
3161
	} else {
3162
		fs_len = 0;
3163 3164 3165
	}

	if (likely(high)) {
3166
		func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
		hs_len = ffs_do_descs(ffs->hs_descs_count,
				      vla_ptr(vlabuf, d, raw_descs) + fs_len,
				      d_raw_descs__sz - fs_len,
				      __ffs_func_bind_do_descs, func);
		if (unlikely(hs_len < 0)) {
			ret = hs_len;
			goto error;
		}
	} else {
		hs_len = 0;
	}

	if (likely(super)) {
3180 3181
		func->function.ss_descriptors = func->function.ssp_descriptors =
			vla_ptr(vlabuf, d, ss_descs);
3182
		ss_len = ffs_do_descs(ffs->ss_descs_count,
3183 3184 3185
				vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
				d_raw_descs__sz - fs_len - hs_len,
				__ffs_func_bind_do_descs, func);
3186 3187
		if (unlikely(ss_len < 0)) {
			ret = ss_len;
3188
			goto error;
3189 3190 3191
		}
	} else {
		ss_len = 0;
3192 3193
	}

3194 3195 3196 3197 3198
	/*
	 * Now handle interface numbers allocation and interface and
	 * endpoint numbers rewriting.  We can do that in one go
	 * now.
	 */
3199
	ret = ffs_do_descs(ffs->fs_descs_count +
3200 3201
			   (high ? ffs->hs_descs_count : 0) +
			   (super ? ffs->ss_descs_count : 0),
3202
			   vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
3203 3204 3205 3206
			   __ffs_func_bind_do_nums, func);
	if (unlikely(ret < 0))
		goto error;

3207
	func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
3208
	if (c->cdev->use_os_string) {
3209 3210 3211 3212 3213 3214 3215 3216 3217 3218
		for (i = 0; i < ffs->interfaces_count; ++i) {
			struct usb_os_desc *desc;

			desc = func->function.os_desc_table[i].os_desc =
				vla_ptr(vlabuf, d, os_desc) +
				i * sizeof(struct usb_os_desc);
			desc->ext_compat_id =
				vla_ptr(vlabuf, d, ext_compat) + i * 16;
			INIT_LIST_HEAD(&desc->ext_prop);
		}
3219 3220 3221 3222 3223 3224 3225 3226 3227
		ret = ffs_do_os_descs(ffs->ms_os_descs_count,
				      vla_ptr(vlabuf, d, raw_descs) +
				      fs_len + hs_len + ss_len,
				      d_raw_descs__sz - fs_len - hs_len -
				      ss_len,
				      __ffs_func_bind_do_os_desc, func);
		if (unlikely(ret < 0))
			goto error;
	}
3228 3229 3230
	func->function.os_desc_n =
		c->cdev->use_os_string ? ffs->interfaces_count : 0;

3231 3232 3233 3234 3235 3236 3237 3238 3239
	/* And we're done */
	ffs_event_add(ffs, FUNCTIONFS_BIND);
	return 0;

error:
	/* XXX Do we need to release all claimed endpoints here? */
	return ret;
}

3240 3241 3242 3243
static int ffs_func_bind(struct usb_configuration *c,
			 struct usb_function *f)
{
	struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
3244 3245
	struct ffs_function *func = ffs_func_from_usb(f);
	int ret;
3246 3247 3248 3249

	if (IS_ERR(ffs_opts))
		return PTR_ERR(ffs_opts);

3250 3251 3252 3253 3254
	ret = _ffs_func_bind(c, f);
	if (ret && !--ffs_opts->refcnt)
		functionfs_unbind(func->ffs);

	return ret;
3255 3256
}

3257 3258 3259

/* Other USB function hooks *************************************************/

3260 3261 3262 3263 3264 3265 3266
static void ffs_reset_work(struct work_struct *work)
{
	struct ffs_data *ffs = container_of(work,
		struct ffs_data, reset_work);
	ffs_data_reset(ffs);
}

3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
static int ffs_func_set_alt(struct usb_function *f,
			    unsigned interface, unsigned alt)
{
	struct ffs_function *func = ffs_func_from_usb(f);
	struct ffs_data *ffs = func->ffs;
	int ret = 0, intf;

	if (alt != (unsigned)-1) {
		intf = ffs_func_revmap_intf(func, interface);
		if (unlikely(intf < 0))
			return intf;
	}

	if (ffs->func)
		ffs_func_eps_disable(ffs->func);

3283 3284 3285 3286 3287 3288 3289
	if (ffs->state == FFS_DEACTIVATED) {
		ffs->state = FFS_CLOSING;
		INIT_WORK(&ffs->reset_work, ffs_reset_work);
		schedule_work(&ffs->reset_work);
		return -ENODEV;
	}

3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
	if (ffs->state != FFS_ACTIVE)
		return -ENODEV;

	if (alt == (unsigned)-1) {
		ffs->func = NULL;
		ffs_event_add(ffs, FUNCTIONFS_DISABLE);
		return 0;
	}

	ffs->func = func;
	ret = ffs_func_eps_enable(func);
	if (likely(ret >= 0))
		ffs_event_add(ffs, FUNCTIONFS_ENABLE);
	return ret;
}

static void ffs_func_disable(struct usb_function *f)
{
	ffs_func_set_alt(f, 0, (unsigned)-1);
}

static int ffs_func_setup(struct usb_function *f,
			  const struct usb_ctrlrequest *creq)
{
	struct ffs_function *func = ffs_func_from_usb(f);
	struct ffs_data *ffs = func->ffs;
	unsigned long flags;
	int ret;

	ENTER();

3321 3322 3323 3324 3325
	pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
	pr_vdebug("creq->bRequest     = %02x\n", creq->bRequest);
	pr_vdebug("creq->wValue       = %04x\n", le16_to_cpu(creq->wValue));
	pr_vdebug("creq->wIndex       = %04x\n", le16_to_cpu(creq->wIndex));
	pr_vdebug("creq->wLength      = %04x\n", le16_to_cpu(creq->wLength));
3326

3327 3328
	/*
	 * Most requests directed to interface go through here
3329 3330 3331 3332
	 * (notable exceptions are set/get interface) so we need to
	 * handle them.  All other either handled by composite or
	 * passed to usb_configuration->setup() (if one is set).  No
	 * matter, we will handle requests directed to endpoint here
3333 3334 3335
	 * as well (as it's straightforward).  Other request recipient
	 * types are only handled when the user flag FUNCTIONFS_ALL_CTRL_RECIP
	 * is being used.
3336
	 */
3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350
	if (ffs->state != FFS_ACTIVE)
		return -ENODEV;

	switch (creq->bRequestType & USB_RECIP_MASK) {
	case USB_RECIP_INTERFACE:
		ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
		if (unlikely(ret < 0))
			return ret;
		break;

	case USB_RECIP_ENDPOINT:
		ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
		if (unlikely(ret < 0))
			return ret;
3351 3352
		if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
			ret = func->ffs->eps_addrmap[ret];
3353 3354 3355
		break;

	default:
3356 3357 3358 3359
		if (func->ffs->user_flags & FUNCTIONFS_ALL_CTRL_RECIP)
			ret = le16_to_cpu(creq->wIndex);
		else
			return -EOPNOTSUPP;
3360 3361 3362 3363 3364 3365 3366 3367
	}

	spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
	ffs->ev.setup = *creq;
	ffs->ev.setup.wIndex = cpu_to_le16(ret);
	__ffs_event_add(ffs, FUNCTIONFS_SETUP);
	spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);

3368
	return creq->wLength == 0 ? USB_GADGET_DELAYED_STATUS : 0;
3369 3370
}

3371
static bool ffs_func_req_match(struct usb_function *f,
3372 3373
			       const struct usb_ctrlrequest *creq,
			       bool config0)
3374 3375 3376
{
	struct ffs_function *func = ffs_func_from_usb(f);

3377
	if (config0 && !(func->ffs->user_flags & FUNCTIONFS_CONFIG0_SETUP))
3378 3379
		return false;

3380 3381
	switch (creq->bRequestType & USB_RECIP_MASK) {
	case USB_RECIP_INTERFACE:
3382 3383
		return (ffs_func_revmap_intf(func,
					     le16_to_cpu(creq->wIndex)) >= 0);
3384
	case USB_RECIP_ENDPOINT:
3385 3386
		return (ffs_func_revmap_ep(func,
					   le16_to_cpu(creq->wIndex)) >= 0);
3387 3388 3389 3390 3391 3392
	default:
		return (bool) (func->ffs->user_flags &
			       FUNCTIONFS_ALL_CTRL_RECIP);
	}
}

3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
static void ffs_func_suspend(struct usb_function *f)
{
	ENTER();
	ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
}

static void ffs_func_resume(struct usb_function *f)
{
	ENTER();
	ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
}


3406
/* Endpoint and interface numbers reverse mapping ***************************/
3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427

static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
{
	num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
	return num ? num : -EDOM;
}

static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
{
	short *nums = func->interfaces_nums;
	unsigned count = func->ffs->interfaces_count;

	for (; count; --count, ++nums) {
		if (*nums >= 0 && *nums == intf)
			return nums - func->interfaces_nums;
	}

	return -EDOM;
}


3428 3429 3430 3431
/* Devices management *******************************************************/

static LIST_HEAD(ffs_devices);

3432
static struct ffs_dev *_ffs_do_find_dev(const char *name)
3433 3434 3435
{
	struct ffs_dev *dev;

3436 3437 3438
	if (!name)
		return NULL;

3439 3440 3441 3442
	list_for_each_entry(dev, &ffs_devices, entry) {
		if (strcmp(dev->name, name) == 0)
			return dev;
	}
3443

3444 3445 3446 3447 3448 3449
	return NULL;
}

/*
 * ffs_lock must be taken by the caller of this function
 */
3450
static struct ffs_dev *_ffs_get_single_dev(void)
3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
{
	struct ffs_dev *dev;

	if (list_is_singular(&ffs_devices)) {
		dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
		if (dev->single)
			return dev;
	}

	return NULL;
}

/*
 * ffs_lock must be taken by the caller of this function
 */
3466
static struct ffs_dev *_ffs_find_dev(const char *name)
3467 3468 3469
{
	struct ffs_dev *dev;

3470
	dev = _ffs_get_single_dev();
3471 3472 3473
	if (dev)
		return dev;

3474
	return _ffs_do_find_dev(name);
3475 3476
}

3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495
/* Configfs support *********************************************************/

static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
{
	return container_of(to_config_group(item), struct f_fs_opts,
			    func_inst.group);
}

static void ffs_attr_release(struct config_item *item)
{
	struct f_fs_opts *opts = to_ffs_opts(item);

	usb_put_function_instance(&opts->func_inst);
}

static struct configfs_item_operations ffs_item_ops = {
	.release	= ffs_attr_release,
};

3496
static const struct config_item_type ffs_func_type = {
3497 3498 3499 3500 3501
	.ct_item_ops	= &ffs_item_ops,
	.ct_owner	= THIS_MODULE,
};


3502 3503 3504 3505 3506 3507 3508 3509
/* Function registration interface ******************************************/

static void ffs_free_inst(struct usb_function_instance *f)
{
	struct f_fs_opts *opts;

	opts = to_f_fs_opts(f);
	ffs_dev_lock();
3510
	_ffs_free_dev(opts->dev);
3511 3512 3513 3514
	ffs_dev_unlock();
	kfree(opts);
}

3515 3516
static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
{
3517
	if (strlen(name) >= sizeof_field(struct ffs_dev, name))
3518
		return -ENAMETOOLONG;
3519
	return ffs_name_dev(to_f_fs_opts(fi)->dev, name);
3520 3521
}

3522 3523 3524 3525 3526 3527 3528 3529 3530
static struct usb_function_instance *ffs_alloc_inst(void)
{
	struct f_fs_opts *opts;
	struct ffs_dev *dev;

	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
	if (!opts)
		return ERR_PTR(-ENOMEM);

3531
	opts->func_inst.set_inst_name = ffs_set_inst_name;
3532 3533
	opts->func_inst.free_func_inst = ffs_free_inst;
	ffs_dev_lock();
3534
	dev = _ffs_alloc_dev();
3535 3536 3537 3538 3539 3540
	ffs_dev_unlock();
	if (IS_ERR(dev)) {
		kfree(opts);
		return ERR_CAST(dev);
	}
	opts->dev = dev;
3541
	dev->opts = opts;
3542

3543 3544
	config_group_init_type_name(&opts->func_inst.group, "",
				    &ffs_func_type);
3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
	return &opts->func_inst;
}

static void ffs_free(struct usb_function *f)
{
	kfree(ffs_func_from_usb(f));
}

static void ffs_func_unbind(struct usb_configuration *c,
			    struct usb_function *f)
{
	struct ffs_function *func = ffs_func_from_usb(f);
	struct ffs_data *ffs = func->ffs;
	struct f_fs_opts *opts =
		container_of(f->fi, struct f_fs_opts, func_inst);
	struct ffs_ep *ep = func->eps;
	unsigned count = ffs->eps_count;
	unsigned long flags;

	ENTER();
	if (ffs->func == func) {
		ffs_func_eps_disable(func);
		ffs->func = NULL;
	}

	if (!--opts->refcnt)
		functionfs_unbind(ffs);

	/* cleanup after autoconfig */
	spin_lock_irqsave(&func->ffs->eps_lock, flags);
3575
	while (count--) {
3576 3577 3578 3579
		if (ep->ep && ep->req)
			usb_ep_free_request(ep->ep, ep->req);
		ep->req = NULL;
		++ep;
3580
	}
3581 3582 3583 3584 3585 3586 3587 3588 3589
	spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
	kfree(func->eps);
	func->eps = NULL;
	/*
	 * eps, descriptors and interfaces_nums are allocated in the
	 * same chunk so only one free is required.
	 */
	func->function.fs_descriptors = NULL;
	func->function.hs_descriptors = NULL;
3590
	func->function.ss_descriptors = NULL;
3591
	func->function.ssp_descriptors = NULL;
3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613
	func->interfaces_nums = NULL;

	ffs_event_add(ffs, FUNCTIONFS_UNBIND);
}

static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
{
	struct ffs_function *func;

	ENTER();

	func = kzalloc(sizeof(*func), GFP_KERNEL);
	if (unlikely(!func))
		return ERR_PTR(-ENOMEM);

	func->function.name    = "Function FS Gadget";

	func->function.bind    = ffs_func_bind;
	func->function.unbind  = ffs_func_unbind;
	func->function.set_alt = ffs_func_set_alt;
	func->function.disable = ffs_func_disable;
	func->function.setup   = ffs_func_setup;
3614
	func->function.req_match = ffs_func_req_match;
3615 3616 3617 3618 3619 3620 3621
	func->function.suspend = ffs_func_suspend;
	func->function.resume  = ffs_func_resume;
	func->function.free_func = ffs_free;

	return &func->function;
}

3622 3623 3624
/*
 * ffs_lock must be taken by the caller of this function
 */
3625
static struct ffs_dev *_ffs_alloc_dev(void)
3626 3627 3628 3629
{
	struct ffs_dev *dev;
	int ret;

3630
	if (_ffs_get_single_dev())
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
			return ERR_PTR(-EBUSY);

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (!dev)
		return ERR_PTR(-ENOMEM);

	if (list_empty(&ffs_devices)) {
		ret = functionfs_init();
		if (ret) {
			kfree(dev);
			return ERR_PTR(ret);
		}
	}

	list_add(&dev->entry, &ffs_devices);

	return dev;
}

3650
int ffs_name_dev(struct ffs_dev *dev, const char *name)
3651 3652
{
	struct ffs_dev *existing;
3653
	int ret = 0;
3654

3655
	ffs_dev_lock();
3656

3657 3658 3659 3660 3661
	existing = _ffs_do_find_dev(name);
	if (!existing)
		strlcpy(dev->name, name, ARRAY_SIZE(dev->name));
	else if (existing != dev)
		ret = -EBUSY;
3662 3663 3664 3665 3666

	ffs_dev_unlock();

	return ret;
}
3667
EXPORT_SYMBOL_GPL(ffs_name_dev);
3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683

int ffs_single_dev(struct ffs_dev *dev)
{
	int ret;

	ret = 0;
	ffs_dev_lock();

	if (!list_is_singular(&ffs_devices))
		ret = -EBUSY;
	else
		dev->single = true;

	ffs_dev_unlock();
	return ret;
}
3684
EXPORT_SYMBOL_GPL(ffs_single_dev);
3685 3686 3687 3688

/*
 * ffs_lock must be taken by the caller of this function
 */
3689
static void _ffs_free_dev(struct ffs_dev *dev)
3690 3691
{
	list_del(&dev->entry);
3692 3693 3694 3695 3696

	/* Clear the private_data pointer to stop incorrect dev access */
	if (dev->ffs_data)
		dev->ffs_data->private_data = NULL;

3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708
	kfree(dev);
	if (list_empty(&ffs_devices))
		functionfs_cleanup();
}

static void *ffs_acquire_dev(const char *dev_name)
{
	struct ffs_dev *ffs_dev;

	ENTER();
	ffs_dev_lock();

3709
	ffs_dev = _ffs_find_dev(dev_name);
3710
	if (!ffs_dev)
3711
		ffs_dev = ERR_PTR(-ENOENT);
3712 3713
	else if (ffs_dev->mounted)
		ffs_dev = ERR_PTR(-EBUSY);
3714 3715
	else if (ffs_dev->ffs_acquire_dev_callback &&
	    ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3716
		ffs_dev = ERR_PTR(-ENOENT);
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731
	else
		ffs_dev->mounted = true;

	ffs_dev_unlock();
	return ffs_dev;
}

static void ffs_release_dev(struct ffs_data *ffs_data)
{
	struct ffs_dev *ffs_dev;

	ENTER();
	ffs_dev_lock();

	ffs_dev = ffs_data->private_data;
3732
	if (ffs_dev) {
3733
		ffs_dev->mounted = false;
3734 3735 3736 3737

		if (ffs_dev->ffs_release_dev_callback)
			ffs_dev->ffs_release_dev_callback(ffs_dev);
	}
3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762

	ffs_dev_unlock();
}

static int ffs_ready(struct ffs_data *ffs)
{
	struct ffs_dev *ffs_obj;
	int ret = 0;

	ENTER();
	ffs_dev_lock();

	ffs_obj = ffs->private_data;
	if (!ffs_obj) {
		ret = -EINVAL;
		goto done;
	}
	if (WARN_ON(ffs_obj->desc_ready)) {
		ret = -EBUSY;
		goto done;
	}

	ffs_obj->desc_ready = true;
	ffs_obj->ffs_data = ffs;

3763
	if (ffs_obj->ffs_ready_callback) {
3764
		ret = ffs_obj->ffs_ready_callback(ffs);
3765 3766 3767
		if (ret)
			goto done;
	}
3768

3769
	set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
3770 3771 3772 3773 3774 3775 3776 3777
done:
	ffs_dev_unlock();
	return ret;
}

static void ffs_closed(struct ffs_data *ffs)
{
	struct ffs_dev *ffs_obj;
3778
	struct f_fs_opts *opts;
3779
	struct config_item *ci;
3780 3781 3782 3783 3784 3785 3786 3787 3788

	ENTER();
	ffs_dev_lock();

	ffs_obj = ffs->private_data;
	if (!ffs_obj)
		goto done;

	ffs_obj->desc_ready = false;
3789
	ffs_obj->ffs_data = NULL;
3790

3791 3792
	if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
	    ffs_obj->ffs_closed_callback)
3793
		ffs_obj->ffs_closed_callback(ffs);
3794

3795 3796 3797 3798 3799 3800
	if (ffs_obj->opts)
		opts = ffs_obj->opts;
	else
		goto done;

	if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
3801
	    || !kref_read(&opts->func_inst.group.cg_item.ci_kref))
3802 3803
		goto done;

3804 3805 3806
	ci = opts->func_inst.group.cg_item.ci_parent->ci_parent;
	ffs_dev_unlock();

3807 3808
	if (test_bit(FFS_FL_BOUND, &ffs->flags))
		unregister_gadget_item(ci);
3809
	return;
3810 3811 3812 3813
done:
	ffs_dev_unlock();
}

3814 3815 3816 3817 3818 3819 3820 3821 3822
/* Misc helper functions ****************************************************/

static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
{
	return nonblock
		? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
		: mutex_lock_interruptible(mutex);
}

A
Al Viro 已提交
3823
static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3824 3825 3826 3827 3828 3829 3830 3831 3832 3833
{
	char *data;

	if (unlikely(!len))
		return NULL;

	data = kmalloc(len, GFP_KERNEL);
	if (unlikely(!data))
		return ERR_PTR(-ENOMEM);

3834
	if (unlikely(copy_from_user(data, buf, len))) {
3835 3836 3837 3838
		kfree(data);
		return ERR_PTR(-EFAULT);
	}

3839
	pr_vdebug("Buffer from user space:\n");
3840 3841 3842 3843
	ffs_dump_mem("", data, len);

	return data;
}
3844 3845 3846 3847

DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michal Nazarewicz");