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