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