• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * f_fs.c -- user mode file system API for USB composite function controllers
3  *
4  * Copyright (C) 2010 Samsung Electronics
5  * Author: Michal Nazarewicz <mina86@mina86.com>
6  *
7  * Based on inode.c (GadgetFS) which was:
8  * Copyright (C) 2003-2004 David Brownell
9  * Copyright (C) 2003 Agilent Technologies
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  */
16 
17 
18 /* #define DEBUG */
19 /* #define VERBOSE_DEBUG */
20 
21 #include <linux/blkdev.h>
22 #include <linux/pagemap.h>
23 #include <linux/export.h>
24 #include <linux/hid.h>
25 #include <linux/module.h>
26 #include <linux/sched/signal.h>
27 #include <linux/uio.h>
28 #include <asm/unaligned.h>
29 
30 #include <linux/usb/composite.h>
31 #include <linux/usb/functionfs.h>
32 
33 #include <linux/aio.h>
34 #include <linux/mmu_context.h>
35 #include <linux/poll.h>
36 #include <linux/eventfd.h>
37 
38 #include "u_fs.h"
39 #include "u_f.h"
40 #include "u_os_desc.h"
41 #include "configfs.h"
42 
43 #define FUNCTIONFS_MAGIC	0xa647361 /* Chosen by a honest dice roll ;) */
44 
45 /* Reference counter handling */
46 static void ffs_data_get(struct ffs_data *ffs);
47 static void ffs_data_put(struct ffs_data *ffs);
48 /* Creates new ffs_data object. */
49 static struct ffs_data *__must_check ffs_data_new(const char *dev_name)
50 	__attribute__((malloc));
51 
52 /* Opened counter handling. */
53 static void ffs_data_opened(struct ffs_data *ffs);
54 static void ffs_data_closed(struct ffs_data *ffs);
55 
56 /* Called with ffs->mutex held; take over ownership of data. */
57 static int __must_check
58 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
59 static int __must_check
60 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
61 
62 
63 /* The function structure ***************************************************/
64 
65 struct ffs_ep;
66 
67 struct ffs_function {
68 	struct usb_configuration	*conf;
69 	struct usb_gadget		*gadget;
70 	struct ffs_data			*ffs;
71 
72 	struct ffs_ep			*eps;
73 	u8				eps_revmap[16];
74 	short				*interfaces_nums;
75 
76 	struct usb_function		function;
77 };
78 
79 
ffs_func_from_usb(struct usb_function * f)80 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
81 {
82 	return container_of(f, struct ffs_function, function);
83 }
84 
85 
86 static inline enum ffs_setup_state
ffs_setup_state_clear_cancelled(struct ffs_data * ffs)87 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
88 {
89 	return (enum ffs_setup_state)
90 		cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
91 }
92 
93 
94 static void ffs_func_eps_disable(struct ffs_function *func);
95 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
96 
97 static int ffs_func_bind(struct usb_configuration *,
98 			 struct usb_function *);
99 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
100 static void ffs_func_disable(struct usb_function *);
101 static int ffs_func_setup(struct usb_function *,
102 			  const struct usb_ctrlrequest *);
103 static bool ffs_func_req_match(struct usb_function *,
104 			       const struct usb_ctrlrequest *,
105 			       bool config0);
106 static void ffs_func_suspend(struct usb_function *);
107 static void ffs_func_resume(struct usb_function *);
108 
109 
110 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
111 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
112 
113 
114 /* The endpoints structures *************************************************/
115 
116 struct ffs_ep {
117 	struct usb_ep			*ep;	/* P: ffs->eps_lock */
118 	struct usb_request		*req;	/* P: epfile->mutex */
119 
120 	/* [0]: full speed, [1]: high speed, [2]: super speed */
121 	struct usb_endpoint_descriptor	*descs[3];
122 
123 	u8				num;
124 
125 	int				status;	/* P: epfile->mutex */
126 };
127 
128 struct ffs_epfile {
129 	/* Protects ep->ep and ep->req. */
130 	struct mutex			mutex;
131 
132 	struct ffs_data			*ffs;
133 	struct ffs_ep			*ep;	/* P: ffs->eps_lock */
134 
135 	struct dentry			*dentry;
136 
137 	/*
138 	 * Buffer for holding data from partial reads which may happen since
139 	 * we’re rounding user read requests to a multiple of a max packet size.
140 	 *
141 	 * The pointer is initialised with NULL value and may be set by
142 	 * __ffs_epfile_read_data function to point to a temporary buffer.
143 	 *
144 	 * In normal operation, calls to __ffs_epfile_read_buffered will consume
145 	 * data from said buffer and eventually free it.  Importantly, while the
146 	 * function is using the buffer, it sets the pointer to NULL.  This is
147 	 * all right since __ffs_epfile_read_data and __ffs_epfile_read_buffered
148 	 * can never run concurrently (they are synchronised by epfile->mutex)
149 	 * so the latter will not assign a new value to the pointer.
150 	 *
151 	 * Meanwhile ffs_func_eps_disable frees the buffer (if the pointer is
152 	 * valid) and sets the pointer to READ_BUFFER_DROP value.  This special
153 	 * value is crux of the synchronisation between ffs_func_eps_disable and
154 	 * __ffs_epfile_read_data.
155 	 *
156 	 * Once __ffs_epfile_read_data is about to finish it will try to set the
157 	 * pointer back to its old value (as described above), but seeing as the
158 	 * pointer is not-NULL (namely READ_BUFFER_DROP) it will instead free
159 	 * the buffer.
160 	 *
161 	 * == State transitions ==
162 	 *
163 	 * • ptr == NULL:  (initial state)
164 	 *   ◦ __ffs_epfile_read_buffer_free: go to ptr == DROP
165 	 *   ◦ __ffs_epfile_read_buffered:    nop
166 	 *   ◦ __ffs_epfile_read_data allocates temp buffer: go to ptr == buf
167 	 *   ◦ reading finishes:              n/a, not in ‘and reading’ state
168 	 * • ptr == DROP:
169 	 *   ◦ __ffs_epfile_read_buffer_free: nop
170 	 *   ◦ __ffs_epfile_read_buffered:    go to ptr == NULL
171 	 *   ◦ __ffs_epfile_read_data allocates temp buffer: free buf, nop
172 	 *   ◦ reading finishes:              n/a, not in ‘and reading’ state
173 	 * • ptr == buf:
174 	 *   ◦ __ffs_epfile_read_buffer_free: free buf, go to ptr == DROP
175 	 *   ◦ __ffs_epfile_read_buffered:    go to ptr == NULL and reading
176 	 *   ◦ __ffs_epfile_read_data:        n/a, __ffs_epfile_read_buffered
177 	 *                                    is always called first
178 	 *   ◦ reading finishes:              n/a, not in ‘and reading’ state
179 	 * • ptr == NULL and reading:
180 	 *   ◦ __ffs_epfile_read_buffer_free: go to ptr == DROP and reading
181 	 *   ◦ __ffs_epfile_read_buffered:    n/a, mutex is held
182 	 *   ◦ __ffs_epfile_read_data:        n/a, mutex is held
183 	 *   ◦ reading finishes and …
184 	 *     … all data read:               free buf, go to ptr == NULL
185 	 *     … otherwise:                   go to ptr == buf and reading
186 	 * • ptr == DROP and reading:
187 	 *   ◦ __ffs_epfile_read_buffer_free: nop
188 	 *   ◦ __ffs_epfile_read_buffered:    n/a, mutex is held
189 	 *   ◦ __ffs_epfile_read_data:        n/a, mutex is held
190 	 *   ◦ reading finishes:              free buf, go to ptr == DROP
191 	 */
192 	struct ffs_buffer		*read_buffer;
193 #define READ_BUFFER_DROP ((struct ffs_buffer *)ERR_PTR(-ESHUTDOWN))
194 
195 	char				name[5];
196 
197 	unsigned char			in;	/* P: ffs->eps_lock */
198 	unsigned char			isoc;	/* P: ffs->eps_lock */
199 
200 	unsigned char			_pad;
201 };
202 
203 struct ffs_buffer {
204 	size_t length;
205 	char *data;
206 	char storage[];
207 };
208 
209 /*  ffs_io_data structure ***************************************************/
210 
211 struct ffs_io_data {
212 	bool aio;
213 	bool read;
214 
215 	struct kiocb *kiocb;
216 	struct iov_iter data;
217 	const void *to_free;
218 	char *buf;
219 
220 	struct mm_struct *mm;
221 	struct work_struct work;
222 
223 	struct usb_ep *ep;
224 	struct usb_request *req;
225 
226 	struct ffs_data *ffs;
227 };
228 
229 struct ffs_desc_helper {
230 	struct ffs_data *ffs;
231 	unsigned interfaces_count;
232 	unsigned eps_count;
233 };
234 
235 static int  __must_check ffs_epfiles_create(struct ffs_data *ffs);
236 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
237 
238 static struct dentry *
239 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
240 		   const struct file_operations *fops);
241 
242 /* Devices management *******************************************************/
243 
244 DEFINE_MUTEX(ffs_lock);
245 EXPORT_SYMBOL_GPL(ffs_lock);
246 
247 static struct ffs_dev *_ffs_find_dev(const char *name);
248 static struct ffs_dev *_ffs_alloc_dev(void);
249 static void _ffs_free_dev(struct ffs_dev *dev);
250 static void *ffs_acquire_dev(const char *dev_name);
251 static void ffs_release_dev(struct ffs_data *ffs_data);
252 static int ffs_ready(struct ffs_data *ffs);
253 static void ffs_closed(struct ffs_data *ffs);
254 
255 /* Misc helper functions ****************************************************/
256 
257 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
258 	__attribute__((warn_unused_result, nonnull));
259 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
260 	__attribute__((warn_unused_result, nonnull));
261 
262 
263 /* Control file aka ep0 *****************************************************/
264 
ffs_ep0_complete(struct usb_ep * ep,struct usb_request * req)265 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
266 {
267 	struct ffs_data *ffs = req->context;
268 
269 	complete(&ffs->ep0req_completion);
270 }
271 
__ffs_ep0_queue_wait(struct ffs_data * ffs,char * data,size_t len)272 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
273 {
274 	struct usb_request *req = ffs->ep0req;
275 	int ret;
276 
277 	req->zero     = len < le16_to_cpu(ffs->ev.setup.wLength);
278 
279 	spin_unlock_irq(&ffs->ev.waitq.lock);
280 
281 	req->buf      = data;
282 	req->length   = len;
283 
284 	/*
285 	 * UDC layer requires to provide a buffer even for ZLP, but should
286 	 * not use it at all. Let's provide some poisoned pointer to catch
287 	 * possible bug in the driver.
288 	 */
289 	if (req->buf == NULL)
290 		req->buf = (void *)0xDEADBABE;
291 
292 	reinit_completion(&ffs->ep0req_completion);
293 
294 	ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
295 	if (unlikely(ret < 0))
296 		return ret;
297 
298 	ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
299 	if (unlikely(ret)) {
300 		usb_ep_dequeue(ffs->gadget->ep0, req);
301 		return -EINTR;
302 	}
303 
304 	ffs->setup_state = FFS_NO_SETUP;
305 	return req->status ? req->status : req->actual;
306 }
307 
__ffs_ep0_stall(struct ffs_data * ffs)308 static int __ffs_ep0_stall(struct ffs_data *ffs)
309 {
310 	if (ffs->ev.can_stall) {
311 		pr_vdebug("ep0 stall\n");
312 		usb_ep_set_halt(ffs->gadget->ep0);
313 		ffs->setup_state = FFS_NO_SETUP;
314 		return -EL2HLT;
315 	} else {
316 		pr_debug("bogus ep0 stall!\n");
317 		return -ESRCH;
318 	}
319 }
320 
ffs_ep0_write(struct file * file,const char __user * buf,size_t len,loff_t * ptr)321 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
322 			     size_t len, loff_t *ptr)
323 {
324 	struct ffs_data *ffs = file->private_data;
325 	ssize_t ret;
326 	char *data;
327 
328 	ENTER();
329 
330 	/* Fast check if setup was canceled */
331 	if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
332 		return -EIDRM;
333 
334 	/* Acquire mutex */
335 	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
336 	if (unlikely(ret < 0))
337 		return ret;
338 
339 	/* Check state */
340 	switch (ffs->state) {
341 	case FFS_READ_DESCRIPTORS:
342 	case FFS_READ_STRINGS:
343 		/* Copy data */
344 		if (unlikely(len < 16)) {
345 			ret = -EINVAL;
346 			break;
347 		}
348 
349 		data = ffs_prepare_buffer(buf, len);
350 		if (IS_ERR(data)) {
351 			ret = PTR_ERR(data);
352 			break;
353 		}
354 
355 		/* Handle data */
356 		if (ffs->state == FFS_READ_DESCRIPTORS) {
357 			pr_info("read descriptors\n");
358 			ret = __ffs_data_got_descs(ffs, data, len);
359 			if (unlikely(ret < 0))
360 				break;
361 
362 			ffs->state = FFS_READ_STRINGS;
363 			ret = len;
364 		} else {
365 			pr_info("read strings\n");
366 			ret = __ffs_data_got_strings(ffs, data, len);
367 			if (unlikely(ret < 0))
368 				break;
369 
370 			ret = ffs_epfiles_create(ffs);
371 			if (unlikely(ret)) {
372 				ffs->state = FFS_CLOSING;
373 				break;
374 			}
375 
376 			ffs->state = FFS_ACTIVE;
377 			mutex_unlock(&ffs->mutex);
378 
379 			ret = ffs_ready(ffs);
380 			if (unlikely(ret < 0)) {
381 				ffs->state = FFS_CLOSING;
382 				return ret;
383 			}
384 
385 			return len;
386 		}
387 		break;
388 
389 	case FFS_ACTIVE:
390 		data = NULL;
391 		/*
392 		 * We're called from user space, we can use _irq
393 		 * rather then _irqsave
394 		 */
395 		spin_lock_irq(&ffs->ev.waitq.lock);
396 		switch (ffs_setup_state_clear_cancelled(ffs)) {
397 		case FFS_SETUP_CANCELLED:
398 			ret = -EIDRM;
399 			goto done_spin;
400 
401 		case FFS_NO_SETUP:
402 			ret = -ESRCH;
403 			goto done_spin;
404 
405 		case FFS_SETUP_PENDING:
406 			break;
407 		}
408 
409 		/* FFS_SETUP_PENDING */
410 		if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
411 			spin_unlock_irq(&ffs->ev.waitq.lock);
412 			ret = __ffs_ep0_stall(ffs);
413 			break;
414 		}
415 
416 		/* FFS_SETUP_PENDING and not stall */
417 		len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
418 
419 		spin_unlock_irq(&ffs->ev.waitq.lock);
420 
421 		data = ffs_prepare_buffer(buf, len);
422 		if (IS_ERR(data)) {
423 			ret = PTR_ERR(data);
424 			break;
425 		}
426 
427 		spin_lock_irq(&ffs->ev.waitq.lock);
428 
429 		/*
430 		 * We are guaranteed to be still in FFS_ACTIVE state
431 		 * but the state of setup could have changed from
432 		 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
433 		 * to check for that.  If that happened we copied data
434 		 * from user space in vain but it's unlikely.
435 		 *
436 		 * For sure we are not in FFS_NO_SETUP since this is
437 		 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
438 		 * transition can be performed and it's protected by
439 		 * mutex.
440 		 */
441 		if (ffs_setup_state_clear_cancelled(ffs) ==
442 		    FFS_SETUP_CANCELLED) {
443 			ret = -EIDRM;
444 done_spin:
445 			spin_unlock_irq(&ffs->ev.waitq.lock);
446 		} else {
447 			/* unlocks spinlock */
448 			ret = __ffs_ep0_queue_wait(ffs, data, len);
449 		}
450 		kfree(data);
451 		break;
452 
453 	default:
454 		ret = -EBADFD;
455 		break;
456 	}
457 
458 	mutex_unlock(&ffs->mutex);
459 	return ret;
460 }
461 
462 /* Called with ffs->ev.waitq.lock and ffs->mutex held, both released on exit. */
__ffs_ep0_read_events(struct ffs_data * ffs,char __user * buf,size_t n)463 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
464 				     size_t n)
465 {
466 	/*
467 	 * n cannot be bigger than ffs->ev.count, which cannot be bigger than
468 	 * size of ffs->ev.types array (which is four) so that's how much space
469 	 * we reserve.
470 	 */
471 	struct usb_functionfs_event events[ARRAY_SIZE(ffs->ev.types)];
472 	const size_t size = n * sizeof *events;
473 	unsigned i = 0;
474 
475 	memset(events, 0, size);
476 
477 	do {
478 		events[i].type = ffs->ev.types[i];
479 		if (events[i].type == FUNCTIONFS_SETUP) {
480 			events[i].u.setup = ffs->ev.setup;
481 			ffs->setup_state = FFS_SETUP_PENDING;
482 		}
483 	} while (++i < n);
484 
485 	ffs->ev.count -= n;
486 	if (ffs->ev.count)
487 		memmove(ffs->ev.types, ffs->ev.types + n,
488 			ffs->ev.count * sizeof *ffs->ev.types);
489 
490 	spin_unlock_irq(&ffs->ev.waitq.lock);
491 	mutex_unlock(&ffs->mutex);
492 
493 	return unlikely(copy_to_user(buf, events, size)) ? -EFAULT : size;
494 }
495 
ffs_ep0_read(struct file * file,char __user * buf,size_t len,loff_t * ptr)496 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
497 			    size_t len, loff_t *ptr)
498 {
499 	struct ffs_data *ffs = file->private_data;
500 	char *data = NULL;
501 	size_t n;
502 	int ret;
503 
504 	ENTER();
505 
506 	/* Fast check if setup was canceled */
507 	if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
508 		return -EIDRM;
509 
510 	/* Acquire mutex */
511 	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
512 	if (unlikely(ret < 0))
513 		return ret;
514 
515 	/* Check state */
516 	if (ffs->state != FFS_ACTIVE) {
517 		ret = -EBADFD;
518 		goto done_mutex;
519 	}
520 
521 	/*
522 	 * We're called from user space, we can use _irq rather then
523 	 * _irqsave
524 	 */
525 	spin_lock_irq(&ffs->ev.waitq.lock);
526 
527 	switch (ffs_setup_state_clear_cancelled(ffs)) {
528 	case FFS_SETUP_CANCELLED:
529 		ret = -EIDRM;
530 		break;
531 
532 	case FFS_NO_SETUP:
533 		n = len / sizeof(struct usb_functionfs_event);
534 		if (unlikely(!n)) {
535 			ret = -EINVAL;
536 			break;
537 		}
538 
539 		if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
540 			ret = -EAGAIN;
541 			break;
542 		}
543 
544 		if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
545 							ffs->ev.count)) {
546 			ret = -EINTR;
547 			break;
548 		}
549 
550 		return __ffs_ep0_read_events(ffs, buf,
551 					     min(n, (size_t)ffs->ev.count));
552 
553 	case FFS_SETUP_PENDING:
554 		if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
555 			spin_unlock_irq(&ffs->ev.waitq.lock);
556 			ret = __ffs_ep0_stall(ffs);
557 			goto done_mutex;
558 		}
559 
560 		len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
561 
562 		spin_unlock_irq(&ffs->ev.waitq.lock);
563 
564 		if (likely(len)) {
565 			data = kmalloc(len, GFP_KERNEL);
566 			if (unlikely(!data)) {
567 				ret = -ENOMEM;
568 				goto done_mutex;
569 			}
570 		}
571 
572 		spin_lock_irq(&ffs->ev.waitq.lock);
573 
574 		/* See ffs_ep0_write() */
575 		if (ffs_setup_state_clear_cancelled(ffs) ==
576 		    FFS_SETUP_CANCELLED) {
577 			ret = -EIDRM;
578 			break;
579 		}
580 
581 		/* unlocks spinlock */
582 		ret = __ffs_ep0_queue_wait(ffs, data, len);
583 		if (likely(ret > 0) && unlikely(copy_to_user(buf, data, len)))
584 			ret = -EFAULT;
585 		goto done_mutex;
586 
587 	default:
588 		ret = -EBADFD;
589 		break;
590 	}
591 
592 	spin_unlock_irq(&ffs->ev.waitq.lock);
593 done_mutex:
594 	mutex_unlock(&ffs->mutex);
595 	kfree(data);
596 	return ret;
597 }
598 
ffs_ep0_open(struct inode * inode,struct file * file)599 static int ffs_ep0_open(struct inode *inode, struct file *file)
600 {
601 	struct ffs_data *ffs = inode->i_private;
602 
603 	ENTER();
604 
605 	if (unlikely(ffs->state == FFS_CLOSING))
606 		return -EBUSY;
607 
608 	file->private_data = ffs;
609 	ffs_data_opened(ffs);
610 
611 	return 0;
612 }
613 
ffs_ep0_release(struct inode * inode,struct file * file)614 static int ffs_ep0_release(struct inode *inode, struct file *file)
615 {
616 	struct ffs_data *ffs = file->private_data;
617 
618 	ENTER();
619 
620 	ffs_data_closed(ffs);
621 
622 	return 0;
623 }
624 
ffs_ep0_ioctl(struct file * file,unsigned code,unsigned long value)625 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
626 {
627 	struct ffs_data *ffs = file->private_data;
628 	struct usb_gadget *gadget = ffs->gadget;
629 	long ret;
630 
631 	ENTER();
632 
633 	if (code == FUNCTIONFS_INTERFACE_REVMAP) {
634 		struct ffs_function *func = ffs->func;
635 		ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
636 	} else if (gadget && gadget->ops->ioctl) {
637 		ret = gadget->ops->ioctl(gadget, code, value);
638 	} else {
639 		ret = -ENOTTY;
640 	}
641 
642 	return ret;
643 }
644 
ffs_ep0_poll(struct file * file,poll_table * wait)645 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
646 {
647 	struct ffs_data *ffs = file->private_data;
648 	unsigned int mask = POLLWRNORM;
649 	int ret;
650 
651 	poll_wait(file, &ffs->ev.waitq, wait);
652 
653 	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
654 	if (unlikely(ret < 0))
655 		return mask;
656 
657 	switch (ffs->state) {
658 	case FFS_READ_DESCRIPTORS:
659 	case FFS_READ_STRINGS:
660 		mask |= POLLOUT;
661 		break;
662 
663 	case FFS_ACTIVE:
664 		switch (ffs->setup_state) {
665 		case FFS_NO_SETUP:
666 			if (ffs->ev.count)
667 				mask |= POLLIN;
668 			break;
669 
670 		case FFS_SETUP_PENDING:
671 		case FFS_SETUP_CANCELLED:
672 			mask |= (POLLIN | POLLOUT);
673 			break;
674 		}
675 	case FFS_CLOSING:
676 		break;
677 	case FFS_DEACTIVATED:
678 		break;
679 	}
680 
681 	mutex_unlock(&ffs->mutex);
682 
683 	return mask;
684 }
685 
686 static const struct file_operations ffs_ep0_operations = {
687 	.llseek =	no_llseek,
688 
689 	.open =		ffs_ep0_open,
690 	.write =	ffs_ep0_write,
691 	.read =		ffs_ep0_read,
692 	.release =	ffs_ep0_release,
693 	.unlocked_ioctl =	ffs_ep0_ioctl,
694 	.poll =		ffs_ep0_poll,
695 };
696 
697 
698 /* "Normal" endpoints operations ********************************************/
699 
ffs_epfile_io_complete(struct usb_ep * _ep,struct usb_request * req)700 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
701 {
702 	ENTER();
703 	if (likely(req->context)) {
704 		struct ffs_ep *ep = _ep->driver_data;
705 		ep->status = req->status ? req->status : req->actual;
706 		complete(req->context);
707 	}
708 }
709 
ffs_copy_to_iter(void * data,int data_len,struct iov_iter * iter)710 static ssize_t ffs_copy_to_iter(void *data, int data_len, struct iov_iter *iter)
711 {
712 	ssize_t ret = copy_to_iter(data, data_len, iter);
713 	if (likely(ret == data_len))
714 		return ret;
715 
716 	if (unlikely(iov_iter_count(iter)))
717 		return -EFAULT;
718 
719 	/*
720 	 * Dear user space developer!
721 	 *
722 	 * TL;DR: To stop getting below error message in your kernel log, change
723 	 * user space code using functionfs to align read buffers to a max
724 	 * packet size.
725 	 *
726 	 * Some UDCs (e.g. dwc3) require request sizes to be a multiple of a max
727 	 * packet size.  When unaligned buffer is passed to functionfs, it
728 	 * internally uses a larger, aligned buffer so that such UDCs are happy.
729 	 *
730 	 * Unfortunately, this means that host may send more data than was
731 	 * requested in read(2) system call.  f_fs doesn’t know what to do with
732 	 * that excess data so it simply drops it.
733 	 *
734 	 * Was the buffer aligned in the first place, no such problem would
735 	 * happen.
736 	 *
737 	 * Data may be dropped only in AIO reads.  Synchronous reads are handled
738 	 * by splitting a request into multiple parts.  This splitting may still
739 	 * be a problem though so it’s likely best to align the buffer
740 	 * regardless of it being AIO or not..
741 	 *
742 	 * This only affects OUT endpoints, i.e. reading data with a read(2),
743 	 * aio_read(2) etc. system calls.  Writing data to an IN endpoint is not
744 	 * affected.
745 	 */
746 	pr_err("functionfs read size %d > requested size %zd, dropping excess data. "
747 	       "Align read buffer size to max packet size to avoid the problem.\n",
748 	       data_len, ret);
749 
750 	return ret;
751 }
752 
ffs_user_copy_worker(struct work_struct * work)753 static void ffs_user_copy_worker(struct work_struct *work)
754 {
755 	struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
756 						   work);
757 	int ret = io_data->req->status ? io_data->req->status :
758 					 io_data->req->actual;
759 	bool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;
760 
761 	if (io_data->read && ret > 0) {
762 		mm_segment_t oldfs = get_fs();
763 
764 		set_fs(USER_DS);
765 		use_mm(io_data->mm);
766 		ret = ffs_copy_to_iter(io_data->buf, ret, &io_data->data);
767 		unuse_mm(io_data->mm);
768 		set_fs(oldfs);
769 	}
770 
771 	io_data->kiocb->ki_complete(io_data->kiocb, ret, ret);
772 
773 	if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd)
774 		eventfd_signal(io_data->ffs->ffs_eventfd, 1);
775 
776 	usb_ep_free_request(io_data->ep, io_data->req);
777 
778 	if (io_data->read)
779 		kfree(io_data->to_free);
780 	kfree(io_data->buf);
781 	kfree(io_data);
782 }
783 
ffs_epfile_async_io_complete(struct usb_ep * _ep,struct usb_request * req)784 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
785 					 struct usb_request *req)
786 {
787 	struct ffs_io_data *io_data = req->context;
788 	struct ffs_data *ffs = io_data->ffs;
789 
790 	ENTER();
791 
792 	INIT_WORK(&io_data->work, ffs_user_copy_worker);
793 	queue_work(ffs->io_completion_wq, &io_data->work);
794 }
795 
__ffs_epfile_read_buffer_free(struct ffs_epfile * epfile)796 static void __ffs_epfile_read_buffer_free(struct ffs_epfile *epfile)
797 {
798 	/*
799 	 * See comment in struct ffs_epfile for full read_buffer pointer
800 	 * synchronisation story.
801 	 */
802 	struct ffs_buffer *buf = xchg(&epfile->read_buffer, READ_BUFFER_DROP);
803 	if (buf && buf != READ_BUFFER_DROP)
804 		kfree(buf);
805 }
806 
807 /* Assumes epfile->mutex is held. */
__ffs_epfile_read_buffered(struct ffs_epfile * epfile,struct iov_iter * iter)808 static ssize_t __ffs_epfile_read_buffered(struct ffs_epfile *epfile,
809 					  struct iov_iter *iter)
810 {
811 	/*
812 	 * Null out epfile->read_buffer so ffs_func_eps_disable does not free
813 	 * the buffer while we are using it.  See comment in struct ffs_epfile
814 	 * for full read_buffer pointer synchronisation story.
815 	 */
816 	struct ffs_buffer *buf = xchg(&epfile->read_buffer, NULL);
817 	ssize_t ret;
818 	if (!buf || buf == READ_BUFFER_DROP)
819 		return 0;
820 
821 	ret = copy_to_iter(buf->data, buf->length, iter);
822 	if (buf->length == ret) {
823 		kfree(buf);
824 		return ret;
825 	}
826 
827 	if (unlikely(iov_iter_count(iter))) {
828 		ret = -EFAULT;
829 	} else {
830 		buf->length -= ret;
831 		buf->data += ret;
832 	}
833 
834 	if (cmpxchg(&epfile->read_buffer, NULL, buf))
835 		kfree(buf);
836 
837 	return ret;
838 }
839 
840 /* Assumes epfile->mutex is held. */
__ffs_epfile_read_data(struct ffs_epfile * epfile,void * data,int data_len,struct iov_iter * iter)841 static ssize_t __ffs_epfile_read_data(struct ffs_epfile *epfile,
842 				      void *data, int data_len,
843 				      struct iov_iter *iter)
844 {
845 	struct ffs_buffer *buf;
846 
847 	ssize_t ret = copy_to_iter(data, data_len, iter);
848 	if (likely(data_len == ret))
849 		return ret;
850 
851 	if (unlikely(iov_iter_count(iter)))
852 		return -EFAULT;
853 
854 	/* See ffs_copy_to_iter for more context. */
855 	pr_warn("functionfs read size %d > requested size %zd, splitting request into multiple reads.",
856 		data_len, ret);
857 
858 	data_len -= ret;
859 	buf = kmalloc(sizeof(*buf) + data_len, GFP_KERNEL);
860 	if (!buf)
861 		return -ENOMEM;
862 	buf->length = data_len;
863 	buf->data = buf->storage;
864 	memcpy(buf->storage, data + ret, data_len);
865 
866 	/*
867 	 * At this point read_buffer is NULL or READ_BUFFER_DROP (if
868 	 * ffs_func_eps_disable has been called in the meanwhile).  See comment
869 	 * in struct ffs_epfile for full read_buffer pointer synchronisation
870 	 * story.
871 	 */
872 	if (unlikely(cmpxchg(&epfile->read_buffer, NULL, buf)))
873 		kfree(buf);
874 
875 	return ret;
876 }
877 
ffs_epfile_io(struct file * file,struct ffs_io_data * io_data)878 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
879 {
880 	struct ffs_epfile *epfile = file->private_data;
881 	struct usb_request *req;
882 	struct ffs_ep *ep;
883 	char *data = NULL;
884 	ssize_t ret, data_len = -EINVAL;
885 	int halt;
886 
887 	/* Are we still active? */
888 	if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
889 		return -ENODEV;
890 
891 	/* Wait for endpoint to be enabled */
892 	ep = epfile->ep;
893 	if (!ep) {
894 		if (file->f_flags & O_NONBLOCK)
895 			return -EAGAIN;
896 
897 		ret = wait_event_interruptible(
898 				epfile->ffs->wait, (ep = epfile->ep));
899 		if (ret)
900 			return -EINTR;
901 	}
902 
903 	/* Do we halt? */
904 	halt = (!io_data->read == !epfile->in);
905 	if (halt && epfile->isoc)
906 		return -EINVAL;
907 
908 	/* We will be using request and read_buffer */
909 	ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
910 	if (unlikely(ret))
911 		goto error;
912 
913 	/* Allocate & copy */
914 	if (!halt) {
915 		struct usb_gadget *gadget;
916 
917 		/*
918 		 * Do we have buffered data from previous partial read?  Check
919 		 * that for synchronous case only because we do not have
920 		 * facility to ‘wake up’ a pending asynchronous read and push
921 		 * buffered data to it which we would need to make things behave
922 		 * consistently.
923 		 */
924 		if (!io_data->aio && io_data->read) {
925 			ret = __ffs_epfile_read_buffered(epfile, &io_data->data);
926 			if (ret)
927 				goto error_mutex;
928 		}
929 
930 		/*
931 		 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
932 		 * before the waiting completes, so do not assign to 'gadget'
933 		 * earlier
934 		 */
935 		gadget = epfile->ffs->gadget;
936 
937 		spin_lock_irq(&epfile->ffs->eps_lock);
938 		/* In the meantime, endpoint got disabled or changed. */
939 		if (epfile->ep != ep) {
940 			ret = -ESHUTDOWN;
941 			goto error_lock;
942 		}
943 		data_len = iov_iter_count(&io_data->data);
944 		/*
945 		 * Controller may require buffer size to be aligned to
946 		 * maxpacketsize of an out endpoint.
947 		 */
948 		if (io_data->read)
949 			data_len = usb_ep_align_maybe(gadget, ep->ep, data_len);
950 		spin_unlock_irq(&epfile->ffs->eps_lock);
951 
952 		data = kmalloc(data_len, GFP_KERNEL);
953 		if (unlikely(!data)) {
954 			ret = -ENOMEM;
955 			goto error_mutex;
956 		}
957 		if (!io_data->read &&
958 		    !copy_from_iter_full(data, data_len, &io_data->data)) {
959 			ret = -EFAULT;
960 			goto error_mutex;
961 		}
962 	}
963 
964 	spin_lock_irq(&epfile->ffs->eps_lock);
965 
966 	if (epfile->ep != ep) {
967 		/* In the meantime, endpoint got disabled or changed. */
968 		ret = -ESHUTDOWN;
969 	} else if (halt) {
970 		ret = usb_ep_set_halt(ep->ep);
971 		if (!ret)
972 			ret = -EBADMSG;
973 	} else if (unlikely(data_len == -EINVAL)) {
974 		/*
975 		 * Sanity Check: even though data_len can't be used
976 		 * uninitialized at the time I write this comment, some
977 		 * compilers complain about this situation.
978 		 * In order to keep the code clean from warnings, data_len is
979 		 * being initialized to -EINVAL during its declaration, which
980 		 * means we can't rely on compiler anymore to warn no future
981 		 * changes won't result in data_len being used uninitialized.
982 		 * For such reason, we're adding this redundant sanity check
983 		 * here.
984 		 */
985 		WARN(1, "%s: data_len == -EINVAL\n", __func__);
986 		ret = -EINVAL;
987 	} else if (!io_data->aio) {
988 		DECLARE_COMPLETION_ONSTACK(done);
989 		bool interrupted = false;
990 
991 		req = ep->req;
992 		req->buf      = data;
993 		req->length   = data_len;
994 
995 		req->context  = &done;
996 		req->complete = ffs_epfile_io_complete;
997 
998 		ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
999 		if (unlikely(ret < 0))
1000 			goto error_lock;
1001 
1002 		spin_unlock_irq(&epfile->ffs->eps_lock);
1003 
1004 		if (unlikely(wait_for_completion_interruptible(&done))) {
1005 			/*
1006 			 * To avoid race condition with ffs_epfile_io_complete,
1007 			 * dequeue the request first then check
1008 			 * status. usb_ep_dequeue API should guarantee no race
1009 			 * condition with req->complete callback.
1010 			 */
1011 			usb_ep_dequeue(ep->ep, req);
1012 			wait_for_completion(&done);
1013 			interrupted = ep->status < 0;
1014 		}
1015 
1016 		if (interrupted)
1017 			ret = -EINTR;
1018 		else if (io_data->read && ep->status > 0)
1019 			ret = __ffs_epfile_read_data(epfile, data, ep->status,
1020 						     &io_data->data);
1021 		else
1022 			ret = ep->status;
1023 		goto error_mutex;
1024 	} else if (!(req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC))) {
1025 		ret = -ENOMEM;
1026 	} else {
1027 		req->buf      = data;
1028 		req->length   = data_len;
1029 
1030 		io_data->buf = data;
1031 		io_data->ep = ep->ep;
1032 		io_data->req = req;
1033 		io_data->ffs = epfile->ffs;
1034 
1035 		req->context  = io_data;
1036 		req->complete = ffs_epfile_async_io_complete;
1037 
1038 		ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
1039 		if (unlikely(ret)) {
1040 			usb_ep_free_request(ep->ep, req);
1041 			goto error_lock;
1042 		}
1043 
1044 		ret = -EIOCBQUEUED;
1045 		/*
1046 		 * Do not kfree the buffer in this function.  It will be freed
1047 		 * by ffs_user_copy_worker.
1048 		 */
1049 		data = NULL;
1050 	}
1051 
1052 error_lock:
1053 	spin_unlock_irq(&epfile->ffs->eps_lock);
1054 error_mutex:
1055 	mutex_unlock(&epfile->mutex);
1056 error:
1057 	kfree(data);
1058 	return ret;
1059 }
1060 
1061 static int
ffs_epfile_open(struct inode * inode,struct file * file)1062 ffs_epfile_open(struct inode *inode, struct file *file)
1063 {
1064 	struct ffs_epfile *epfile = inode->i_private;
1065 
1066 	ENTER();
1067 
1068 	if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1069 		return -ENODEV;
1070 
1071 	file->private_data = epfile;
1072 	ffs_data_opened(epfile->ffs);
1073 
1074 	return 0;
1075 }
1076 
ffs_aio_cancel(struct kiocb * kiocb)1077 static int ffs_aio_cancel(struct kiocb *kiocb)
1078 {
1079 	struct ffs_io_data *io_data = kiocb->private;
1080 	struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
1081 	unsigned long flags;
1082 	int value;
1083 
1084 	ENTER();
1085 
1086 	spin_lock_irqsave(&epfile->ffs->eps_lock, flags);
1087 
1088 	if (likely(io_data && io_data->ep && io_data->req))
1089 		value = usb_ep_dequeue(io_data->ep, io_data->req);
1090 	else
1091 		value = -EINVAL;
1092 
1093 	spin_unlock_irqrestore(&epfile->ffs->eps_lock, flags);
1094 
1095 	return value;
1096 }
1097 
ffs_epfile_write_iter(struct kiocb * kiocb,struct iov_iter * from)1098 static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
1099 {
1100 	struct ffs_io_data io_data, *p = &io_data;
1101 	ssize_t res;
1102 
1103 	ENTER();
1104 
1105 	if (!is_sync_kiocb(kiocb)) {
1106 		p = kzalloc(sizeof(io_data), GFP_KERNEL);
1107 		if (unlikely(!p))
1108 			return -ENOMEM;
1109 		p->aio = true;
1110 	} else {
1111 		memset(p, 0, sizeof(*p));
1112 		p->aio = false;
1113 	}
1114 
1115 	p->read = false;
1116 	p->kiocb = kiocb;
1117 	p->data = *from;
1118 	p->mm = current->mm;
1119 
1120 	kiocb->private = p;
1121 
1122 	if (p->aio)
1123 		kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1124 
1125 	res = ffs_epfile_io(kiocb->ki_filp, p);
1126 	if (res == -EIOCBQUEUED)
1127 		return res;
1128 	if (p->aio)
1129 		kfree(p);
1130 	else
1131 		*from = p->data;
1132 	return res;
1133 }
1134 
ffs_epfile_read_iter(struct kiocb * kiocb,struct iov_iter * to)1135 static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
1136 {
1137 	struct ffs_io_data io_data, *p = &io_data;
1138 	ssize_t res;
1139 
1140 	ENTER();
1141 
1142 	if (!is_sync_kiocb(kiocb)) {
1143 		p = kzalloc(sizeof(io_data), GFP_KERNEL);
1144 		if (unlikely(!p))
1145 			return -ENOMEM;
1146 		p->aio = true;
1147 	} else {
1148 		memset(p, 0, sizeof(*p));
1149 		p->aio = false;
1150 	}
1151 
1152 	p->read = true;
1153 	p->kiocb = kiocb;
1154 	if (p->aio) {
1155 		p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
1156 		if (!p->to_free) {
1157 			kfree(p);
1158 			return -ENOMEM;
1159 		}
1160 	} else {
1161 		p->data = *to;
1162 		p->to_free = NULL;
1163 	}
1164 	p->mm = current->mm;
1165 
1166 	kiocb->private = p;
1167 
1168 	if (p->aio)
1169 		kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1170 
1171 	res = ffs_epfile_io(kiocb->ki_filp, p);
1172 	if (res == -EIOCBQUEUED)
1173 		return res;
1174 
1175 	if (p->aio) {
1176 		kfree(p->to_free);
1177 		kfree(p);
1178 	} else {
1179 		*to = p->data;
1180 	}
1181 	return res;
1182 }
1183 
1184 static int
ffs_epfile_release(struct inode * inode,struct file * file)1185 ffs_epfile_release(struct inode *inode, struct file *file)
1186 {
1187 	struct ffs_epfile *epfile = inode->i_private;
1188 
1189 	ENTER();
1190 
1191 	__ffs_epfile_read_buffer_free(epfile);
1192 	ffs_data_closed(epfile->ffs);
1193 
1194 	return 0;
1195 }
1196 
ffs_epfile_ioctl(struct file * file,unsigned code,unsigned long value)1197 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1198 			     unsigned long value)
1199 {
1200 	struct ffs_epfile *epfile = file->private_data;
1201 	struct ffs_ep *ep;
1202 	int ret;
1203 
1204 	ENTER();
1205 
1206 	if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1207 		return -ENODEV;
1208 
1209 	/* Wait for endpoint to be enabled */
1210 	ep = epfile->ep;
1211 	if (!ep) {
1212 		if (file->f_flags & O_NONBLOCK)
1213 			return -EAGAIN;
1214 
1215 		ret = wait_event_interruptible(
1216 				epfile->ffs->wait, (ep = epfile->ep));
1217 		if (ret)
1218 			return -EINTR;
1219 	}
1220 
1221 	spin_lock_irq(&epfile->ffs->eps_lock);
1222 
1223 	/* In the meantime, endpoint got disabled or changed. */
1224 	if (epfile->ep != ep) {
1225 		spin_unlock_irq(&epfile->ffs->eps_lock);
1226 		return -ESHUTDOWN;
1227 	}
1228 
1229 	switch (code) {
1230 	case FUNCTIONFS_FIFO_STATUS:
1231 		ret = usb_ep_fifo_status(epfile->ep->ep);
1232 		break;
1233 	case FUNCTIONFS_FIFO_FLUSH:
1234 		usb_ep_fifo_flush(epfile->ep->ep);
1235 		ret = 0;
1236 		break;
1237 	case FUNCTIONFS_CLEAR_HALT:
1238 		ret = usb_ep_clear_halt(epfile->ep->ep);
1239 		break;
1240 	case FUNCTIONFS_ENDPOINT_REVMAP:
1241 		ret = epfile->ep->num;
1242 		break;
1243 	case FUNCTIONFS_ENDPOINT_DESC:
1244 	{
1245 		int desc_idx;
1246 		struct usb_endpoint_descriptor *desc;
1247 
1248 		switch (epfile->ffs->gadget->speed) {
1249 		case USB_SPEED_SUPER:
1250 			desc_idx = 2;
1251 			break;
1252 		case USB_SPEED_HIGH:
1253 			desc_idx = 1;
1254 			break;
1255 		default:
1256 			desc_idx = 0;
1257 		}
1258 		desc = epfile->ep->descs[desc_idx];
1259 
1260 		spin_unlock_irq(&epfile->ffs->eps_lock);
1261 		ret = copy_to_user((void *)value, desc, desc->bLength);
1262 		if (ret)
1263 			ret = -EFAULT;
1264 		return ret;
1265 	}
1266 	default:
1267 		ret = -ENOTTY;
1268 	}
1269 	spin_unlock_irq(&epfile->ffs->eps_lock);
1270 
1271 	return ret;
1272 }
1273 
1274 static const struct file_operations ffs_epfile_operations = {
1275 	.llseek =	no_llseek,
1276 
1277 	.open =		ffs_epfile_open,
1278 	.write_iter =	ffs_epfile_write_iter,
1279 	.read_iter =	ffs_epfile_read_iter,
1280 	.release =	ffs_epfile_release,
1281 	.unlocked_ioctl =	ffs_epfile_ioctl,
1282 };
1283 
1284 
1285 /* File system and super block operations ***********************************/
1286 
1287 /*
1288  * Mounting the file system creates a controller file, used first for
1289  * function configuration then later for event monitoring.
1290  */
1291 
1292 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)1293 ffs_sb_make_inode(struct super_block *sb, void *data,
1294 		  const struct file_operations *fops,
1295 		  const struct inode_operations *iops,
1296 		  struct ffs_file_perms *perms)
1297 {
1298 	struct inode *inode;
1299 
1300 	ENTER();
1301 
1302 	inode = new_inode(sb);
1303 
1304 	if (likely(inode)) {
1305 		struct timespec ts = current_time(inode);
1306 
1307 		inode->i_ino	 = get_next_ino();
1308 		inode->i_mode    = perms->mode;
1309 		inode->i_uid     = perms->uid;
1310 		inode->i_gid     = perms->gid;
1311 		inode->i_atime   = ts;
1312 		inode->i_mtime   = ts;
1313 		inode->i_ctime   = ts;
1314 		inode->i_private = data;
1315 		if (fops)
1316 			inode->i_fop = fops;
1317 		if (iops)
1318 			inode->i_op  = iops;
1319 	}
1320 
1321 	return inode;
1322 }
1323 
1324 /* Create "regular" file */
ffs_sb_create_file(struct super_block * sb,const char * name,void * data,const struct file_operations * fops)1325 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1326 					const char *name, void *data,
1327 					const struct file_operations *fops)
1328 {
1329 	struct ffs_data	*ffs = sb->s_fs_info;
1330 	struct dentry	*dentry;
1331 	struct inode	*inode;
1332 
1333 	ENTER();
1334 
1335 	dentry = d_alloc_name(sb->s_root, name);
1336 	if (unlikely(!dentry))
1337 		return NULL;
1338 
1339 	inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1340 	if (unlikely(!inode)) {
1341 		dput(dentry);
1342 		return NULL;
1343 	}
1344 
1345 	d_add(dentry, inode);
1346 	return dentry;
1347 }
1348 
1349 /* Super block */
1350 static const struct super_operations ffs_sb_operations = {
1351 	.statfs =	simple_statfs,
1352 	.drop_inode =	generic_delete_inode,
1353 };
1354 
1355 struct ffs_sb_fill_data {
1356 	struct ffs_file_perms perms;
1357 	umode_t root_mode;
1358 	const char *dev_name;
1359 	bool no_disconnect;
1360 	struct ffs_data *ffs_data;
1361 };
1362 
ffs_sb_fill(struct super_block * sb,void * _data,int silent)1363 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1364 {
1365 	struct ffs_sb_fill_data *data = _data;
1366 	struct inode	*inode;
1367 	struct ffs_data	*ffs = data->ffs_data;
1368 
1369 	ENTER();
1370 
1371 	ffs->sb              = sb;
1372 	data->ffs_data       = NULL;
1373 	sb->s_fs_info        = ffs;
1374 	sb->s_blocksize      = PAGE_SIZE;
1375 	sb->s_blocksize_bits = PAGE_SHIFT;
1376 	sb->s_magic          = FUNCTIONFS_MAGIC;
1377 	sb->s_op             = &ffs_sb_operations;
1378 	sb->s_time_gran      = 1;
1379 
1380 	/* Root inode */
1381 	data->perms.mode = data->root_mode;
1382 	inode = ffs_sb_make_inode(sb, NULL,
1383 				  &simple_dir_operations,
1384 				  &simple_dir_inode_operations,
1385 				  &data->perms);
1386 	sb->s_root = d_make_root(inode);
1387 	if (unlikely(!sb->s_root))
1388 		return -ENOMEM;
1389 
1390 	/* EP0 file */
1391 	if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1392 					 &ffs_ep0_operations)))
1393 		return -ENOMEM;
1394 
1395 	return 0;
1396 }
1397 
ffs_fs_parse_opts(struct ffs_sb_fill_data * data,char * opts)1398 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1399 {
1400 	ENTER();
1401 
1402 	if (!opts || !*opts)
1403 		return 0;
1404 
1405 	for (;;) {
1406 		unsigned long value;
1407 		char *eq, *comma;
1408 
1409 		/* Option limit */
1410 		comma = strchr(opts, ',');
1411 		if (comma)
1412 			*comma = 0;
1413 
1414 		/* Value limit */
1415 		eq = strchr(opts, '=');
1416 		if (unlikely(!eq)) {
1417 			pr_err("'=' missing in %s\n", opts);
1418 			return -EINVAL;
1419 		}
1420 		*eq = 0;
1421 
1422 		/* Parse value */
1423 		if (kstrtoul(eq + 1, 0, &value)) {
1424 			pr_err("%s: invalid value: %s\n", opts, eq + 1);
1425 			return -EINVAL;
1426 		}
1427 
1428 		/* Interpret option */
1429 		switch (eq - opts) {
1430 		case 13:
1431 			if (!memcmp(opts, "no_disconnect", 13))
1432 				data->no_disconnect = !!value;
1433 			else
1434 				goto invalid;
1435 			break;
1436 		case 5:
1437 			if (!memcmp(opts, "rmode", 5))
1438 				data->root_mode  = (value & 0555) | S_IFDIR;
1439 			else if (!memcmp(opts, "fmode", 5))
1440 				data->perms.mode = (value & 0666) | S_IFREG;
1441 			else
1442 				goto invalid;
1443 			break;
1444 
1445 		case 4:
1446 			if (!memcmp(opts, "mode", 4)) {
1447 				data->root_mode  = (value & 0555) | S_IFDIR;
1448 				data->perms.mode = (value & 0666) | S_IFREG;
1449 			} else {
1450 				goto invalid;
1451 			}
1452 			break;
1453 
1454 		case 3:
1455 			if (!memcmp(opts, "uid", 3)) {
1456 				data->perms.uid = make_kuid(current_user_ns(), value);
1457 				if (!uid_valid(data->perms.uid)) {
1458 					pr_err("%s: unmapped value: %lu\n", opts, value);
1459 					return -EINVAL;
1460 				}
1461 			} else if (!memcmp(opts, "gid", 3)) {
1462 				data->perms.gid = make_kgid(current_user_ns(), value);
1463 				if (!gid_valid(data->perms.gid)) {
1464 					pr_err("%s: unmapped value: %lu\n", opts, value);
1465 					return -EINVAL;
1466 				}
1467 			} else {
1468 				goto invalid;
1469 			}
1470 			break;
1471 
1472 		default:
1473 invalid:
1474 			pr_err("%s: invalid option\n", opts);
1475 			return -EINVAL;
1476 		}
1477 
1478 		/* Next iteration */
1479 		if (!comma)
1480 			break;
1481 		opts = comma + 1;
1482 	}
1483 
1484 	return 0;
1485 }
1486 
1487 /* "mount -t functionfs dev_name /dev/function" ends up here */
1488 
1489 static struct dentry *
ffs_fs_mount(struct file_system_type * t,int flags,const char * dev_name,void * opts)1490 ffs_fs_mount(struct file_system_type *t, int flags,
1491 	      const char *dev_name, void *opts)
1492 {
1493 	struct ffs_sb_fill_data data = {
1494 		.perms = {
1495 			.mode = S_IFREG | 0600,
1496 			.uid = GLOBAL_ROOT_UID,
1497 			.gid = GLOBAL_ROOT_GID,
1498 		},
1499 		.root_mode = S_IFDIR | 0500,
1500 		.no_disconnect = false,
1501 	};
1502 	struct dentry *rv;
1503 	int ret;
1504 	void *ffs_dev;
1505 	struct ffs_data	*ffs;
1506 
1507 	ENTER();
1508 
1509 	ret = ffs_fs_parse_opts(&data, opts);
1510 	if (unlikely(ret < 0))
1511 		return ERR_PTR(ret);
1512 
1513 	ffs = ffs_data_new(dev_name);
1514 	if (unlikely(!ffs))
1515 		return ERR_PTR(-ENOMEM);
1516 	ffs->file_perms = data.perms;
1517 	ffs->no_disconnect = data.no_disconnect;
1518 
1519 	ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1520 	if (unlikely(!ffs->dev_name)) {
1521 		ffs_data_put(ffs);
1522 		return ERR_PTR(-ENOMEM);
1523 	}
1524 
1525 	ffs_dev = ffs_acquire_dev(dev_name);
1526 	if (IS_ERR(ffs_dev)) {
1527 		ffs_data_put(ffs);
1528 		return ERR_CAST(ffs_dev);
1529 	}
1530 	ffs->private_data = ffs_dev;
1531 	data.ffs_data = ffs;
1532 
1533 	rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1534 	if (IS_ERR(rv) && data.ffs_data) {
1535 		ffs_release_dev(data.ffs_data);
1536 		ffs_data_put(data.ffs_data);
1537 	}
1538 	return rv;
1539 }
1540 
1541 static void
ffs_fs_kill_sb(struct super_block * sb)1542 ffs_fs_kill_sb(struct super_block *sb)
1543 {
1544 	ENTER();
1545 
1546 	kill_litter_super(sb);
1547 	if (sb->s_fs_info) {
1548 		ffs_release_dev(sb->s_fs_info);
1549 		ffs_data_closed(sb->s_fs_info);
1550 	}
1551 }
1552 
1553 static struct file_system_type ffs_fs_type = {
1554 	.owner		= THIS_MODULE,
1555 	.name		= "functionfs",
1556 	.mount		= ffs_fs_mount,
1557 	.kill_sb	= ffs_fs_kill_sb,
1558 };
1559 MODULE_ALIAS_FS("functionfs");
1560 
1561 
1562 /* Driver's main init/cleanup functions *************************************/
1563 
functionfs_init(void)1564 static int functionfs_init(void)
1565 {
1566 	int ret;
1567 
1568 	ENTER();
1569 
1570 	ret = register_filesystem(&ffs_fs_type);
1571 	if (likely(!ret))
1572 		pr_info("file system registered\n");
1573 	else
1574 		pr_err("failed registering file system (%d)\n", ret);
1575 
1576 	return ret;
1577 }
1578 
functionfs_cleanup(void)1579 static void functionfs_cleanup(void)
1580 {
1581 	ENTER();
1582 
1583 	pr_info("unloading\n");
1584 	unregister_filesystem(&ffs_fs_type);
1585 }
1586 
1587 
1588 /* ffs_data and ffs_function construction and destruction code **************/
1589 
1590 static void ffs_data_clear(struct ffs_data *ffs);
1591 static void ffs_data_reset(struct ffs_data *ffs);
1592 
ffs_data_get(struct ffs_data * ffs)1593 static void ffs_data_get(struct ffs_data *ffs)
1594 {
1595 	ENTER();
1596 
1597 	refcount_inc(&ffs->ref);
1598 }
1599 
ffs_data_opened(struct ffs_data * ffs)1600 static void ffs_data_opened(struct ffs_data *ffs)
1601 {
1602 	ENTER();
1603 
1604 	refcount_inc(&ffs->ref);
1605 	if (atomic_add_return(1, &ffs->opened) == 1 &&
1606 			ffs->state == FFS_DEACTIVATED) {
1607 		ffs->state = FFS_CLOSING;
1608 		ffs_data_reset(ffs);
1609 	}
1610 }
1611 
ffs_data_put(struct ffs_data * ffs)1612 static void ffs_data_put(struct ffs_data *ffs)
1613 {
1614 	ENTER();
1615 
1616 	if (unlikely(refcount_dec_and_test(&ffs->ref))) {
1617 		pr_info("%s(): freeing\n", __func__);
1618 		ffs_data_clear(ffs);
1619 		BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1620 		       waitqueue_active(&ffs->ep0req_completion.wait) ||
1621 		       waitqueue_active(&ffs->wait));
1622 		destroy_workqueue(ffs->io_completion_wq);
1623 		kfree(ffs->dev_name);
1624 		kfree(ffs);
1625 	}
1626 }
1627 
ffs_data_closed(struct ffs_data * ffs)1628 static void ffs_data_closed(struct ffs_data *ffs)
1629 {
1630 	ENTER();
1631 
1632 	if (atomic_dec_and_test(&ffs->opened)) {
1633 		if (ffs->no_disconnect) {
1634 			ffs->state = FFS_DEACTIVATED;
1635 			if (ffs->epfiles) {
1636 				ffs_epfiles_destroy(ffs->epfiles,
1637 						   ffs->eps_count);
1638 				ffs->epfiles = NULL;
1639 			}
1640 			if (ffs->setup_state == FFS_SETUP_PENDING)
1641 				__ffs_ep0_stall(ffs);
1642 		} else {
1643 			ffs->state = FFS_CLOSING;
1644 			ffs_data_reset(ffs);
1645 		}
1646 	}
1647 	if (atomic_read(&ffs->opened) < 0) {
1648 		ffs->state = FFS_CLOSING;
1649 		ffs_data_reset(ffs);
1650 	}
1651 
1652 	ffs_data_put(ffs);
1653 }
1654 
ffs_data_new(const char * dev_name)1655 static struct ffs_data *ffs_data_new(const char *dev_name)
1656 {
1657 	struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1658 	if (unlikely(!ffs))
1659 		return NULL;
1660 
1661 	ENTER();
1662 
1663 	ffs->io_completion_wq = alloc_ordered_workqueue("%s", 0, dev_name);
1664 	if (!ffs->io_completion_wq) {
1665 		kfree(ffs);
1666 		return NULL;
1667 	}
1668 
1669 	refcount_set(&ffs->ref, 1);
1670 	atomic_set(&ffs->opened, 0);
1671 	ffs->state = FFS_READ_DESCRIPTORS;
1672 	mutex_init(&ffs->mutex);
1673 	spin_lock_init(&ffs->eps_lock);
1674 	init_waitqueue_head(&ffs->ev.waitq);
1675 	init_waitqueue_head(&ffs->wait);
1676 	init_completion(&ffs->ep0req_completion);
1677 
1678 	/* XXX REVISIT need to update it in some places, or do we? */
1679 	ffs->ev.can_stall = 1;
1680 
1681 	return ffs;
1682 }
1683 
ffs_data_clear(struct ffs_data * ffs)1684 static void ffs_data_clear(struct ffs_data *ffs)
1685 {
1686 	ENTER();
1687 
1688 	ffs_closed(ffs);
1689 
1690 	BUG_ON(ffs->gadget);
1691 
1692 	if (ffs->epfiles)
1693 		ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1694 
1695 	if (ffs->ffs_eventfd)
1696 		eventfd_ctx_put(ffs->ffs_eventfd);
1697 
1698 	kfree(ffs->raw_descs_data);
1699 	kfree(ffs->raw_strings);
1700 	kfree(ffs->stringtabs);
1701 }
1702 
ffs_data_reset(struct ffs_data * ffs)1703 static void ffs_data_reset(struct ffs_data *ffs)
1704 {
1705 	ENTER();
1706 
1707 	ffs_data_clear(ffs);
1708 
1709 	ffs->epfiles = NULL;
1710 	ffs->raw_descs_data = NULL;
1711 	ffs->raw_descs = NULL;
1712 	ffs->raw_strings = NULL;
1713 	ffs->stringtabs = NULL;
1714 
1715 	ffs->raw_descs_length = 0;
1716 	ffs->fs_descs_count = 0;
1717 	ffs->hs_descs_count = 0;
1718 	ffs->ss_descs_count = 0;
1719 
1720 	ffs->strings_count = 0;
1721 	ffs->interfaces_count = 0;
1722 	ffs->eps_count = 0;
1723 
1724 	ffs->ev.count = 0;
1725 
1726 	ffs->state = FFS_READ_DESCRIPTORS;
1727 	ffs->setup_state = FFS_NO_SETUP;
1728 	ffs->flags = 0;
1729 }
1730 
1731 
functionfs_bind(struct ffs_data * ffs,struct usb_composite_dev * cdev)1732 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1733 {
1734 	struct usb_gadget_strings **lang;
1735 	int first_id;
1736 
1737 	ENTER();
1738 
1739 	if (WARN_ON(ffs->state != FFS_ACTIVE
1740 		 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1741 		return -EBADFD;
1742 
1743 	first_id = usb_string_ids_n(cdev, ffs->strings_count);
1744 	if (unlikely(first_id < 0))
1745 		return first_id;
1746 
1747 	ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1748 	if (unlikely(!ffs->ep0req))
1749 		return -ENOMEM;
1750 	ffs->ep0req->complete = ffs_ep0_complete;
1751 	ffs->ep0req->context = ffs;
1752 
1753 	lang = ffs->stringtabs;
1754 	if (lang) {
1755 		for (; *lang; ++lang) {
1756 			struct usb_string *str = (*lang)->strings;
1757 			int id = first_id;
1758 			for (; str->s; ++id, ++str)
1759 				str->id = id;
1760 		}
1761 	}
1762 
1763 	ffs->gadget = cdev->gadget;
1764 	ffs_data_get(ffs);
1765 	return 0;
1766 }
1767 
functionfs_unbind(struct ffs_data * ffs)1768 static void functionfs_unbind(struct ffs_data *ffs)
1769 {
1770 	ENTER();
1771 
1772 	if (!WARN_ON(!ffs->gadget)) {
1773 		usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1774 		ffs->ep0req = NULL;
1775 		ffs->gadget = NULL;
1776 		clear_bit(FFS_FL_BOUND, &ffs->flags);
1777 		ffs_data_put(ffs);
1778 	}
1779 }
1780 
ffs_epfiles_create(struct ffs_data * ffs)1781 static int ffs_epfiles_create(struct ffs_data *ffs)
1782 {
1783 	struct ffs_epfile *epfile, *epfiles;
1784 	unsigned i, count;
1785 
1786 	ENTER();
1787 
1788 	count = ffs->eps_count;
1789 	epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1790 	if (!epfiles)
1791 		return -ENOMEM;
1792 
1793 	epfile = epfiles;
1794 	for (i = 1; i <= count; ++i, ++epfile) {
1795 		epfile->ffs = ffs;
1796 		mutex_init(&epfile->mutex);
1797 		if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1798 			sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1799 		else
1800 			sprintf(epfile->name, "ep%u", i);
1801 		epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
1802 						 epfile,
1803 						 &ffs_epfile_operations);
1804 		if (unlikely(!epfile->dentry)) {
1805 			ffs_epfiles_destroy(epfiles, i - 1);
1806 			return -ENOMEM;
1807 		}
1808 	}
1809 
1810 	ffs->epfiles = epfiles;
1811 	return 0;
1812 }
1813 
ffs_epfiles_destroy(struct ffs_epfile * epfiles,unsigned count)1814 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1815 {
1816 	struct ffs_epfile *epfile = epfiles;
1817 
1818 	ENTER();
1819 
1820 	for (; count; --count, ++epfile) {
1821 		BUG_ON(mutex_is_locked(&epfile->mutex));
1822 		if (epfile->dentry) {
1823 			d_delete(epfile->dentry);
1824 			dput(epfile->dentry);
1825 			epfile->dentry = NULL;
1826 		}
1827 	}
1828 
1829 	kfree(epfiles);
1830 }
1831 
ffs_func_eps_disable(struct ffs_function * func)1832 static void ffs_func_eps_disable(struct ffs_function *func)
1833 {
1834 	struct ffs_ep *ep         = func->eps;
1835 	struct ffs_epfile *epfile = func->ffs->epfiles;
1836 	unsigned count            = func->ffs->eps_count;
1837 	unsigned long flags;
1838 
1839 	spin_lock_irqsave(&func->ffs->eps_lock, flags);
1840 	while (count--) {
1841 		/* pending requests get nuked */
1842 		if (likely(ep->ep))
1843 			usb_ep_disable(ep->ep);
1844 		++ep;
1845 
1846 		if (epfile) {
1847 			epfile->ep = NULL;
1848 			__ffs_epfile_read_buffer_free(epfile);
1849 			++epfile;
1850 		}
1851 	}
1852 	spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1853 }
1854 
ffs_func_eps_enable(struct ffs_function * func)1855 static int ffs_func_eps_enable(struct ffs_function *func)
1856 {
1857 	struct ffs_data *ffs      = func->ffs;
1858 	struct ffs_ep *ep         = func->eps;
1859 	struct ffs_epfile *epfile = ffs->epfiles;
1860 	unsigned count            = ffs->eps_count;
1861 	unsigned long flags;
1862 	int ret = 0;
1863 
1864 	spin_lock_irqsave(&func->ffs->eps_lock, flags);
1865 	while(count--) {
1866 		ep->ep->driver_data = ep;
1867 
1868 		ret = config_ep_by_speed(func->gadget, &func->function, ep->ep);
1869 		if (ret) {
1870 			pr_err("%s: config_ep_by_speed(%s) returned %d\n",
1871 					__func__, ep->ep->name, ret);
1872 			break;
1873 		}
1874 
1875 		ret = usb_ep_enable(ep->ep);
1876 		if (likely(!ret)) {
1877 			epfile->ep = ep;
1878 			epfile->in = usb_endpoint_dir_in(ep->ep->desc);
1879 			epfile->isoc = usb_endpoint_xfer_isoc(ep->ep->desc);
1880 		} else {
1881 			break;
1882 		}
1883 
1884 		++ep;
1885 		++epfile;
1886 	}
1887 
1888 	wake_up_interruptible(&ffs->wait);
1889 	spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1890 
1891 	return ret;
1892 }
1893 
1894 
1895 /* Parsing and building descriptors and strings *****************************/
1896 
1897 /*
1898  * This validates if data pointed by data is a valid USB descriptor as
1899  * well as record how many interfaces, endpoints and strings are
1900  * required by given configuration.  Returns address after the
1901  * descriptor or NULL if data is invalid.
1902  */
1903 
1904 enum ffs_entity_type {
1905 	FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1906 };
1907 
1908 enum ffs_os_desc_type {
1909 	FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1910 };
1911 
1912 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1913 				   u8 *valuep,
1914 				   struct usb_descriptor_header *desc,
1915 				   void *priv);
1916 
1917 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1918 				    struct usb_os_desc_header *h, void *data,
1919 				    unsigned len, void *priv);
1920 
ffs_do_single_desc(char * data,unsigned len,ffs_entity_callback entity,void * priv)1921 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1922 					   ffs_entity_callback entity,
1923 					   void *priv)
1924 {
1925 	struct usb_descriptor_header *_ds = (void *)data;
1926 	u8 length;
1927 	int ret;
1928 
1929 	ENTER();
1930 
1931 	/* At least two bytes are required: length and type */
1932 	if (len < 2) {
1933 		pr_vdebug("descriptor too short\n");
1934 		return -EINVAL;
1935 	}
1936 
1937 	/* If we have at least as many bytes as the descriptor takes? */
1938 	length = _ds->bLength;
1939 	if (len < length) {
1940 		pr_vdebug("descriptor longer then available data\n");
1941 		return -EINVAL;
1942 	}
1943 
1944 #define __entity_check_INTERFACE(val)  1
1945 #define __entity_check_STRING(val)     (val)
1946 #define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
1947 #define __entity(type, val) do {					\
1948 		pr_vdebug("entity " #type "(%02x)\n", (val));		\
1949 		if (unlikely(!__entity_check_ ##type(val))) {		\
1950 			pr_vdebug("invalid entity's value\n");		\
1951 			return -EINVAL;					\
1952 		}							\
1953 		ret = entity(FFS_ ##type, &val, _ds, priv);		\
1954 		if (unlikely(ret < 0)) {				\
1955 			pr_debug("entity " #type "(%02x); ret = %d\n",	\
1956 				 (val), ret);				\
1957 			return ret;					\
1958 		}							\
1959 	} while (0)
1960 
1961 	/* Parse descriptor depending on type. */
1962 	switch (_ds->bDescriptorType) {
1963 	case USB_DT_DEVICE:
1964 	case USB_DT_CONFIG:
1965 	case USB_DT_STRING:
1966 	case USB_DT_DEVICE_QUALIFIER:
1967 		/* function can't have any of those */
1968 		pr_vdebug("descriptor reserved for gadget: %d\n",
1969 		      _ds->bDescriptorType);
1970 		return -EINVAL;
1971 
1972 	case USB_DT_INTERFACE: {
1973 		struct usb_interface_descriptor *ds = (void *)_ds;
1974 		pr_vdebug("interface descriptor\n");
1975 		if (length != sizeof *ds)
1976 			goto inv_length;
1977 
1978 		__entity(INTERFACE, ds->bInterfaceNumber);
1979 		if (ds->iInterface)
1980 			__entity(STRING, ds->iInterface);
1981 	}
1982 		break;
1983 
1984 	case USB_DT_ENDPOINT: {
1985 		struct usb_endpoint_descriptor *ds = (void *)_ds;
1986 		pr_vdebug("endpoint descriptor\n");
1987 		if (length != USB_DT_ENDPOINT_SIZE &&
1988 		    length != USB_DT_ENDPOINT_AUDIO_SIZE)
1989 			goto inv_length;
1990 		__entity(ENDPOINT, ds->bEndpointAddress);
1991 	}
1992 		break;
1993 
1994 	case HID_DT_HID:
1995 		pr_vdebug("hid descriptor\n");
1996 		if (length != sizeof(struct hid_descriptor))
1997 			goto inv_length;
1998 		break;
1999 
2000 	case USB_DT_OTG:
2001 		if (length != sizeof(struct usb_otg_descriptor))
2002 			goto inv_length;
2003 		break;
2004 
2005 	case USB_DT_INTERFACE_ASSOCIATION: {
2006 		struct usb_interface_assoc_descriptor *ds = (void *)_ds;
2007 		pr_vdebug("interface association descriptor\n");
2008 		if (length != sizeof *ds)
2009 			goto inv_length;
2010 		if (ds->iFunction)
2011 			__entity(STRING, ds->iFunction);
2012 	}
2013 		break;
2014 
2015 	case USB_DT_SS_ENDPOINT_COMP:
2016 		pr_vdebug("EP SS companion descriptor\n");
2017 		if (length != sizeof(struct usb_ss_ep_comp_descriptor))
2018 			goto inv_length;
2019 		break;
2020 
2021 	case USB_DT_OTHER_SPEED_CONFIG:
2022 	case USB_DT_INTERFACE_POWER:
2023 	case USB_DT_DEBUG:
2024 	case USB_DT_SECURITY:
2025 	case USB_DT_CS_RADIO_CONTROL:
2026 		/* TODO */
2027 		pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
2028 		return -EINVAL;
2029 
2030 	default:
2031 		/* We should never be here */
2032 		pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
2033 		return -EINVAL;
2034 
2035 inv_length:
2036 		pr_vdebug("invalid length: %d (descriptor %d)\n",
2037 			  _ds->bLength, _ds->bDescriptorType);
2038 		return -EINVAL;
2039 	}
2040 
2041 #undef __entity
2042 #undef __entity_check_DESCRIPTOR
2043 #undef __entity_check_INTERFACE
2044 #undef __entity_check_STRING
2045 #undef __entity_check_ENDPOINT
2046 
2047 	return length;
2048 }
2049 
ffs_do_descs(unsigned count,char * data,unsigned len,ffs_entity_callback entity,void * priv)2050 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
2051 				     ffs_entity_callback entity, void *priv)
2052 {
2053 	const unsigned _len = len;
2054 	unsigned long num = 0;
2055 
2056 	ENTER();
2057 
2058 	for (;;) {
2059 		int ret;
2060 
2061 		if (num == count)
2062 			data = NULL;
2063 
2064 		/* Record "descriptor" entity */
2065 		ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
2066 		if (unlikely(ret < 0)) {
2067 			pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
2068 				 num, ret);
2069 			return ret;
2070 		}
2071 
2072 		if (!data)
2073 			return _len - len;
2074 
2075 		ret = ffs_do_single_desc(data, len, entity, priv);
2076 		if (unlikely(ret < 0)) {
2077 			pr_debug("%s returns %d\n", __func__, ret);
2078 			return ret;
2079 		}
2080 
2081 		len -= ret;
2082 		data += ret;
2083 		++num;
2084 	}
2085 }
2086 
__ffs_data_do_entity(enum ffs_entity_type type,u8 * valuep,struct usb_descriptor_header * desc,void * priv)2087 static int __ffs_data_do_entity(enum ffs_entity_type type,
2088 				u8 *valuep, struct usb_descriptor_header *desc,
2089 				void *priv)
2090 {
2091 	struct ffs_desc_helper *helper = priv;
2092 	struct usb_endpoint_descriptor *d;
2093 
2094 	ENTER();
2095 
2096 	switch (type) {
2097 	case FFS_DESCRIPTOR:
2098 		break;
2099 
2100 	case FFS_INTERFACE:
2101 		/*
2102 		 * Interfaces are indexed from zero so if we
2103 		 * encountered interface "n" then there are at least
2104 		 * "n+1" interfaces.
2105 		 */
2106 		if (*valuep >= helper->interfaces_count)
2107 			helper->interfaces_count = *valuep + 1;
2108 		break;
2109 
2110 	case FFS_STRING:
2111 		/*
2112 		 * Strings are indexed from 1 (0 is reserved
2113 		 * for languages list)
2114 		 */
2115 		if (*valuep > helper->ffs->strings_count)
2116 			helper->ffs->strings_count = *valuep;
2117 		break;
2118 
2119 	case FFS_ENDPOINT:
2120 		d = (void *)desc;
2121 		helper->eps_count++;
2122 		if (helper->eps_count >= FFS_MAX_EPS_COUNT)
2123 			return -EINVAL;
2124 		/* Check if descriptors for any speed were already parsed */
2125 		if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
2126 			helper->ffs->eps_addrmap[helper->eps_count] =
2127 				d->bEndpointAddress;
2128 		else if (helper->ffs->eps_addrmap[helper->eps_count] !=
2129 				d->bEndpointAddress)
2130 			return -EINVAL;
2131 		break;
2132 	}
2133 
2134 	return 0;
2135 }
2136 
__ffs_do_os_desc_header(enum ffs_os_desc_type * next_type,struct usb_os_desc_header * desc)2137 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
2138 				   struct usb_os_desc_header *desc)
2139 {
2140 	u16 bcd_version = le16_to_cpu(desc->bcdVersion);
2141 	u16 w_index = le16_to_cpu(desc->wIndex);
2142 
2143 	if (bcd_version != 1) {
2144 		pr_vdebug("unsupported os descriptors version: %d",
2145 			  bcd_version);
2146 		return -EINVAL;
2147 	}
2148 	switch (w_index) {
2149 	case 0x4:
2150 		*next_type = FFS_OS_DESC_EXT_COMPAT;
2151 		break;
2152 	case 0x5:
2153 		*next_type = FFS_OS_DESC_EXT_PROP;
2154 		break;
2155 	default:
2156 		pr_vdebug("unsupported os descriptor type: %d", w_index);
2157 		return -EINVAL;
2158 	}
2159 
2160 	return sizeof(*desc);
2161 }
2162 
2163 /*
2164  * Process all extended compatibility/extended property descriptors
2165  * of a feature descriptor
2166  */
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)2167 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
2168 					      enum ffs_os_desc_type type,
2169 					      u16 feature_count,
2170 					      ffs_os_desc_callback entity,
2171 					      void *priv,
2172 					      struct usb_os_desc_header *h)
2173 {
2174 	int ret;
2175 	const unsigned _len = len;
2176 
2177 	ENTER();
2178 
2179 	/* loop over all ext compat/ext prop descriptors */
2180 	while (feature_count--) {
2181 		ret = entity(type, h, data, len, priv);
2182 		if (unlikely(ret < 0)) {
2183 			pr_debug("bad OS descriptor, type: %d\n", type);
2184 			return ret;
2185 		}
2186 		data += ret;
2187 		len -= ret;
2188 	}
2189 	return _len - len;
2190 }
2191 
2192 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
ffs_do_os_descs(unsigned count,char * data,unsigned len,ffs_os_desc_callback entity,void * priv)2193 static int __must_check ffs_do_os_descs(unsigned count,
2194 					char *data, unsigned len,
2195 					ffs_os_desc_callback entity, void *priv)
2196 {
2197 	const unsigned _len = len;
2198 	unsigned long num = 0;
2199 
2200 	ENTER();
2201 
2202 	for (num = 0; num < count; ++num) {
2203 		int ret;
2204 		enum ffs_os_desc_type type;
2205 		u16 feature_count;
2206 		struct usb_os_desc_header *desc = (void *)data;
2207 
2208 		if (len < sizeof(*desc))
2209 			return -EINVAL;
2210 
2211 		/*
2212 		 * Record "descriptor" entity.
2213 		 * Process dwLength, bcdVersion, wIndex, get b/wCount.
2214 		 * Move the data pointer to the beginning of extended
2215 		 * compatibilities proper or extended properties proper
2216 		 * portions of the data
2217 		 */
2218 		if (le32_to_cpu(desc->dwLength) > len)
2219 			return -EINVAL;
2220 
2221 		ret = __ffs_do_os_desc_header(&type, desc);
2222 		if (unlikely(ret < 0)) {
2223 			pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2224 				 num, ret);
2225 			return ret;
2226 		}
2227 		/*
2228 		 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2229 		 */
2230 		feature_count = le16_to_cpu(desc->wCount);
2231 		if (type == FFS_OS_DESC_EXT_COMPAT &&
2232 		    (feature_count > 255 || desc->Reserved))
2233 				return -EINVAL;
2234 		len -= ret;
2235 		data += ret;
2236 
2237 		/*
2238 		 * Process all function/property descriptors
2239 		 * of this Feature Descriptor
2240 		 */
2241 		ret = ffs_do_single_os_desc(data, len, type,
2242 					    feature_count, entity, priv, desc);
2243 		if (unlikely(ret < 0)) {
2244 			pr_debug("%s returns %d\n", __func__, ret);
2245 			return ret;
2246 		}
2247 
2248 		len -= ret;
2249 		data += ret;
2250 	}
2251 	return _len - len;
2252 }
2253 
2254 /**
2255  * Validate contents of the buffer from userspace related to OS descriptors.
2256  */
__ffs_data_do_os_desc(enum ffs_os_desc_type type,struct usb_os_desc_header * h,void * data,unsigned len,void * priv)2257 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2258 				 struct usb_os_desc_header *h, void *data,
2259 				 unsigned len, void *priv)
2260 {
2261 	struct ffs_data *ffs = priv;
2262 	u8 length;
2263 
2264 	ENTER();
2265 
2266 	switch (type) {
2267 	case FFS_OS_DESC_EXT_COMPAT: {
2268 		struct usb_ext_compat_desc *d = data;
2269 		int i;
2270 
2271 		if (len < sizeof(*d) ||
2272 		    d->bFirstInterfaceNumber >= ffs->interfaces_count)
2273 			return -EINVAL;
2274 		if (d->Reserved1 != 1) {
2275 			/*
2276 			 * According to the spec, Reserved1 must be set to 1
2277 			 * but older kernels incorrectly rejected non-zero
2278 			 * values.  We fix it here to avoid returning EINVAL
2279 			 * in response to values we used to accept.
2280 			 */
2281 			pr_debug("usb_ext_compat_desc::Reserved1 forced to 1\n");
2282 			d->Reserved1 = 1;
2283 		}
2284 		for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2285 			if (d->Reserved2[i])
2286 				return -EINVAL;
2287 
2288 		length = sizeof(struct usb_ext_compat_desc);
2289 	}
2290 		break;
2291 	case FFS_OS_DESC_EXT_PROP: {
2292 		struct usb_ext_prop_desc *d = data;
2293 		u32 type, pdl;
2294 		u16 pnl;
2295 
2296 		if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2297 			return -EINVAL;
2298 		length = le32_to_cpu(d->dwSize);
2299 		if (len < length)
2300 			return -EINVAL;
2301 		type = le32_to_cpu(d->dwPropertyDataType);
2302 		if (type < USB_EXT_PROP_UNICODE ||
2303 		    type > USB_EXT_PROP_UNICODE_MULTI) {
2304 			pr_vdebug("unsupported os descriptor property type: %d",
2305 				  type);
2306 			return -EINVAL;
2307 		}
2308 		pnl = le16_to_cpu(d->wPropertyNameLength);
2309 		if (length < 14 + pnl) {
2310 			pr_vdebug("invalid os descriptor length: %d pnl:%d (descriptor %d)\n",
2311 				  length, pnl, type);
2312 			return -EINVAL;
2313 		}
2314 		pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2315 		if (length != 14 + pnl + pdl) {
2316 			pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2317 				  length, pnl, pdl, type);
2318 			return -EINVAL;
2319 		}
2320 		++ffs->ms_os_descs_ext_prop_count;
2321 		/* property name reported to the host as "WCHAR"s */
2322 		ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2323 		ffs->ms_os_descs_ext_prop_data_len += pdl;
2324 	}
2325 		break;
2326 	default:
2327 		pr_vdebug("unknown descriptor: %d\n", type);
2328 		return -EINVAL;
2329 	}
2330 	return length;
2331 }
2332 
__ffs_data_got_descs(struct ffs_data * ffs,char * const _data,size_t len)2333 static int __ffs_data_got_descs(struct ffs_data *ffs,
2334 				char *const _data, size_t len)
2335 {
2336 	char *data = _data, *raw_descs;
2337 	unsigned os_descs_count = 0, counts[3], flags;
2338 	int ret = -EINVAL, i;
2339 	struct ffs_desc_helper helper;
2340 
2341 	ENTER();
2342 
2343 	if (get_unaligned_le32(data + 4) != len)
2344 		goto error;
2345 
2346 	switch (get_unaligned_le32(data)) {
2347 	case FUNCTIONFS_DESCRIPTORS_MAGIC:
2348 		flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2349 		data += 8;
2350 		len  -= 8;
2351 		break;
2352 	case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2353 		flags = get_unaligned_le32(data + 8);
2354 		ffs->user_flags = flags;
2355 		if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2356 			      FUNCTIONFS_HAS_HS_DESC |
2357 			      FUNCTIONFS_HAS_SS_DESC |
2358 			      FUNCTIONFS_HAS_MS_OS_DESC |
2359 			      FUNCTIONFS_VIRTUAL_ADDR |
2360 			      FUNCTIONFS_EVENTFD |
2361 			      FUNCTIONFS_ALL_CTRL_RECIP |
2362 			      FUNCTIONFS_CONFIG0_SETUP)) {
2363 			ret = -ENOSYS;
2364 			goto error;
2365 		}
2366 		data += 12;
2367 		len  -= 12;
2368 		break;
2369 	default:
2370 		goto error;
2371 	}
2372 
2373 	if (flags & FUNCTIONFS_EVENTFD) {
2374 		if (len < 4)
2375 			goto error;
2376 		ffs->ffs_eventfd =
2377 			eventfd_ctx_fdget((int)get_unaligned_le32(data));
2378 		if (IS_ERR(ffs->ffs_eventfd)) {
2379 			ret = PTR_ERR(ffs->ffs_eventfd);
2380 			ffs->ffs_eventfd = NULL;
2381 			goto error;
2382 		}
2383 		data += 4;
2384 		len  -= 4;
2385 	}
2386 
2387 	/* Read fs_count, hs_count and ss_count (if present) */
2388 	for (i = 0; i < 3; ++i) {
2389 		if (!(flags & (1 << i))) {
2390 			counts[i] = 0;
2391 		} else if (len < 4) {
2392 			goto error;
2393 		} else {
2394 			counts[i] = get_unaligned_le32(data);
2395 			data += 4;
2396 			len  -= 4;
2397 		}
2398 	}
2399 	if (flags & (1 << i)) {
2400 		if (len < 4) {
2401 			goto error;
2402 		}
2403 		os_descs_count = get_unaligned_le32(data);
2404 		data += 4;
2405 		len -= 4;
2406 	};
2407 
2408 	/* Read descriptors */
2409 	raw_descs = data;
2410 	helper.ffs = ffs;
2411 	for (i = 0; i < 3; ++i) {
2412 		if (!counts[i])
2413 			continue;
2414 		helper.interfaces_count = 0;
2415 		helper.eps_count = 0;
2416 		ret = ffs_do_descs(counts[i], data, len,
2417 				   __ffs_data_do_entity, &helper);
2418 		if (ret < 0)
2419 			goto error;
2420 		if (!ffs->eps_count && !ffs->interfaces_count) {
2421 			ffs->eps_count = helper.eps_count;
2422 			ffs->interfaces_count = helper.interfaces_count;
2423 		} else {
2424 			if (ffs->eps_count != helper.eps_count) {
2425 				ret = -EINVAL;
2426 				goto error;
2427 			}
2428 			if (ffs->interfaces_count != helper.interfaces_count) {
2429 				ret = -EINVAL;
2430 				goto error;
2431 			}
2432 		}
2433 		data += ret;
2434 		len  -= ret;
2435 	}
2436 	if (os_descs_count) {
2437 		ret = ffs_do_os_descs(os_descs_count, data, len,
2438 				      __ffs_data_do_os_desc, ffs);
2439 		if (ret < 0)
2440 			goto error;
2441 		data += ret;
2442 		len -= ret;
2443 	}
2444 
2445 	if (raw_descs == data || len) {
2446 		ret = -EINVAL;
2447 		goto error;
2448 	}
2449 
2450 	ffs->raw_descs_data	= _data;
2451 	ffs->raw_descs		= raw_descs;
2452 	ffs->raw_descs_length	= data - raw_descs;
2453 	ffs->fs_descs_count	= counts[0];
2454 	ffs->hs_descs_count	= counts[1];
2455 	ffs->ss_descs_count	= counts[2];
2456 	ffs->ms_os_descs_count	= os_descs_count;
2457 
2458 	return 0;
2459 
2460 error:
2461 	kfree(_data);
2462 	return ret;
2463 }
2464 
__ffs_data_got_strings(struct ffs_data * ffs,char * const _data,size_t len)2465 static int __ffs_data_got_strings(struct ffs_data *ffs,
2466 				  char *const _data, size_t len)
2467 {
2468 	u32 str_count, needed_count, lang_count;
2469 	struct usb_gadget_strings **stringtabs, *t;
2470 	const char *data = _data;
2471 	struct usb_string *s;
2472 
2473 	ENTER();
2474 
2475 	if (unlikely(len < 16 ||
2476 		     get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2477 		     get_unaligned_le32(data + 4) != len))
2478 		goto error;
2479 	str_count  = get_unaligned_le32(data + 8);
2480 	lang_count = get_unaligned_le32(data + 12);
2481 
2482 	/* if one is zero the other must be zero */
2483 	if (unlikely(!str_count != !lang_count))
2484 		goto error;
2485 
2486 	/* Do we have at least as many strings as descriptors need? */
2487 	needed_count = ffs->strings_count;
2488 	if (unlikely(str_count < needed_count))
2489 		goto error;
2490 
2491 	/*
2492 	 * If we don't need any strings just return and free all
2493 	 * memory.
2494 	 */
2495 	if (!needed_count) {
2496 		kfree(_data);
2497 		return 0;
2498 	}
2499 
2500 	/* Allocate everything in one chunk so there's less maintenance. */
2501 	{
2502 		unsigned i = 0;
2503 		vla_group(d);
2504 		vla_item(d, struct usb_gadget_strings *, stringtabs,
2505 			lang_count + 1);
2506 		vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2507 		vla_item(d, struct usb_string, strings,
2508 			lang_count*(needed_count+1));
2509 
2510 		char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2511 
2512 		if (unlikely(!vlabuf)) {
2513 			kfree(_data);
2514 			return -ENOMEM;
2515 		}
2516 
2517 		/* Initialize the VLA pointers */
2518 		stringtabs = vla_ptr(vlabuf, d, stringtabs);
2519 		t = vla_ptr(vlabuf, d, stringtab);
2520 		i = lang_count;
2521 		do {
2522 			*stringtabs++ = t++;
2523 		} while (--i);
2524 		*stringtabs = NULL;
2525 
2526 		/* stringtabs = vlabuf = d_stringtabs for later kfree */
2527 		stringtabs = vla_ptr(vlabuf, d, stringtabs);
2528 		t = vla_ptr(vlabuf, d, stringtab);
2529 		s = vla_ptr(vlabuf, d, strings);
2530 	}
2531 
2532 	/* For each language */
2533 	data += 16;
2534 	len -= 16;
2535 
2536 	do { /* lang_count > 0 so we can use do-while */
2537 		unsigned needed = needed_count;
2538 
2539 		if (unlikely(len < 3))
2540 			goto error_free;
2541 		t->language = get_unaligned_le16(data);
2542 		t->strings  = s;
2543 		++t;
2544 
2545 		data += 2;
2546 		len -= 2;
2547 
2548 		/* For each string */
2549 		do { /* str_count > 0 so we can use do-while */
2550 			size_t length = strnlen(data, len);
2551 
2552 			if (unlikely(length == len))
2553 				goto error_free;
2554 
2555 			/*
2556 			 * User may provide more strings then we need,
2557 			 * if that's the case we simply ignore the
2558 			 * rest
2559 			 */
2560 			if (likely(needed)) {
2561 				/*
2562 				 * s->id will be set while adding
2563 				 * function to configuration so for
2564 				 * now just leave garbage here.
2565 				 */
2566 				s->s = data;
2567 				--needed;
2568 				++s;
2569 			}
2570 
2571 			data += length + 1;
2572 			len -= length + 1;
2573 		} while (--str_count);
2574 
2575 		s->id = 0;   /* terminator */
2576 		s->s = NULL;
2577 		++s;
2578 
2579 	} while (--lang_count);
2580 
2581 	/* Some garbage left? */
2582 	if (unlikely(len))
2583 		goto error_free;
2584 
2585 	/* Done! */
2586 	ffs->stringtabs = stringtabs;
2587 	ffs->raw_strings = _data;
2588 
2589 	return 0;
2590 
2591 error_free:
2592 	kfree(stringtabs);
2593 error:
2594 	kfree(_data);
2595 	return -EINVAL;
2596 }
2597 
2598 
2599 /* Events handling and management *******************************************/
2600 
__ffs_event_add(struct ffs_data * ffs,enum usb_functionfs_event_type type)2601 static void __ffs_event_add(struct ffs_data *ffs,
2602 			    enum usb_functionfs_event_type type)
2603 {
2604 	enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2605 	int neg = 0;
2606 
2607 	/*
2608 	 * Abort any unhandled setup
2609 	 *
2610 	 * We do not need to worry about some cmpxchg() changing value
2611 	 * of ffs->setup_state without holding the lock because when
2612 	 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2613 	 * the source does nothing.
2614 	 */
2615 	if (ffs->setup_state == FFS_SETUP_PENDING)
2616 		ffs->setup_state = FFS_SETUP_CANCELLED;
2617 
2618 	/*
2619 	 * Logic of this function guarantees that there are at most four pending
2620 	 * evens on ffs->ev.types queue.  This is important because the queue
2621 	 * has space for four elements only and __ffs_ep0_read_events function
2622 	 * depends on that limit as well.  If more event types are added, those
2623 	 * limits have to be revisited or guaranteed to still hold.
2624 	 */
2625 	switch (type) {
2626 	case FUNCTIONFS_RESUME:
2627 		rem_type2 = FUNCTIONFS_SUSPEND;
2628 		/* FALL THROUGH */
2629 	case FUNCTIONFS_SUSPEND:
2630 	case FUNCTIONFS_SETUP:
2631 		rem_type1 = type;
2632 		/* Discard all similar events */
2633 		break;
2634 
2635 	case FUNCTIONFS_BIND:
2636 	case FUNCTIONFS_UNBIND:
2637 	case FUNCTIONFS_DISABLE:
2638 	case FUNCTIONFS_ENABLE:
2639 		/* Discard everything other then power management. */
2640 		rem_type1 = FUNCTIONFS_SUSPEND;
2641 		rem_type2 = FUNCTIONFS_RESUME;
2642 		neg = 1;
2643 		break;
2644 
2645 	default:
2646 		WARN(1, "%d: unknown event, this should not happen\n", type);
2647 		return;
2648 	}
2649 
2650 	{
2651 		u8 *ev  = ffs->ev.types, *out = ev;
2652 		unsigned n = ffs->ev.count;
2653 		for (; n; --n, ++ev)
2654 			if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2655 				*out++ = *ev;
2656 			else
2657 				pr_vdebug("purging event %d\n", *ev);
2658 		ffs->ev.count = out - ffs->ev.types;
2659 	}
2660 
2661 	pr_vdebug("adding event %d\n", type);
2662 	ffs->ev.types[ffs->ev.count++] = type;
2663 	wake_up_locked(&ffs->ev.waitq);
2664 	if (ffs->ffs_eventfd)
2665 		eventfd_signal(ffs->ffs_eventfd, 1);
2666 }
2667 
ffs_event_add(struct ffs_data * ffs,enum usb_functionfs_event_type type)2668 static void ffs_event_add(struct ffs_data *ffs,
2669 			  enum usb_functionfs_event_type type)
2670 {
2671 	unsigned long flags;
2672 	spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2673 	__ffs_event_add(ffs, type);
2674 	spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2675 }
2676 
2677 /* Bind/unbind USB function hooks *******************************************/
2678 
ffs_ep_addr2idx(struct ffs_data * ffs,u8 endpoint_address)2679 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2680 {
2681 	int i;
2682 
2683 	for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2684 		if (ffs->eps_addrmap[i] == endpoint_address)
2685 			return i;
2686 	return -ENOENT;
2687 }
2688 
__ffs_func_bind_do_descs(enum ffs_entity_type type,u8 * valuep,struct usb_descriptor_header * desc,void * priv)2689 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2690 				    struct usb_descriptor_header *desc,
2691 				    void *priv)
2692 {
2693 	struct usb_endpoint_descriptor *ds = (void *)desc;
2694 	struct ffs_function *func = priv;
2695 	struct ffs_ep *ffs_ep;
2696 	unsigned ep_desc_id;
2697 	int idx;
2698 	static const char *speed_names[] = { "full", "high", "super" };
2699 
2700 	if (type != FFS_DESCRIPTOR)
2701 		return 0;
2702 
2703 	/*
2704 	 * If ss_descriptors is not NULL, we are reading super speed
2705 	 * descriptors; if hs_descriptors is not NULL, we are reading high
2706 	 * speed descriptors; otherwise, we are reading full speed
2707 	 * descriptors.
2708 	 */
2709 	if (func->function.ss_descriptors) {
2710 		ep_desc_id = 2;
2711 		func->function.ss_descriptors[(long)valuep] = desc;
2712 	} else if (func->function.hs_descriptors) {
2713 		ep_desc_id = 1;
2714 		func->function.hs_descriptors[(long)valuep] = desc;
2715 	} else {
2716 		ep_desc_id = 0;
2717 		func->function.fs_descriptors[(long)valuep]    = desc;
2718 	}
2719 
2720 	if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2721 		return 0;
2722 
2723 	idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2724 	if (idx < 0)
2725 		return idx;
2726 
2727 	ffs_ep = func->eps + idx;
2728 
2729 	if (unlikely(ffs_ep->descs[ep_desc_id])) {
2730 		pr_err("two %sspeed descriptors for EP %d\n",
2731 			  speed_names[ep_desc_id],
2732 			  ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2733 		return -EINVAL;
2734 	}
2735 	ffs_ep->descs[ep_desc_id] = ds;
2736 
2737 	ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
2738 	if (ffs_ep->ep) {
2739 		ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2740 		if (!ds->wMaxPacketSize)
2741 			ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2742 	} else {
2743 		struct usb_request *req;
2744 		struct usb_ep *ep;
2745 		u8 bEndpointAddress;
2746 
2747 		/*
2748 		 * We back up bEndpointAddress because autoconfig overwrites
2749 		 * it with physical endpoint address.
2750 		 */
2751 		bEndpointAddress = ds->bEndpointAddress;
2752 		pr_vdebug("autoconfig\n");
2753 		ep = usb_ep_autoconfig(func->gadget, ds);
2754 		if (unlikely(!ep))
2755 			return -ENOTSUPP;
2756 		ep->driver_data = func->eps + idx;
2757 
2758 		req = usb_ep_alloc_request(ep, GFP_KERNEL);
2759 		if (unlikely(!req))
2760 			return -ENOMEM;
2761 
2762 		ffs_ep->ep  = ep;
2763 		ffs_ep->req = req;
2764 		func->eps_revmap[ds->bEndpointAddress &
2765 				 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2766 		/*
2767 		 * If we use virtual address mapping, we restore
2768 		 * original bEndpointAddress value.
2769 		 */
2770 		if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2771 			ds->bEndpointAddress = bEndpointAddress;
2772 	}
2773 	ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2774 
2775 	return 0;
2776 }
2777 
__ffs_func_bind_do_nums(enum ffs_entity_type type,u8 * valuep,struct usb_descriptor_header * desc,void * priv)2778 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2779 				   struct usb_descriptor_header *desc,
2780 				   void *priv)
2781 {
2782 	struct ffs_function *func = priv;
2783 	unsigned idx;
2784 	u8 newValue;
2785 
2786 	switch (type) {
2787 	default:
2788 	case FFS_DESCRIPTOR:
2789 		/* Handled in previous pass by __ffs_func_bind_do_descs() */
2790 		return 0;
2791 
2792 	case FFS_INTERFACE:
2793 		idx = *valuep;
2794 		if (func->interfaces_nums[idx] < 0) {
2795 			int id = usb_interface_id(func->conf, &func->function);
2796 			if (unlikely(id < 0))
2797 				return id;
2798 			func->interfaces_nums[idx] = id;
2799 		}
2800 		newValue = func->interfaces_nums[idx];
2801 		break;
2802 
2803 	case FFS_STRING:
2804 		/* String' IDs are allocated when fsf_data is bound to cdev */
2805 		newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2806 		break;
2807 
2808 	case FFS_ENDPOINT:
2809 		/*
2810 		 * USB_DT_ENDPOINT are handled in
2811 		 * __ffs_func_bind_do_descs().
2812 		 */
2813 		if (desc->bDescriptorType == USB_DT_ENDPOINT)
2814 			return 0;
2815 
2816 		idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2817 		if (unlikely(!func->eps[idx].ep))
2818 			return -EINVAL;
2819 
2820 		{
2821 			struct usb_endpoint_descriptor **descs;
2822 			descs = func->eps[idx].descs;
2823 			newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2824 		}
2825 		break;
2826 	}
2827 
2828 	pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2829 	*valuep = newValue;
2830 	return 0;
2831 }
2832 
__ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,struct usb_os_desc_header * h,void * data,unsigned len,void * priv)2833 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2834 				      struct usb_os_desc_header *h, void *data,
2835 				      unsigned len, void *priv)
2836 {
2837 	struct ffs_function *func = priv;
2838 	u8 length = 0;
2839 
2840 	switch (type) {
2841 	case FFS_OS_DESC_EXT_COMPAT: {
2842 		struct usb_ext_compat_desc *desc = data;
2843 		struct usb_os_desc_table *t;
2844 
2845 		t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2846 		t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2847 		memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2848 		       ARRAY_SIZE(desc->CompatibleID) +
2849 		       ARRAY_SIZE(desc->SubCompatibleID));
2850 		length = sizeof(*desc);
2851 	}
2852 		break;
2853 	case FFS_OS_DESC_EXT_PROP: {
2854 		struct usb_ext_prop_desc *desc = data;
2855 		struct usb_os_desc_table *t;
2856 		struct usb_os_desc_ext_prop *ext_prop;
2857 		char *ext_prop_name;
2858 		char *ext_prop_data;
2859 
2860 		t = &func->function.os_desc_table[h->interface];
2861 		t->if_id = func->interfaces_nums[h->interface];
2862 
2863 		ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2864 		func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2865 
2866 		ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2867 		ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2868 		ext_prop->data_len = le32_to_cpu(*(u32 *)
2869 			usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2870 		length = ext_prop->name_len + ext_prop->data_len + 14;
2871 
2872 		ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2873 		func->ffs->ms_os_descs_ext_prop_name_avail +=
2874 			ext_prop->name_len;
2875 
2876 		ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2877 		func->ffs->ms_os_descs_ext_prop_data_avail +=
2878 			ext_prop->data_len;
2879 		memcpy(ext_prop_data,
2880 		       usb_ext_prop_data_ptr(data, ext_prop->name_len),
2881 		       ext_prop->data_len);
2882 		/* unicode data reported to the host as "WCHAR"s */
2883 		switch (ext_prop->type) {
2884 		case USB_EXT_PROP_UNICODE:
2885 		case USB_EXT_PROP_UNICODE_ENV:
2886 		case USB_EXT_PROP_UNICODE_LINK:
2887 		case USB_EXT_PROP_UNICODE_MULTI:
2888 			ext_prop->data_len *= 2;
2889 			break;
2890 		}
2891 		ext_prop->data = ext_prop_data;
2892 
2893 		memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2894 		       ext_prop->name_len);
2895 		/* property name reported to the host as "WCHAR"s */
2896 		ext_prop->name_len *= 2;
2897 		ext_prop->name = ext_prop_name;
2898 
2899 		t->os_desc->ext_prop_len +=
2900 			ext_prop->name_len + ext_prop->data_len + 14;
2901 		++t->os_desc->ext_prop_count;
2902 		list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2903 	}
2904 		break;
2905 	default:
2906 		pr_vdebug("unknown descriptor: %d\n", type);
2907 	}
2908 
2909 	return length;
2910 }
2911 
ffs_do_functionfs_bind(struct usb_function * f,struct usb_configuration * c)2912 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2913 						struct usb_configuration *c)
2914 {
2915 	struct ffs_function *func = ffs_func_from_usb(f);
2916 	struct f_fs_opts *ffs_opts =
2917 		container_of(f->fi, struct f_fs_opts, func_inst);
2918 	int ret;
2919 
2920 	ENTER();
2921 
2922 	/*
2923 	 * Legacy gadget triggers binding in functionfs_ready_callback,
2924 	 * which already uses locking; taking the same lock here would
2925 	 * cause a deadlock.
2926 	 *
2927 	 * Configfs-enabled gadgets however do need ffs_dev_lock.
2928 	 */
2929 	if (!ffs_opts->no_configfs)
2930 		ffs_dev_lock();
2931 	ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2932 	func->ffs = ffs_opts->dev->ffs_data;
2933 	if (!ffs_opts->no_configfs)
2934 		ffs_dev_unlock();
2935 	if (ret)
2936 		return ERR_PTR(ret);
2937 
2938 	func->conf = c;
2939 	func->gadget = c->cdev->gadget;
2940 
2941 	/*
2942 	 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2943 	 * configurations are bound in sequence with list_for_each_entry,
2944 	 * in each configuration its functions are bound in sequence
2945 	 * with list_for_each_entry, so we assume no race condition
2946 	 * with regard to ffs_opts->bound access
2947 	 */
2948 	if (!ffs_opts->refcnt) {
2949 		ret = functionfs_bind(func->ffs, c->cdev);
2950 		if (ret)
2951 			return ERR_PTR(ret);
2952 	}
2953 	ffs_opts->refcnt++;
2954 	func->function.strings = func->ffs->stringtabs;
2955 
2956 	return ffs_opts;
2957 }
2958 
_ffs_func_bind(struct usb_configuration * c,struct usb_function * f)2959 static int _ffs_func_bind(struct usb_configuration *c,
2960 			  struct usb_function *f)
2961 {
2962 	struct ffs_function *func = ffs_func_from_usb(f);
2963 	struct ffs_data *ffs = func->ffs;
2964 
2965 	const int full = !!func->ffs->fs_descs_count;
2966 	const int high = !!func->ffs->hs_descs_count;
2967 	const int super = !!func->ffs->ss_descs_count;
2968 
2969 	int fs_len, hs_len, ss_len, ret, i;
2970 	struct ffs_ep *eps_ptr;
2971 
2972 	/* Make it a single chunk, less management later on */
2973 	vla_group(d);
2974 	vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2975 	vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2976 		full ? ffs->fs_descs_count + 1 : 0);
2977 	vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2978 		high ? ffs->hs_descs_count + 1 : 0);
2979 	vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2980 		super ? ffs->ss_descs_count + 1 : 0);
2981 	vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2982 	vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2983 			 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2984 	vla_item_with_sz(d, char[16], ext_compat,
2985 			 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2986 	vla_item_with_sz(d, struct usb_os_desc, os_desc,
2987 			 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2988 	vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2989 			 ffs->ms_os_descs_ext_prop_count);
2990 	vla_item_with_sz(d, char, ext_prop_name,
2991 			 ffs->ms_os_descs_ext_prop_name_len);
2992 	vla_item_with_sz(d, char, ext_prop_data,
2993 			 ffs->ms_os_descs_ext_prop_data_len);
2994 	vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2995 	char *vlabuf;
2996 
2997 	ENTER();
2998 
2999 	/* Has descriptors only for speeds gadget does not support */
3000 	if (unlikely(!(full | high | super)))
3001 		return -ENOTSUPP;
3002 
3003 	/* Allocate a single chunk, less management later on */
3004 	vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
3005 	if (unlikely(!vlabuf))
3006 		return -ENOMEM;
3007 
3008 	ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
3009 	ffs->ms_os_descs_ext_prop_name_avail =
3010 		vla_ptr(vlabuf, d, ext_prop_name);
3011 	ffs->ms_os_descs_ext_prop_data_avail =
3012 		vla_ptr(vlabuf, d, ext_prop_data);
3013 
3014 	/* Copy descriptors  */
3015 	memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
3016 	       ffs->raw_descs_length);
3017 
3018 	memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
3019 	eps_ptr = vla_ptr(vlabuf, d, eps);
3020 	for (i = 0; i < ffs->eps_count; i++)
3021 		eps_ptr[i].num = -1;
3022 
3023 	/* Save pointers
3024 	 * d_eps == vlabuf, func->eps used to kfree vlabuf later
3025 	*/
3026 	func->eps             = vla_ptr(vlabuf, d, eps);
3027 	func->interfaces_nums = vla_ptr(vlabuf, d, inums);
3028 
3029 	/*
3030 	 * Go through all the endpoint descriptors and allocate
3031 	 * endpoints first, so that later we can rewrite the endpoint
3032 	 * numbers without worrying that it may be described later on.
3033 	 */
3034 	if (likely(full)) {
3035 		func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
3036 		fs_len = ffs_do_descs(ffs->fs_descs_count,
3037 				      vla_ptr(vlabuf, d, raw_descs),
3038 				      d_raw_descs__sz,
3039 				      __ffs_func_bind_do_descs, func);
3040 		if (unlikely(fs_len < 0)) {
3041 			ret = fs_len;
3042 			goto error;
3043 		}
3044 	} else {
3045 		fs_len = 0;
3046 	}
3047 
3048 	if (likely(high)) {
3049 		func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
3050 		hs_len = ffs_do_descs(ffs->hs_descs_count,
3051 				      vla_ptr(vlabuf, d, raw_descs) + fs_len,
3052 				      d_raw_descs__sz - fs_len,
3053 				      __ffs_func_bind_do_descs, func);
3054 		if (unlikely(hs_len < 0)) {
3055 			ret = hs_len;
3056 			goto error;
3057 		}
3058 	} else {
3059 		hs_len = 0;
3060 	}
3061 
3062 	if (likely(super)) {
3063 		func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
3064 		ss_len = ffs_do_descs(ffs->ss_descs_count,
3065 				vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
3066 				d_raw_descs__sz - fs_len - hs_len,
3067 				__ffs_func_bind_do_descs, func);
3068 		if (unlikely(ss_len < 0)) {
3069 			ret = ss_len;
3070 			goto error;
3071 		}
3072 	} else {
3073 		ss_len = 0;
3074 	}
3075 
3076 	/*
3077 	 * Now handle interface numbers allocation and interface and
3078 	 * endpoint numbers rewriting.  We can do that in one go
3079 	 * now.
3080 	 */
3081 	ret = ffs_do_descs(ffs->fs_descs_count +
3082 			   (high ? ffs->hs_descs_count : 0) +
3083 			   (super ? ffs->ss_descs_count : 0),
3084 			   vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
3085 			   __ffs_func_bind_do_nums, func);
3086 	if (unlikely(ret < 0))
3087 		goto error;
3088 
3089 	func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
3090 	if (c->cdev->use_os_string) {
3091 		for (i = 0; i < ffs->interfaces_count; ++i) {
3092 			struct usb_os_desc *desc;
3093 
3094 			desc = func->function.os_desc_table[i].os_desc =
3095 				vla_ptr(vlabuf, d, os_desc) +
3096 				i * sizeof(struct usb_os_desc);
3097 			desc->ext_compat_id =
3098 				vla_ptr(vlabuf, d, ext_compat) + i * 16;
3099 			INIT_LIST_HEAD(&desc->ext_prop);
3100 		}
3101 		ret = ffs_do_os_descs(ffs->ms_os_descs_count,
3102 				      vla_ptr(vlabuf, d, raw_descs) +
3103 				      fs_len + hs_len + ss_len,
3104 				      d_raw_descs__sz - fs_len - hs_len -
3105 				      ss_len,
3106 				      __ffs_func_bind_do_os_desc, func);
3107 		if (unlikely(ret < 0))
3108 			goto error;
3109 	}
3110 	func->function.os_desc_n =
3111 		c->cdev->use_os_string ? ffs->interfaces_count : 0;
3112 
3113 	/* And we're done */
3114 	ffs_event_add(ffs, FUNCTIONFS_BIND);
3115 	return 0;
3116 
3117 error:
3118 	/* XXX Do we need to release all claimed endpoints here? */
3119 	return ret;
3120 }
3121 
ffs_func_bind(struct usb_configuration * c,struct usb_function * f)3122 static int ffs_func_bind(struct usb_configuration *c,
3123 			 struct usb_function *f)
3124 {
3125 	struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
3126 	struct ffs_function *func = ffs_func_from_usb(f);
3127 	int ret;
3128 
3129 	if (IS_ERR(ffs_opts))
3130 		return PTR_ERR(ffs_opts);
3131 
3132 	ret = _ffs_func_bind(c, f);
3133 	if (ret && !--ffs_opts->refcnt)
3134 		functionfs_unbind(func->ffs);
3135 
3136 	return ret;
3137 }
3138 
3139 
3140 /* Other USB function hooks *************************************************/
3141 
ffs_reset_work(struct work_struct * work)3142 static void ffs_reset_work(struct work_struct *work)
3143 {
3144 	struct ffs_data *ffs = container_of(work,
3145 		struct ffs_data, reset_work);
3146 	ffs_data_reset(ffs);
3147 }
3148 
ffs_func_set_alt(struct usb_function * f,unsigned interface,unsigned alt)3149 static int ffs_func_set_alt(struct usb_function *f,
3150 			    unsigned interface, unsigned alt)
3151 {
3152 	struct ffs_function *func = ffs_func_from_usb(f);
3153 	struct ffs_data *ffs = func->ffs;
3154 	int ret = 0, intf;
3155 
3156 	if (alt != (unsigned)-1) {
3157 		intf = ffs_func_revmap_intf(func, interface);
3158 		if (unlikely(intf < 0))
3159 			return intf;
3160 	}
3161 
3162 	if (ffs->func)
3163 		ffs_func_eps_disable(ffs->func);
3164 
3165 	if (ffs->state == FFS_DEACTIVATED) {
3166 		ffs->state = FFS_CLOSING;
3167 		INIT_WORK(&ffs->reset_work, ffs_reset_work);
3168 		schedule_work(&ffs->reset_work);
3169 		return -ENODEV;
3170 	}
3171 
3172 	if (ffs->state != FFS_ACTIVE)
3173 		return -ENODEV;
3174 
3175 	if (alt == (unsigned)-1) {
3176 		ffs->func = NULL;
3177 		ffs_event_add(ffs, FUNCTIONFS_DISABLE);
3178 		return 0;
3179 	}
3180 
3181 	ffs->func = func;
3182 	ret = ffs_func_eps_enable(func);
3183 	if (likely(ret >= 0))
3184 		ffs_event_add(ffs, FUNCTIONFS_ENABLE);
3185 	return ret;
3186 }
3187 
ffs_func_disable(struct usb_function * f)3188 static void ffs_func_disable(struct usb_function *f)
3189 {
3190 	ffs_func_set_alt(f, 0, (unsigned)-1);
3191 }
3192 
ffs_func_setup(struct usb_function * f,const struct usb_ctrlrequest * creq)3193 static int ffs_func_setup(struct usb_function *f,
3194 			  const struct usb_ctrlrequest *creq)
3195 {
3196 	struct ffs_function *func = ffs_func_from_usb(f);
3197 	struct ffs_data *ffs = func->ffs;
3198 	unsigned long flags;
3199 	int ret;
3200 
3201 	ENTER();
3202 
3203 	pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
3204 	pr_vdebug("creq->bRequest     = %02x\n", creq->bRequest);
3205 	pr_vdebug("creq->wValue       = %04x\n", le16_to_cpu(creq->wValue));
3206 	pr_vdebug("creq->wIndex       = %04x\n", le16_to_cpu(creq->wIndex));
3207 	pr_vdebug("creq->wLength      = %04x\n", le16_to_cpu(creq->wLength));
3208 
3209 	/*
3210 	 * Most requests directed to interface go through here
3211 	 * (notable exceptions are set/get interface) so we need to
3212 	 * handle them.  All other either handled by composite or
3213 	 * passed to usb_configuration->setup() (if one is set).  No
3214 	 * matter, we will handle requests directed to endpoint here
3215 	 * as well (as it's straightforward).  Other request recipient
3216 	 * types are only handled when the user flag FUNCTIONFS_ALL_CTRL_RECIP
3217 	 * is being used.
3218 	 */
3219 	if (ffs->state != FFS_ACTIVE)
3220 		return -ENODEV;
3221 
3222 	switch (creq->bRequestType & USB_RECIP_MASK) {
3223 	case USB_RECIP_INTERFACE:
3224 		ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
3225 		if (unlikely(ret < 0))
3226 			return ret;
3227 		break;
3228 
3229 	case USB_RECIP_ENDPOINT:
3230 		ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
3231 		if (unlikely(ret < 0))
3232 			return ret;
3233 		if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3234 			ret = func->ffs->eps_addrmap[ret];
3235 		break;
3236 
3237 	default:
3238 		if (func->ffs->user_flags & FUNCTIONFS_ALL_CTRL_RECIP)
3239 			ret = le16_to_cpu(creq->wIndex);
3240 		else
3241 			return -EOPNOTSUPP;
3242 	}
3243 
3244 	spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
3245 	ffs->ev.setup = *creq;
3246 	ffs->ev.setup.wIndex = cpu_to_le16(ret);
3247 	__ffs_event_add(ffs, FUNCTIONFS_SETUP);
3248 	spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
3249 
3250 	return creq->wLength == 0 ? USB_GADGET_DELAYED_STATUS : 0;
3251 }
3252 
ffs_func_req_match(struct usb_function * f,const struct usb_ctrlrequest * creq,bool config0)3253 static bool ffs_func_req_match(struct usb_function *f,
3254 			       const struct usb_ctrlrequest *creq,
3255 			       bool config0)
3256 {
3257 	struct ffs_function *func = ffs_func_from_usb(f);
3258 
3259 	if (config0 && !(func->ffs->user_flags & FUNCTIONFS_CONFIG0_SETUP))
3260 		return false;
3261 
3262 	switch (creq->bRequestType & USB_RECIP_MASK) {
3263 	case USB_RECIP_INTERFACE:
3264 		return (ffs_func_revmap_intf(func,
3265 					     le16_to_cpu(creq->wIndex)) >= 0);
3266 	case USB_RECIP_ENDPOINT:
3267 		return (ffs_func_revmap_ep(func,
3268 					   le16_to_cpu(creq->wIndex)) >= 0);
3269 	default:
3270 		return (bool) (func->ffs->user_flags &
3271 			       FUNCTIONFS_ALL_CTRL_RECIP);
3272 	}
3273 }
3274 
ffs_func_suspend(struct usb_function * f)3275 static void ffs_func_suspend(struct usb_function *f)
3276 {
3277 	ENTER();
3278 	ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
3279 }
3280 
ffs_func_resume(struct usb_function * f)3281 static void ffs_func_resume(struct usb_function *f)
3282 {
3283 	ENTER();
3284 	ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
3285 }
3286 
3287 
3288 /* Endpoint and interface numbers reverse mapping ***************************/
3289 
ffs_func_revmap_ep(struct ffs_function * func,u8 num)3290 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3291 {
3292 	num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3293 	return num ? num : -EDOM;
3294 }
3295 
ffs_func_revmap_intf(struct ffs_function * func,u8 intf)3296 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3297 {
3298 	short *nums = func->interfaces_nums;
3299 	unsigned count = func->ffs->interfaces_count;
3300 
3301 	for (; count; --count, ++nums) {
3302 		if (*nums >= 0 && *nums == intf)
3303 			return nums - func->interfaces_nums;
3304 	}
3305 
3306 	return -EDOM;
3307 }
3308 
3309 
3310 /* Devices management *******************************************************/
3311 
3312 static LIST_HEAD(ffs_devices);
3313 
_ffs_do_find_dev(const char * name)3314 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3315 {
3316 	struct ffs_dev *dev;
3317 
3318 	if (!name)
3319 		return NULL;
3320 
3321 	list_for_each_entry(dev, &ffs_devices, entry) {
3322 		if (strcmp(dev->name, name) == 0)
3323 			return dev;
3324 	}
3325 
3326 	return NULL;
3327 }
3328 
3329 /*
3330  * ffs_lock must be taken by the caller of this function
3331  */
_ffs_get_single_dev(void)3332 static struct ffs_dev *_ffs_get_single_dev(void)
3333 {
3334 	struct ffs_dev *dev;
3335 
3336 	if (list_is_singular(&ffs_devices)) {
3337 		dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3338 		if (dev->single)
3339 			return dev;
3340 	}
3341 
3342 	return NULL;
3343 }
3344 
3345 /*
3346  * ffs_lock must be taken by the caller of this function
3347  */
_ffs_find_dev(const char * name)3348 static struct ffs_dev *_ffs_find_dev(const char *name)
3349 {
3350 	struct ffs_dev *dev;
3351 
3352 	dev = _ffs_get_single_dev();
3353 	if (dev)
3354 		return dev;
3355 
3356 	return _ffs_do_find_dev(name);
3357 }
3358 
3359 /* Configfs support *********************************************************/
3360 
to_ffs_opts(struct config_item * item)3361 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3362 {
3363 	return container_of(to_config_group(item), struct f_fs_opts,
3364 			    func_inst.group);
3365 }
3366 
ffs_attr_release(struct config_item * item)3367 static void ffs_attr_release(struct config_item *item)
3368 {
3369 	struct f_fs_opts *opts = to_ffs_opts(item);
3370 
3371 	usb_put_function_instance(&opts->func_inst);
3372 }
3373 
3374 static struct configfs_item_operations ffs_item_ops = {
3375 	.release	= ffs_attr_release,
3376 };
3377 
3378 static struct config_item_type ffs_func_type = {
3379 	.ct_item_ops	= &ffs_item_ops,
3380 	.ct_owner	= THIS_MODULE,
3381 };
3382 
3383 
3384 /* Function registration interface ******************************************/
3385 
ffs_free_inst(struct usb_function_instance * f)3386 static void ffs_free_inst(struct usb_function_instance *f)
3387 {
3388 	struct f_fs_opts *opts;
3389 
3390 	opts = to_f_fs_opts(f);
3391 	ffs_dev_lock();
3392 	_ffs_free_dev(opts->dev);
3393 	ffs_dev_unlock();
3394 	kfree(opts);
3395 }
3396 
ffs_set_inst_name(struct usb_function_instance * fi,const char * name)3397 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3398 {
3399 	if (strlen(name) >= FIELD_SIZEOF(struct ffs_dev, name))
3400 		return -ENAMETOOLONG;
3401 	return ffs_name_dev(to_f_fs_opts(fi)->dev, name);
3402 }
3403 
ffs_alloc_inst(void)3404 static struct usb_function_instance *ffs_alloc_inst(void)
3405 {
3406 	struct f_fs_opts *opts;
3407 	struct ffs_dev *dev;
3408 
3409 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3410 	if (!opts)
3411 		return ERR_PTR(-ENOMEM);
3412 
3413 	opts->func_inst.set_inst_name = ffs_set_inst_name;
3414 	opts->func_inst.free_func_inst = ffs_free_inst;
3415 	ffs_dev_lock();
3416 	dev = _ffs_alloc_dev();
3417 	ffs_dev_unlock();
3418 	if (IS_ERR(dev)) {
3419 		kfree(opts);
3420 		return ERR_CAST(dev);
3421 	}
3422 	opts->dev = dev;
3423 	dev->opts = opts;
3424 
3425 	config_group_init_type_name(&opts->func_inst.group, "",
3426 				    &ffs_func_type);
3427 	return &opts->func_inst;
3428 }
3429 
ffs_free(struct usb_function * f)3430 static void ffs_free(struct usb_function *f)
3431 {
3432 	kfree(ffs_func_from_usb(f));
3433 }
3434 
ffs_func_unbind(struct usb_configuration * c,struct usb_function * f)3435 static void ffs_func_unbind(struct usb_configuration *c,
3436 			    struct usb_function *f)
3437 {
3438 	struct ffs_function *func = ffs_func_from_usb(f);
3439 	struct ffs_data *ffs = func->ffs;
3440 	struct f_fs_opts *opts =
3441 		container_of(f->fi, struct f_fs_opts, func_inst);
3442 	struct ffs_ep *ep = func->eps;
3443 	unsigned count = ffs->eps_count;
3444 	unsigned long flags;
3445 
3446 	ENTER();
3447 	if (ffs->func == func) {
3448 		ffs_func_eps_disable(func);
3449 		ffs->func = NULL;
3450 	}
3451 
3452 	if (!--opts->refcnt)
3453 		functionfs_unbind(ffs);
3454 
3455 	/* cleanup after autoconfig */
3456 	spin_lock_irqsave(&func->ffs->eps_lock, flags);
3457 	while (count--) {
3458 		if (ep->ep && ep->req)
3459 			usb_ep_free_request(ep->ep, ep->req);
3460 		ep->req = NULL;
3461 		++ep;
3462 	}
3463 	spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3464 	kfree(func->eps);
3465 	func->eps = NULL;
3466 	/*
3467 	 * eps, descriptors and interfaces_nums are allocated in the
3468 	 * same chunk so only one free is required.
3469 	 */
3470 	func->function.fs_descriptors = NULL;
3471 	func->function.hs_descriptors = NULL;
3472 	func->function.ss_descriptors = NULL;
3473 	func->interfaces_nums = NULL;
3474 
3475 	ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3476 }
3477 
ffs_alloc(struct usb_function_instance * fi)3478 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3479 {
3480 	struct ffs_function *func;
3481 
3482 	ENTER();
3483 
3484 	func = kzalloc(sizeof(*func), GFP_KERNEL);
3485 	if (unlikely(!func))
3486 		return ERR_PTR(-ENOMEM);
3487 
3488 	func->function.name    = "Function FS Gadget";
3489 
3490 	func->function.bind    = ffs_func_bind;
3491 	func->function.unbind  = ffs_func_unbind;
3492 	func->function.set_alt = ffs_func_set_alt;
3493 	func->function.disable = ffs_func_disable;
3494 	func->function.setup   = ffs_func_setup;
3495 	func->function.req_match = ffs_func_req_match;
3496 	func->function.suspend = ffs_func_suspend;
3497 	func->function.resume  = ffs_func_resume;
3498 	func->function.free_func = ffs_free;
3499 
3500 	return &func->function;
3501 }
3502 
3503 /*
3504  * ffs_lock must be taken by the caller of this function
3505  */
_ffs_alloc_dev(void)3506 static struct ffs_dev *_ffs_alloc_dev(void)
3507 {
3508 	struct ffs_dev *dev;
3509 	int ret;
3510 
3511 	if (_ffs_get_single_dev())
3512 			return ERR_PTR(-EBUSY);
3513 
3514 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3515 	if (!dev)
3516 		return ERR_PTR(-ENOMEM);
3517 
3518 	if (list_empty(&ffs_devices)) {
3519 		ret = functionfs_init();
3520 		if (ret) {
3521 			kfree(dev);
3522 			return ERR_PTR(ret);
3523 		}
3524 	}
3525 
3526 	list_add(&dev->entry, &ffs_devices);
3527 
3528 	return dev;
3529 }
3530 
ffs_name_dev(struct ffs_dev * dev,const char * name)3531 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3532 {
3533 	struct ffs_dev *existing;
3534 	int ret = 0;
3535 
3536 	ffs_dev_lock();
3537 
3538 	existing = _ffs_do_find_dev(name);
3539 	if (!existing)
3540 		strlcpy(dev->name, name, ARRAY_SIZE(dev->name));
3541 	else if (existing != dev)
3542 		ret = -EBUSY;
3543 
3544 	ffs_dev_unlock();
3545 
3546 	return ret;
3547 }
3548 EXPORT_SYMBOL_GPL(ffs_name_dev);
3549 
ffs_single_dev(struct ffs_dev * dev)3550 int ffs_single_dev(struct ffs_dev *dev)
3551 {
3552 	int ret;
3553 
3554 	ret = 0;
3555 	ffs_dev_lock();
3556 
3557 	if (!list_is_singular(&ffs_devices))
3558 		ret = -EBUSY;
3559 	else
3560 		dev->single = true;
3561 
3562 	ffs_dev_unlock();
3563 	return ret;
3564 }
3565 EXPORT_SYMBOL_GPL(ffs_single_dev);
3566 
3567 /*
3568  * ffs_lock must be taken by the caller of this function
3569  */
_ffs_free_dev(struct ffs_dev * dev)3570 static void _ffs_free_dev(struct ffs_dev *dev)
3571 {
3572 	list_del(&dev->entry);
3573 
3574 	/* Clear the private_data pointer to stop incorrect dev access */
3575 	if (dev->ffs_data)
3576 		dev->ffs_data->private_data = NULL;
3577 
3578 	kfree(dev);
3579 	if (list_empty(&ffs_devices))
3580 		functionfs_cleanup();
3581 }
3582 
ffs_acquire_dev(const char * dev_name)3583 static void *ffs_acquire_dev(const char *dev_name)
3584 {
3585 	struct ffs_dev *ffs_dev;
3586 
3587 	ENTER();
3588 	ffs_dev_lock();
3589 
3590 	ffs_dev = _ffs_find_dev(dev_name);
3591 	if (!ffs_dev)
3592 		ffs_dev = ERR_PTR(-ENOENT);
3593 	else if (ffs_dev->mounted)
3594 		ffs_dev = ERR_PTR(-EBUSY);
3595 	else if (ffs_dev->ffs_acquire_dev_callback &&
3596 	    ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3597 		ffs_dev = ERR_PTR(-ENOENT);
3598 	else
3599 		ffs_dev->mounted = true;
3600 
3601 	ffs_dev_unlock();
3602 	return ffs_dev;
3603 }
3604 
ffs_release_dev(struct ffs_data * ffs_data)3605 static void ffs_release_dev(struct ffs_data *ffs_data)
3606 {
3607 	struct ffs_dev *ffs_dev;
3608 
3609 	ENTER();
3610 	ffs_dev_lock();
3611 
3612 	ffs_dev = ffs_data->private_data;
3613 	if (ffs_dev) {
3614 		ffs_dev->mounted = false;
3615 
3616 		if (ffs_dev->ffs_release_dev_callback)
3617 			ffs_dev->ffs_release_dev_callback(ffs_dev);
3618 	}
3619 
3620 	ffs_dev_unlock();
3621 }
3622 
ffs_ready(struct ffs_data * ffs)3623 static int ffs_ready(struct ffs_data *ffs)
3624 {
3625 	struct ffs_dev *ffs_obj;
3626 	int ret = 0;
3627 
3628 	ENTER();
3629 	ffs_dev_lock();
3630 
3631 	ffs_obj = ffs->private_data;
3632 	if (!ffs_obj) {
3633 		ret = -EINVAL;
3634 		goto done;
3635 	}
3636 	if (WARN_ON(ffs_obj->desc_ready)) {
3637 		ret = -EBUSY;
3638 		goto done;
3639 	}
3640 
3641 	ffs_obj->desc_ready = true;
3642 	ffs_obj->ffs_data = ffs;
3643 
3644 	if (ffs_obj->ffs_ready_callback) {
3645 		ret = ffs_obj->ffs_ready_callback(ffs);
3646 		if (ret)
3647 			goto done;
3648 	}
3649 
3650 	set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
3651 done:
3652 	ffs_dev_unlock();
3653 	return ret;
3654 }
3655 
ffs_closed(struct ffs_data * ffs)3656 static void ffs_closed(struct ffs_data *ffs)
3657 {
3658 	struct ffs_dev *ffs_obj;
3659 	struct f_fs_opts *opts;
3660 	struct config_item *ci;
3661 
3662 	ENTER();
3663 	ffs_dev_lock();
3664 
3665 	ffs_obj = ffs->private_data;
3666 	if (!ffs_obj)
3667 		goto done;
3668 
3669 	ffs_obj->desc_ready = false;
3670 	ffs_obj->ffs_data = NULL;
3671 
3672 	if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
3673 	    ffs_obj->ffs_closed_callback)
3674 		ffs_obj->ffs_closed_callback(ffs);
3675 
3676 	if (ffs_obj->opts)
3677 		opts = ffs_obj->opts;
3678 	else
3679 		goto done;
3680 
3681 	if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
3682 	    || !kref_read(&opts->func_inst.group.cg_item.ci_kref))
3683 		goto done;
3684 
3685 	ci = opts->func_inst.group.cg_item.ci_parent->ci_parent;
3686 	ffs_dev_unlock();
3687 
3688 	if (test_bit(FFS_FL_BOUND, &ffs->flags))
3689 		unregister_gadget_item(ci);
3690 	return;
3691 done:
3692 	ffs_dev_unlock();
3693 }
3694 
3695 /* Misc helper functions ****************************************************/
3696 
ffs_mutex_lock(struct mutex * mutex,unsigned nonblock)3697 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3698 {
3699 	return nonblock
3700 		? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3701 		: mutex_lock_interruptible(mutex);
3702 }
3703 
ffs_prepare_buffer(const char __user * buf,size_t len)3704 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3705 {
3706 	char *data;
3707 
3708 	if (unlikely(!len))
3709 		return NULL;
3710 
3711 	data = kmalloc(len, GFP_KERNEL);
3712 	if (unlikely(!data))
3713 		return ERR_PTR(-ENOMEM);
3714 
3715 	if (unlikely(copy_from_user(data, buf, len))) {
3716 		kfree(data);
3717 		return ERR_PTR(-EFAULT);
3718 	}
3719 
3720 	pr_vdebug("Buffer from user space:\n");
3721 	ffs_dump_mem("", data, len);
3722 
3723 	return data;
3724 }
3725 
3726 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3727 MODULE_LICENSE("GPL");
3728 MODULE_AUTHOR("Michal Nazarewicz");
3729