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