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