1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * fs/eventpoll.c (Efficient event retrieval implementation) 4 * Copyright (C) 2001,...,2009 Davide Libenzi 5 * 6 * Davide Libenzi <davidel@xmailserver.org> 7 */ 8 9 #include <linux/init.h> 10 #include <linux/kernel.h> 11 #include <linux/sched/signal.h> 12 #include <linux/fs.h> 13 #include <linux/file.h> 14 #include <linux/signal.h> 15 #include <linux/errno.h> 16 #include <linux/mm.h> 17 #include <linux/slab.h> 18 #include <linux/poll.h> 19 #include <linux/string.h> 20 #include <linux/list.h> 21 #include <linux/hash.h> 22 #include <linux/spinlock.h> 23 #include <linux/syscalls.h> 24 #include <linux/rbtree.h> 25 #include <linux/wait.h> 26 #include <linux/eventpoll.h> 27 #include <linux/mount.h> 28 #include <linux/bitops.h> 29 #include <linux/mutex.h> 30 #include <linux/anon_inodes.h> 31 #include <linux/device.h> 32 #include <linux/uaccess.h> 33 #include <asm/io.h> 34 #include <asm/mman.h> 35 #include <linux/atomic.h> 36 #include <linux/proc_fs.h> 37 #include <linux/seq_file.h> 38 #include <linux/compat.h> 39 #include <linux/rculist.h> 40 #include <linux/capability.h> 41 #include <net/busy_poll.h> 42 43 /* 44 * LOCKING: 45 * There are three level of locking required by epoll : 46 * 47 * 1) epnested_mutex (mutex) 48 * 2) ep->mtx (mutex) 49 * 3) ep->lock (spinlock) 50 * 51 * The acquire order is the one listed above, from 1 to 3. 52 * We need a spinlock (ep->lock) because we manipulate objects 53 * from inside the poll callback, that might be triggered from 54 * a wake_up() that in turn might be called from IRQ context. 55 * So we can't sleep inside the poll callback and hence we need 56 * a spinlock. During the event transfer loop (from kernel to 57 * user space) we could end up sleeping due a copy_to_user(), so 58 * we need a lock that will allow us to sleep. This lock is a 59 * mutex (ep->mtx). It is acquired during the event transfer loop, 60 * during epoll_ctl(EPOLL_CTL_DEL) and during eventpoll_release_file(). 61 * The epnested_mutex is acquired when inserting an epoll fd onto another 62 * epoll fd. We do this so that we walk the epoll tree and ensure that this 63 * insertion does not create a cycle of epoll file descriptors, which 64 * could lead to deadlock. We need a global mutex to prevent two 65 * simultaneous inserts (A into B and B into A) from racing and 66 * constructing a cycle without either insert observing that it is 67 * going to. 68 * It is necessary to acquire multiple "ep->mtx"es at once in the 69 * case when one epoll fd is added to another. In this case, we 70 * always acquire the locks in the order of nesting (i.e. after 71 * epoll_ctl(e1, EPOLL_CTL_ADD, e2), e1->mtx will always be acquired 72 * before e2->mtx). Since we disallow cycles of epoll file 73 * descriptors, this ensures that the mutexes are well-ordered. In 74 * order to communicate this nesting to lockdep, when walking a tree 75 * of epoll file descriptors, we use the current recursion depth as 76 * the lockdep subkey. 77 * It is possible to drop the "ep->mtx" and to use the global 78 * mutex "epnested_mutex" (together with "ep->lock") to have it working, 79 * but having "ep->mtx" will make the interface more scalable. 80 * Events that require holding "epnested_mutex" are very rare, while for 81 * normal operations the epoll private "ep->mtx" will guarantee 82 * a better scalability. 83 */ 84 85 /* Epoll private bits inside the event mask */ 86 #define EP_PRIVATE_BITS (EPOLLWAKEUP | EPOLLONESHOT | EPOLLET | EPOLLEXCLUSIVE) 87 88 #define EPOLLINOUT_BITS (EPOLLIN | EPOLLOUT) 89 90 #define EPOLLEXCLUSIVE_OK_BITS (EPOLLINOUT_BITS | EPOLLERR | EPOLLHUP | \ 91 EPOLLWAKEUP | EPOLLET | EPOLLEXCLUSIVE) 92 93 /* Maximum number of nesting allowed inside epoll sets */ 94 #define EP_MAX_NESTS 4 95 96 #define EP_MAX_EVENTS (INT_MAX / sizeof(struct epoll_event)) 97 98 #define EP_UNACTIVE_PTR ((void *) -1L) 99 100 #define EP_ITEM_COST (sizeof(struct epitem) + sizeof(struct eppoll_entry)) 101 102 struct epoll_filefd { 103 struct file *file; 104 int fd; 105 } __packed; 106 107 /* Wait structure used by the poll hooks */ 108 struct eppoll_entry { 109 /* List header used to link this structure to the "struct epitem" */ 110 struct eppoll_entry *next; 111 112 /* The "base" pointer is set to the container "struct epitem" */ 113 struct epitem *base; 114 115 /* 116 * Wait queue item that will be linked to the target file wait 117 * queue head. 118 */ 119 wait_queue_entry_t wait; 120 121 /* The wait queue head that linked the "wait" wait queue item */ 122 wait_queue_head_t *whead; 123 }; 124 125 /* 126 * Each file descriptor added to the eventpoll interface will 127 * have an entry of this type linked to the "rbr" RB tree. 128 * Avoid increasing the size of this struct, there can be many thousands 129 * of these on a server and we do not want this to take another cache line. 130 */ 131 struct epitem { 132 union { 133 /* RB tree node links this structure to the eventpoll RB tree */ 134 struct rb_node rbn; 135 /* Used to free the struct epitem */ 136 struct rcu_head rcu; 137 }; 138 139 /* List header used to link this structure to the eventpoll ready list */ 140 struct list_head rdllink; 141 142 /* 143 * Works together "struct eventpoll"->ovflist in keeping the 144 * single linked chain of items. 145 */ 146 struct epitem *next; 147 148 /* The file descriptor information this item refers to */ 149 struct epoll_filefd ffd; 150 151 /* List containing poll wait queues */ 152 struct eppoll_entry *pwqlist; 153 154 /* The "container" of this item */ 155 struct eventpoll *ep; 156 157 /* List header used to link this item to the "struct file" items list */ 158 struct hlist_node fllink; 159 160 /* wakeup_source used when EPOLLWAKEUP is set */ 161 struct wakeup_source __rcu *ws; 162 163 /* The structure that describe the interested events and the source fd */ 164 struct epoll_event event; 165 }; 166 167 /* 168 * This structure is stored inside the "private_data" member of the file 169 * structure and represents the main data structure for the eventpoll 170 * interface. 171 */ 172 struct eventpoll { 173 /* 174 * This mutex is used to ensure that files are not removed 175 * while epoll is using them. This is held during the event 176 * collection loop, the file cleanup path, the epoll file exit 177 * code and the ctl operations. 178 */ 179 struct mutex mtx; 180 181 /* Wait queue used by sys_epoll_wait() */ 182 wait_queue_head_t wq; 183 184 /* Wait queue used by file->poll() */ 185 wait_queue_head_t poll_wait; 186 187 /* List of ready file descriptors */ 188 struct list_head rdllist; 189 190 /* Lock which protects rdllist and ovflist */ 191 spinlock_t lock; 192 193 /* RB tree root used to store monitored fd structs */ 194 struct rb_root_cached rbr; 195 196 /* 197 * This is a single linked list that chains all the "struct epitem" that 198 * happened while transferring ready events to userspace w/out 199 * holding ->lock. 200 */ 201 struct epitem *ovflist; 202 203 /* wakeup_source used when ep_send_events or __ep_eventpoll_poll is running */ 204 struct wakeup_source *ws; 205 206 /* The user that created the eventpoll descriptor */ 207 struct user_struct *user; 208 209 struct file *file; 210 211 /* used to optimize loop detection check */ 212 u64 gen; 213 struct hlist_head refs; 214 u8 loop_check_depth; 215 216 /* usage count, orchestrates "struct eventpoll" disposal */ 217 refcount_t refcount; 218 219 /* used to defer freeing past ep_get_upwards_depth_proc() RCU walk */ 220 struct rcu_head rcu; 221 222 #ifdef CONFIG_NET_RX_BUSY_POLL 223 /* used to track busy poll napi_id */ 224 unsigned int napi_id; 225 /* busy poll timeout */ 226 u32 busy_poll_usecs; 227 /* busy poll packet budget */ 228 u16 busy_poll_budget; 229 bool prefer_busy_poll; 230 #endif 231 232 #ifdef CONFIG_DEBUG_LOCK_ALLOC 233 /* tracks wakeup nests for lockdep validation */ 234 u8 nests; 235 #endif 236 }; 237 238 /* Wrapper struct used by poll queueing */ 239 struct ep_pqueue { 240 poll_table pt; 241 struct epitem *epi; 242 }; 243 244 /* 245 * Configuration options available inside /proc/sys/fs/epoll/ 246 */ 247 /* Maximum number of epoll watched descriptors, per user */ 248 static long max_user_watches __read_mostly; 249 250 /* Used for cycles detection */ 251 static DEFINE_MUTEX(epnested_mutex); 252 253 static u64 loop_check_gen = 0; 254 255 /* Used to check for epoll file descriptor inclusion loops */ 256 static struct eventpoll *inserting_into; 257 258 /* Slab cache used to allocate "struct epitem" */ 259 static struct kmem_cache *epi_cache __ro_after_init; 260 261 /* Slab cache used to allocate "struct eppoll_entry" */ 262 static struct kmem_cache *pwq_cache __ro_after_init; 263 264 /* 265 * List of files with newly added links, where we may need to limit the number 266 * of emanating paths. Protected by the epnested_mutex. 267 */ 268 struct epitems_head { 269 struct hlist_head epitems; 270 struct epitems_head *next; 271 }; 272 static struct epitems_head *tfile_check_list = EP_UNACTIVE_PTR; 273 274 static struct kmem_cache *ephead_cache __ro_after_init; 275 276 static inline void free_ephead(struct epitems_head *head) 277 { 278 if (head) 279 kmem_cache_free(ephead_cache, head); 280 } 281 282 static void list_file(struct file *file) 283 { 284 struct epitems_head *head; 285 286 head = container_of(file->f_ep, struct epitems_head, epitems); 287 if (!head->next) { 288 head->next = tfile_check_list; 289 tfile_check_list = head; 290 } 291 } 292 293 static void unlist_file(struct epitems_head *head) 294 { 295 struct epitems_head *to_free = head; 296 struct hlist_node *p = rcu_dereference(hlist_first_rcu(&head->epitems)); 297 if (p) { 298 struct epitem *epi= container_of(p, struct epitem, fllink); 299 spin_lock(&epi->ffd.file->f_lock); 300 if (!hlist_empty(&head->epitems)) 301 to_free = NULL; 302 head->next = NULL; 303 spin_unlock(&epi->ffd.file->f_lock); 304 } 305 free_ephead(to_free); 306 } 307 308 #ifdef CONFIG_SYSCTL 309 310 #include <linux/sysctl.h> 311 312 static long long_zero; 313 static long long_max = LONG_MAX; 314 315 static const struct ctl_table epoll_table[] = { 316 { 317 .procname = "max_user_watches", 318 .data = &max_user_watches, 319 .maxlen = sizeof(max_user_watches), 320 .mode = 0644, 321 .proc_handler = proc_doulongvec_minmax, 322 .extra1 = &long_zero, 323 .extra2 = &long_max, 324 }, 325 }; 326 327 static void __init epoll_sysctls_init(void) 328 { 329 register_sysctl("fs/epoll", epoll_table); 330 } 331 #else 332 #define epoll_sysctls_init() do { } while (0) 333 #endif /* CONFIG_SYSCTL */ 334 335 static const struct file_operations eventpoll_fops; 336 337 static inline int is_file_epoll(struct file *f) 338 { 339 return f->f_op == &eventpoll_fops; 340 } 341 342 /* Setup the structure that is used as key for the RB tree */ 343 static inline void ep_set_ffd(struct epoll_filefd *ffd, 344 struct file *file, int fd) 345 { 346 ffd->file = file; 347 ffd->fd = fd; 348 } 349 350 /* Compare RB tree keys */ 351 static inline int ep_cmp_ffd(struct epoll_filefd *p1, 352 struct epoll_filefd *p2) 353 { 354 return (p1->file > p2->file ? +1: 355 (p1->file < p2->file ? -1 : p1->fd - p2->fd)); 356 } 357 358 /* Tells us if the item is currently linked */ 359 static inline int ep_is_linked(struct epitem *epi) 360 { 361 return !list_empty(&epi->rdllink); 362 } 363 364 static inline struct eppoll_entry *ep_pwq_from_wait(wait_queue_entry_t *p) 365 { 366 return container_of(p, struct eppoll_entry, wait); 367 } 368 369 /* Get the "struct epitem" from a wait queue pointer */ 370 static inline struct epitem *ep_item_from_wait(wait_queue_entry_t *p) 371 { 372 return container_of(p, struct eppoll_entry, wait)->base; 373 } 374 375 /** 376 * ep_events_available - Checks if ready events might be available. 377 * 378 * @ep: Pointer to the eventpoll context. 379 * 380 * Return: a value different than %zero if ready events are available, 381 * or %zero otherwise. 382 */ 383 static inline int ep_events_available(struct eventpoll *ep) 384 { 385 return !list_empty_careful(&ep->rdllist) || 386 READ_ONCE(ep->ovflist) != EP_UNACTIVE_PTR; 387 } 388 389 #ifdef CONFIG_NET_RX_BUSY_POLL 390 /** 391 * busy_loop_ep_timeout - check if busy poll has timed out. The timeout value 392 * from the epoll instance ep is preferred, but if it is not set fallback to 393 * the system-wide global via busy_loop_timeout. 394 * 395 * @start_time: The start time used to compute the remaining time until timeout. 396 * @ep: Pointer to the eventpoll context. 397 * 398 * Return: true if the timeout has expired, false otherwise. 399 */ 400 static bool busy_loop_ep_timeout(unsigned long start_time, 401 struct eventpoll *ep) 402 { 403 unsigned long bp_usec = READ_ONCE(ep->busy_poll_usecs); 404 405 if (bp_usec) { 406 unsigned long end_time = start_time + bp_usec; 407 unsigned long now = busy_loop_current_time(); 408 409 return time_after(now, end_time); 410 } else { 411 return busy_loop_timeout(start_time); 412 } 413 } 414 415 static bool ep_busy_loop_on(struct eventpoll *ep) 416 { 417 return !!READ_ONCE(ep->busy_poll_usecs) || 418 READ_ONCE(ep->prefer_busy_poll) || 419 net_busy_loop_on(); 420 } 421 422 static bool ep_busy_loop_end(void *p, unsigned long start_time) 423 { 424 struct eventpoll *ep = p; 425 426 return ep_events_available(ep) || busy_loop_ep_timeout(start_time, ep); 427 } 428 429 /* 430 * Busy poll if globally on and supporting sockets found && no events, 431 * busy loop will return if need_resched or ep_events_available. 432 * 433 * we must do our busy polling with irqs enabled 434 */ 435 static bool ep_busy_loop(struct eventpoll *ep) 436 { 437 unsigned int napi_id = READ_ONCE(ep->napi_id); 438 u16 budget = READ_ONCE(ep->busy_poll_budget); 439 bool prefer_busy_poll = READ_ONCE(ep->prefer_busy_poll); 440 441 if (!budget) 442 budget = BUSY_POLL_BUDGET; 443 444 if (napi_id_valid(napi_id) && ep_busy_loop_on(ep)) { 445 napi_busy_loop(napi_id, ep_busy_loop_end, 446 ep, prefer_busy_poll, budget); 447 if (ep_events_available(ep)) 448 return true; 449 /* 450 * Busy poll timed out. Drop NAPI ID for now, we can add 451 * it back in when we have moved a socket with a valid NAPI 452 * ID onto the ready list. 453 */ 454 if (prefer_busy_poll) 455 napi_resume_irqs(napi_id); 456 ep->napi_id = 0; 457 return false; 458 } 459 return false; 460 } 461 462 /* 463 * Set epoll busy poll NAPI ID from sk. 464 */ 465 static inline void ep_set_busy_poll_napi_id(struct epitem *epi) 466 { 467 struct eventpoll *ep = epi->ep; 468 unsigned int napi_id; 469 struct socket *sock; 470 struct sock *sk; 471 472 if (!ep_busy_loop_on(ep)) 473 return; 474 475 sock = sock_from_file(epi->ffd.file); 476 if (!sock) 477 return; 478 479 sk = sock->sk; 480 if (!sk) 481 return; 482 483 napi_id = READ_ONCE(sk->sk_napi_id); 484 485 /* Non-NAPI IDs can be rejected 486 * or 487 * Nothing to do if we already have this ID 488 */ 489 if (!napi_id_valid(napi_id) || napi_id == ep->napi_id) 490 return; 491 492 /* record NAPI ID for use in next busy poll */ 493 ep->napi_id = napi_id; 494 } 495 496 static long ep_eventpoll_bp_ioctl(struct file *file, unsigned int cmd, 497 unsigned long arg) 498 { 499 struct eventpoll *ep = file->private_data; 500 void __user *uarg = (void __user *)arg; 501 struct epoll_params epoll_params; 502 503 switch (cmd) { 504 case EPIOCSPARAMS: 505 if (copy_from_user(&epoll_params, uarg, sizeof(epoll_params))) 506 return -EFAULT; 507 508 /* pad byte must be zero */ 509 if (epoll_params.__pad) 510 return -EINVAL; 511 512 if (epoll_params.busy_poll_usecs > S32_MAX) 513 return -EINVAL; 514 515 if (epoll_params.prefer_busy_poll > 1) 516 return -EINVAL; 517 518 if (epoll_params.busy_poll_budget > NAPI_POLL_WEIGHT && 519 !capable(CAP_NET_ADMIN)) 520 return -EPERM; 521 522 WRITE_ONCE(ep->busy_poll_usecs, epoll_params.busy_poll_usecs); 523 WRITE_ONCE(ep->busy_poll_budget, epoll_params.busy_poll_budget); 524 WRITE_ONCE(ep->prefer_busy_poll, epoll_params.prefer_busy_poll); 525 return 0; 526 case EPIOCGPARAMS: 527 memset(&epoll_params, 0, sizeof(epoll_params)); 528 epoll_params.busy_poll_usecs = READ_ONCE(ep->busy_poll_usecs); 529 epoll_params.busy_poll_budget = READ_ONCE(ep->busy_poll_budget); 530 epoll_params.prefer_busy_poll = READ_ONCE(ep->prefer_busy_poll); 531 if (copy_to_user(uarg, &epoll_params, sizeof(epoll_params))) 532 return -EFAULT; 533 return 0; 534 default: 535 return -ENOIOCTLCMD; 536 } 537 } 538 539 static void ep_suspend_napi_irqs(struct eventpoll *ep) 540 { 541 unsigned int napi_id = READ_ONCE(ep->napi_id); 542 543 if (napi_id_valid(napi_id) && READ_ONCE(ep->prefer_busy_poll)) 544 napi_suspend_irqs(napi_id); 545 } 546 547 static void ep_resume_napi_irqs(struct eventpoll *ep) 548 { 549 unsigned int napi_id = READ_ONCE(ep->napi_id); 550 551 if (napi_id_valid(napi_id) && READ_ONCE(ep->prefer_busy_poll)) 552 napi_resume_irqs(napi_id); 553 } 554 555 #else 556 557 static inline bool ep_busy_loop(struct eventpoll *ep) 558 { 559 return false; 560 } 561 562 static inline void ep_set_busy_poll_napi_id(struct epitem *epi) 563 { 564 } 565 566 static long ep_eventpoll_bp_ioctl(struct file *file, unsigned int cmd, 567 unsigned long arg) 568 { 569 return -EOPNOTSUPP; 570 } 571 572 static void ep_suspend_napi_irqs(struct eventpoll *ep) 573 { 574 } 575 576 static void ep_resume_napi_irqs(struct eventpoll *ep) 577 { 578 } 579 580 #endif /* CONFIG_NET_RX_BUSY_POLL */ 581 582 /* 583 * As described in commit 0ccf831cb lockdep: annotate epoll 584 * the use of wait queues used by epoll is done in a very controlled 585 * manner. Wake ups can nest inside each other, but are never done 586 * with the same locking. For example: 587 * 588 * dfd = socket(...); 589 * efd1 = epoll_create(); 590 * efd2 = epoll_create(); 591 * epoll_ctl(efd1, EPOLL_CTL_ADD, dfd, ...); 592 * epoll_ctl(efd2, EPOLL_CTL_ADD, efd1, ...); 593 * 594 * When a packet arrives to the device underneath "dfd", the net code will 595 * issue a wake_up() on its poll wake list. Epoll (efd1) has installed a 596 * callback wakeup entry on that queue, and the wake_up() performed by the 597 * "dfd" net code will end up in ep_poll_callback(). At this point epoll 598 * (efd1) notices that it may have some event ready, so it needs to wake up 599 * the waiters on its poll wait list (efd2). So it calls ep_poll_safewake() 600 * that ends up in another wake_up(), after having checked about the 601 * recursion constraints. That are, no more than EP_MAX_NESTS, to avoid 602 * stack blasting. 603 * 604 * When CONFIG_DEBUG_LOCK_ALLOC is enabled, make sure lockdep can handle 605 * this special case of epoll. 606 */ 607 #ifdef CONFIG_DEBUG_LOCK_ALLOC 608 609 static void ep_poll_safewake(struct eventpoll *ep, struct epitem *epi, 610 unsigned pollflags) 611 { 612 struct eventpoll *ep_src; 613 unsigned long flags; 614 u8 nests = 0; 615 616 /* 617 * To set the subclass or nesting level for spin_lock_irqsave_nested() 618 * it might be natural to create a per-cpu nest count. However, since 619 * we can recurse on ep->poll_wait.lock, and a non-raw spinlock can 620 * schedule() in the -rt kernel, the per-cpu variable are no longer 621 * protected. Thus, we are introducing a per eventpoll nest field. 622 * If we are not being call from ep_poll_callback(), epi is NULL and 623 * we are at the first level of nesting, 0. Otherwise, we are being 624 * called from ep_poll_callback() and if a previous wakeup source is 625 * not an epoll file itself, we are at depth 1 since the wakeup source 626 * is depth 0. If the wakeup source is a previous epoll file in the 627 * wakeup chain then we use its nests value and record ours as 628 * nests + 1. The previous epoll file nests value is stable since its 629 * already holding its own poll_wait.lock. 630 */ 631 if (epi) { 632 if ((is_file_epoll(epi->ffd.file))) { 633 ep_src = epi->ffd.file->private_data; 634 nests = ep_src->nests; 635 } else { 636 nests = 1; 637 } 638 } 639 spin_lock_irqsave_nested(&ep->poll_wait.lock, flags, nests); 640 ep->nests = nests + 1; 641 wake_up_locked_poll(&ep->poll_wait, EPOLLIN | pollflags); 642 ep->nests = 0; 643 spin_unlock_irqrestore(&ep->poll_wait.lock, flags); 644 } 645 646 #else 647 648 static void ep_poll_safewake(struct eventpoll *ep, struct epitem *epi, 649 __poll_t pollflags) 650 { 651 wake_up_poll(&ep->poll_wait, EPOLLIN | pollflags); 652 } 653 654 #endif 655 656 static void ep_remove_wait_queue(struct eppoll_entry *pwq) 657 { 658 wait_queue_head_t *whead; 659 660 rcu_read_lock(); 661 /* 662 * If it is cleared by POLLFREE, it should be rcu-safe. 663 * If we read NULL we need a barrier paired with 664 * smp_store_release() in ep_poll_callback(), otherwise 665 * we rely on whead->lock. 666 */ 667 whead = smp_load_acquire(&pwq->whead); 668 if (whead) 669 remove_wait_queue(whead, &pwq->wait); 670 rcu_read_unlock(); 671 } 672 673 /* 674 * This function unregisters poll callbacks from the associated file 675 * descriptor. Must be called with "mtx" held. 676 */ 677 static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi) 678 { 679 struct eppoll_entry **p = &epi->pwqlist; 680 struct eppoll_entry *pwq; 681 682 while ((pwq = *p) != NULL) { 683 *p = pwq->next; 684 ep_remove_wait_queue(pwq); 685 kmem_cache_free(pwq_cache, pwq); 686 } 687 } 688 689 /* call only when ep->mtx is held */ 690 static inline struct wakeup_source *ep_wakeup_source(struct epitem *epi) 691 { 692 return rcu_dereference_check(epi->ws, lockdep_is_held(&epi->ep->mtx)); 693 } 694 695 /* call only when ep->mtx is held */ 696 static inline void ep_pm_stay_awake(struct epitem *epi) 697 { 698 struct wakeup_source *ws = ep_wakeup_source(epi); 699 700 if (ws) 701 __pm_stay_awake(ws); 702 } 703 704 static inline bool ep_has_wakeup_source(struct epitem *epi) 705 { 706 return rcu_access_pointer(epi->ws) ? true : false; 707 } 708 709 /* call when ep->mtx cannot be held (ep_poll_callback) */ 710 static inline void ep_pm_stay_awake_rcu(struct epitem *epi) 711 { 712 struct wakeup_source *ws; 713 714 rcu_read_lock(); 715 ws = rcu_dereference(epi->ws); 716 if (ws) 717 __pm_stay_awake(ws); 718 rcu_read_unlock(); 719 } 720 721 722 /* 723 * ep->mutex needs to be held because we could be hit by 724 * eventpoll_release_file() and epoll_ctl(). 725 */ 726 static void ep_start_scan(struct eventpoll *ep, struct list_head *txlist) 727 { 728 /* 729 * Steal the ready list, and re-init the original one to the 730 * empty list. Also, set ep->ovflist to NULL so that events 731 * happening while looping w/out locks, are not lost. We cannot 732 * have the poll callback to queue directly on ep->rdllist, 733 * because we want the "sproc" callback to be able to do it 734 * in a lockless way. 735 */ 736 lockdep_assert_irqs_enabled(); 737 spin_lock_irq(&ep->lock); 738 list_splice_init(&ep->rdllist, txlist); 739 WRITE_ONCE(ep->ovflist, NULL); 740 spin_unlock_irq(&ep->lock); 741 } 742 743 static void ep_done_scan(struct eventpoll *ep, 744 struct list_head *txlist) 745 { 746 struct epitem *epi, *nepi; 747 748 spin_lock_irq(&ep->lock); 749 /* 750 * During the time we spent inside the "sproc" callback, some 751 * other events might have been queued by the poll callback. 752 * We re-insert them inside the main ready-list here. 753 */ 754 for (nepi = READ_ONCE(ep->ovflist); (epi = nepi) != NULL; 755 nepi = epi->next, epi->next = EP_UNACTIVE_PTR) { 756 /* 757 * We need to check if the item is already in the list. 758 * During the "sproc" callback execution time, items are 759 * queued into ->ovflist but the "txlist" might already 760 * contain them, and the list_splice() below takes care of them. 761 */ 762 if (!ep_is_linked(epi)) { 763 /* 764 * ->ovflist is LIFO, so we have to reverse it in order 765 * to keep in FIFO. 766 */ 767 list_add(&epi->rdllink, &ep->rdllist); 768 ep_pm_stay_awake(epi); 769 } 770 } 771 /* 772 * We need to set back ep->ovflist to EP_UNACTIVE_PTR, so that after 773 * releasing the lock, events will be queued in the normal way inside 774 * ep->rdllist. 775 */ 776 WRITE_ONCE(ep->ovflist, EP_UNACTIVE_PTR); 777 778 /* 779 * Quickly re-inject items left on "txlist". 780 */ 781 list_splice(txlist, &ep->rdllist); 782 __pm_relax(ep->ws); 783 784 if (!list_empty(&ep->rdllist)) { 785 if (waitqueue_active(&ep->wq)) 786 wake_up(&ep->wq); 787 } 788 789 spin_unlock_irq(&ep->lock); 790 } 791 792 static void ep_get(struct eventpoll *ep) 793 { 794 refcount_inc(&ep->refcount); 795 } 796 797 /* 798 * Returns true if the event poll can be disposed 799 */ 800 static bool ep_refcount_dec_and_test(struct eventpoll *ep) 801 { 802 if (!refcount_dec_and_test(&ep->refcount)) 803 return false; 804 805 WARN_ON_ONCE(!RB_EMPTY_ROOT(&ep->rbr.rb_root)); 806 return true; 807 } 808 809 static void ep_free(struct eventpoll *ep) 810 { 811 ep_resume_napi_irqs(ep); 812 mutex_destroy(&ep->mtx); 813 free_uid(ep->user); 814 wakeup_source_unregister(ep->ws); 815 /* ep_get_upwards_depth_proc() may still hold epi->ep under RCU */ 816 kfree_rcu(ep, rcu); 817 } 818 819 /* 820 * The ffd.file pointer may be in the process of being torn down due to 821 * being closed, but we may not have finished eventpoll_release() yet. 822 * 823 * Normally, even with the atomic_long_inc_not_zero, the file may have 824 * been free'd and then gotten re-allocated to something else (since 825 * files are not RCU-delayed, they are SLAB_TYPESAFE_BY_RCU). 826 * 827 * But for epoll, users hold the ep->mtx mutex, and as such any file in 828 * the process of being free'd will block in eventpoll_release_file() 829 * and thus the underlying file allocation will not be free'd, and the 830 * file re-use cannot happen. 831 * 832 * For the same reason we can avoid a rcu_read_lock() around the 833 * operation - 'ffd.file' cannot go away even if the refcount has 834 * reached zero (but we must still not call out to ->poll() functions 835 * etc). 836 */ 837 static struct file *epi_fget(const struct epitem *epi) 838 { 839 struct file *file; 840 841 file = epi->ffd.file; 842 if (!file_ref_get(&file->f_ref)) 843 file = NULL; 844 return file; 845 } 846 847 /* 848 * Takes &file->f_lock; returns with it released. 849 */ 850 static void ep_remove_file(struct eventpoll *ep, struct epitem *epi, 851 struct file *file) 852 { 853 struct epitems_head *to_free = NULL; 854 struct hlist_head *head; 855 856 lockdep_assert_held(&ep->mtx); 857 858 spin_lock(&file->f_lock); 859 head = file->f_ep; 860 if (hlist_is_singular_node(&epi->fllink, head)) { 861 /* See eventpoll_release() for details. */ 862 WRITE_ONCE(file->f_ep, NULL); 863 if (!is_file_epoll(file)) { 864 struct epitems_head *v; 865 v = container_of(head, struct epitems_head, epitems); 866 if (!smp_load_acquire(&v->next)) 867 to_free = v; 868 } 869 } 870 hlist_del_rcu(&epi->fllink); 871 spin_unlock(&file->f_lock); 872 free_ephead(to_free); 873 } 874 875 static void ep_remove_epi(struct eventpoll *ep, struct epitem *epi) 876 { 877 lockdep_assert_held(&ep->mtx); 878 879 rb_erase_cached(&epi->rbn, &ep->rbr); 880 881 spin_lock_irq(&ep->lock); 882 if (ep_is_linked(epi)) 883 list_del_init(&epi->rdllink); 884 spin_unlock_irq(&ep->lock); 885 886 wakeup_source_unregister(ep_wakeup_source(epi)); 887 /* 888 * At this point it is safe to free the eventpoll item. Use the union 889 * field epi->rcu, since we are trying to minimize the size of 890 * 'struct epitem'. The 'rbn' field is no longer in use. Protected by 891 * ep->mtx. The rcu read side, reverse_path_check_proc(), does not make 892 * use of the rbn field. 893 */ 894 kfree_rcu(epi, rcu); 895 896 percpu_counter_dec(&ep->user->epoll_watches); 897 } 898 899 /* 900 * ep_remove variant for callers owing an additional reference to the ep 901 */ 902 static void ep_remove(struct eventpoll *ep, struct epitem *epi) 903 { 904 struct file *file __free(fput) = NULL; 905 906 lockdep_assert_irqs_enabled(); 907 lockdep_assert_held(&ep->mtx); 908 909 ep_unregister_pollwait(ep, epi); 910 911 /* 912 * If we manage to grab a reference it means we're not in 913 * eventpoll_release_file() and aren't going to be: once @file's 914 * refcount has reached zero, file_ref_get() cannot bring it back. 915 */ 916 file = epi_fget(epi); 917 if (!file) 918 return; 919 920 ep_remove_file(ep, epi, file); 921 ep_remove_epi(ep, epi); 922 WARN_ON_ONCE(ep_refcount_dec_and_test(ep)); 923 } 924 925 static void ep_clear_and_put(struct eventpoll *ep) 926 { 927 struct rb_node *rbp, *next; 928 struct epitem *epi; 929 930 /* We need to release all tasks waiting for these file */ 931 if (waitqueue_active(&ep->poll_wait)) 932 ep_poll_safewake(ep, NULL, 0); 933 934 mutex_lock(&ep->mtx); 935 936 /* 937 * Walks through the whole tree by unregistering poll callbacks. 938 */ 939 for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) { 940 epi = rb_entry(rbp, struct epitem, rbn); 941 942 ep_unregister_pollwait(ep, epi); 943 cond_resched(); 944 } 945 946 /* 947 * Walks through the whole tree and try to free each "struct epitem". 948 * Note that ep_remove() will not remove the epitem in case of a 949 * racing eventpoll_release_file(); the latter will do the removal. 950 * At this point we are sure no poll callbacks will be lingering around. 951 * Since we still own a reference to the eventpoll struct, the loop can't 952 * dispose it. 953 */ 954 for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = next) { 955 next = rb_next(rbp); 956 epi = rb_entry(rbp, struct epitem, rbn); 957 ep_remove(ep, epi); 958 cond_resched(); 959 } 960 961 mutex_unlock(&ep->mtx); 962 if (ep_refcount_dec_and_test(ep)) 963 ep_free(ep); 964 } 965 966 static long ep_eventpoll_ioctl(struct file *file, unsigned int cmd, 967 unsigned long arg) 968 { 969 int ret; 970 971 if (!is_file_epoll(file)) 972 return -EINVAL; 973 974 switch (cmd) { 975 case EPIOCSPARAMS: 976 case EPIOCGPARAMS: 977 ret = ep_eventpoll_bp_ioctl(file, cmd, arg); 978 break; 979 default: 980 ret = -EINVAL; 981 break; 982 } 983 984 return ret; 985 } 986 987 static int ep_eventpoll_release(struct inode *inode, struct file *file) 988 { 989 struct eventpoll *ep = file->private_data; 990 991 if (ep) 992 ep_clear_and_put(ep); 993 994 return 0; 995 } 996 997 static __poll_t ep_item_poll(const struct epitem *epi, poll_table *pt, int depth); 998 999 static __poll_t __ep_eventpoll_poll(struct file *file, poll_table *wait, int depth) 1000 { 1001 struct eventpoll *ep = file->private_data; 1002 LIST_HEAD(txlist); 1003 struct epitem *epi, *tmp; 1004 poll_table pt; 1005 __poll_t res = 0; 1006 1007 init_poll_funcptr(&pt, NULL); 1008 1009 /* Insert inside our poll wait queue */ 1010 poll_wait(file, &ep->poll_wait, wait); 1011 1012 /* 1013 * Proceed to find out if wanted events are really available inside 1014 * the ready list. 1015 */ 1016 mutex_lock_nested(&ep->mtx, depth); 1017 ep_start_scan(ep, &txlist); 1018 list_for_each_entry_safe(epi, tmp, &txlist, rdllink) { 1019 if (ep_item_poll(epi, &pt, depth + 1)) { 1020 res = EPOLLIN | EPOLLRDNORM; 1021 break; 1022 } else { 1023 /* 1024 * Item has been dropped into the ready list by the poll 1025 * callback, but it's not actually ready, as far as 1026 * caller requested events goes. We can remove it here. 1027 */ 1028 __pm_relax(ep_wakeup_source(epi)); 1029 list_del_init(&epi->rdllink); 1030 } 1031 } 1032 ep_done_scan(ep, &txlist); 1033 mutex_unlock(&ep->mtx); 1034 return res; 1035 } 1036 1037 /* 1038 * Differs from ep_eventpoll_poll() in that internal callers already have 1039 * the ep->mtx so we need to start from depth=1, such that mutex_lock_nested() 1040 * is correctly annotated. 1041 */ 1042 static __poll_t ep_item_poll(const struct epitem *epi, poll_table *pt, 1043 int depth) 1044 { 1045 struct file *file = epi_fget(epi); 1046 __poll_t res; 1047 1048 /* 1049 * We could return EPOLLERR | EPOLLHUP or something, but let's 1050 * treat this more as "file doesn't exist, poll didn't happen". 1051 */ 1052 if (!file) 1053 return 0; 1054 1055 pt->_key = epi->event.events; 1056 if (!is_file_epoll(file)) 1057 res = vfs_poll(file, pt); 1058 else 1059 res = __ep_eventpoll_poll(file, pt, depth); 1060 fput(file); 1061 return res & epi->event.events; 1062 } 1063 1064 static __poll_t ep_eventpoll_poll(struct file *file, poll_table *wait) 1065 { 1066 return __ep_eventpoll_poll(file, wait, 0); 1067 } 1068 1069 #ifdef CONFIG_PROC_FS 1070 static void ep_show_fdinfo(struct seq_file *m, struct file *f) 1071 { 1072 struct eventpoll *ep = f->private_data; 1073 struct rb_node *rbp; 1074 1075 mutex_lock(&ep->mtx); 1076 for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) { 1077 struct epitem *epi = rb_entry(rbp, struct epitem, rbn); 1078 struct inode *inode = file_inode(epi->ffd.file); 1079 1080 seq_printf(m, "tfd: %8d events: %8x data: %16llx " 1081 " pos:%lli ino:%llx sdev:%x\n", 1082 epi->ffd.fd, epi->event.events, 1083 (long long)epi->event.data, 1084 (long long)epi->ffd.file->f_pos, 1085 inode->i_ino, inode->i_sb->s_dev); 1086 if (seq_has_overflowed(m)) 1087 break; 1088 } 1089 mutex_unlock(&ep->mtx); 1090 } 1091 #endif 1092 1093 /* File callbacks that implement the eventpoll file behaviour */ 1094 static const struct file_operations eventpoll_fops = { 1095 #ifdef CONFIG_PROC_FS 1096 .show_fdinfo = ep_show_fdinfo, 1097 #endif 1098 .release = ep_eventpoll_release, 1099 .poll = ep_eventpoll_poll, 1100 .llseek = noop_llseek, 1101 .unlocked_ioctl = ep_eventpoll_ioctl, 1102 .compat_ioctl = compat_ptr_ioctl, 1103 }; 1104 1105 /* 1106 * This is called from eventpoll_release() to unlink files from the eventpoll 1107 * interface. We need to have this facility to cleanup correctly files that are 1108 * closed without being removed from the eventpoll interface. 1109 */ 1110 void eventpoll_release_file(struct file *file) 1111 { 1112 struct eventpoll *ep; 1113 struct epitem *epi; 1114 1115 /* 1116 * A concurrent ep_remove() cannot outrace us: it pins @file via 1117 * epi_fget(), which fails once __fput() has dropped the refcount 1118 * to zero -- the path we're on. So any racing ep_remove() bails 1119 * and leaves the epi for us to clean up here. 1120 */ 1121 again: 1122 spin_lock(&file->f_lock); 1123 if (file->f_ep && file->f_ep->first) { 1124 epi = hlist_entry(file->f_ep->first, struct epitem, fllink); 1125 spin_unlock(&file->f_lock); 1126 1127 /* 1128 * ep access is safe as we still own a reference to the ep 1129 * struct 1130 */ 1131 ep = epi->ep; 1132 mutex_lock(&ep->mtx); 1133 1134 ep_unregister_pollwait(ep, epi); 1135 1136 ep_remove_file(ep, epi, file); 1137 ep_remove_epi(ep, epi); 1138 1139 mutex_unlock(&ep->mtx); 1140 1141 if (ep_refcount_dec_and_test(ep)) 1142 ep_free(ep); 1143 goto again; 1144 } 1145 spin_unlock(&file->f_lock); 1146 } 1147 1148 static int ep_alloc(struct eventpoll **pep) 1149 { 1150 struct eventpoll *ep; 1151 1152 ep = kzalloc_obj(*ep); 1153 if (unlikely(!ep)) 1154 return -ENOMEM; 1155 1156 mutex_init(&ep->mtx); 1157 spin_lock_init(&ep->lock); 1158 init_waitqueue_head(&ep->wq); 1159 init_waitqueue_head(&ep->poll_wait); 1160 INIT_LIST_HEAD(&ep->rdllist); 1161 ep->rbr = RB_ROOT_CACHED; 1162 ep->ovflist = EP_UNACTIVE_PTR; 1163 ep->user = get_current_user(); 1164 refcount_set(&ep->refcount, 1); 1165 1166 *pep = ep; 1167 1168 return 0; 1169 } 1170 1171 /* 1172 * Search the file inside the eventpoll tree. The RB tree operations 1173 * are protected by the "mtx" mutex, and ep_find() must be called with 1174 * "mtx" held. 1175 */ 1176 static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd) 1177 { 1178 int kcmp; 1179 struct rb_node *rbp; 1180 struct epitem *epi, *epir = NULL; 1181 struct epoll_filefd ffd; 1182 1183 ep_set_ffd(&ffd, file, fd); 1184 for (rbp = ep->rbr.rb_root.rb_node; rbp; ) { 1185 epi = rb_entry(rbp, struct epitem, rbn); 1186 kcmp = ep_cmp_ffd(&ffd, &epi->ffd); 1187 if (kcmp > 0) 1188 rbp = rbp->rb_right; 1189 else if (kcmp < 0) 1190 rbp = rbp->rb_left; 1191 else { 1192 epir = epi; 1193 break; 1194 } 1195 } 1196 1197 return epir; 1198 } 1199 1200 #ifdef CONFIG_KCMP 1201 static struct epitem *ep_find_tfd(struct eventpoll *ep, int tfd, unsigned long toff) 1202 { 1203 struct rb_node *rbp; 1204 struct epitem *epi; 1205 1206 for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) { 1207 epi = rb_entry(rbp, struct epitem, rbn); 1208 if (epi->ffd.fd == tfd) { 1209 if (toff == 0) 1210 return epi; 1211 else 1212 toff--; 1213 } 1214 cond_resched(); 1215 } 1216 1217 return NULL; 1218 } 1219 1220 struct file *get_epoll_tfile_raw_ptr(struct file *file, int tfd, 1221 unsigned long toff) 1222 { 1223 struct file *file_raw; 1224 struct eventpoll *ep; 1225 struct epitem *epi; 1226 1227 if (!is_file_epoll(file)) 1228 return ERR_PTR(-EINVAL); 1229 1230 ep = file->private_data; 1231 1232 mutex_lock(&ep->mtx); 1233 epi = ep_find_tfd(ep, tfd, toff); 1234 if (epi) 1235 file_raw = epi->ffd.file; 1236 else 1237 file_raw = ERR_PTR(-ENOENT); 1238 mutex_unlock(&ep->mtx); 1239 1240 return file_raw; 1241 } 1242 #endif /* CONFIG_KCMP */ 1243 1244 /* 1245 * This is the callback that is passed to the wait queue wakeup 1246 * mechanism. It is called by the stored file descriptors when they 1247 * have events to report. 1248 */ 1249 static int ep_poll_callback(wait_queue_entry_t *wait, unsigned mode, int sync, void *key) 1250 { 1251 int pwake = 0; 1252 struct epitem *epi = ep_item_from_wait(wait); 1253 struct eventpoll *ep = epi->ep; 1254 __poll_t pollflags = key_to_poll(key); 1255 unsigned long flags; 1256 int ewake = 0; 1257 1258 spin_lock_irqsave(&ep->lock, flags); 1259 1260 ep_set_busy_poll_napi_id(epi); 1261 1262 /* 1263 * If the event mask does not contain any poll(2) event, we consider the 1264 * descriptor to be disabled. This condition is likely the effect of the 1265 * EPOLLONESHOT bit that disables the descriptor when an event is received, 1266 * until the next EPOLL_CTL_MOD will be issued. 1267 */ 1268 if (!(epi->event.events & ~EP_PRIVATE_BITS)) 1269 goto out_unlock; 1270 1271 /* 1272 * Check the events coming with the callback. At this stage, not 1273 * every device reports the events in the "key" parameter of the 1274 * callback. We need to be able to handle both cases here, hence the 1275 * test for "key" != NULL before the event match test. 1276 */ 1277 if (pollflags && !(pollflags & epi->event.events)) 1278 goto out_unlock; 1279 1280 /* 1281 * If we are transferring events to userspace, we can hold no locks 1282 * (because we're accessing user memory, and because of linux f_op->poll() 1283 * semantics). All the events that happen during that period of time are 1284 * chained in ep->ovflist and requeued later on. 1285 */ 1286 if (READ_ONCE(ep->ovflist) != EP_UNACTIVE_PTR) { 1287 if (epi->next == EP_UNACTIVE_PTR) { 1288 epi->next = READ_ONCE(ep->ovflist); 1289 WRITE_ONCE(ep->ovflist, epi); 1290 ep_pm_stay_awake_rcu(epi); 1291 } 1292 } else if (!ep_is_linked(epi)) { 1293 /* In the usual case, add event to ready list. */ 1294 list_add_tail(&epi->rdllink, &ep->rdllist); 1295 ep_pm_stay_awake_rcu(epi); 1296 } 1297 1298 /* 1299 * Wake up ( if active ) both the eventpoll wait list and the ->poll() 1300 * wait list. 1301 */ 1302 if (waitqueue_active(&ep->wq)) { 1303 if ((epi->event.events & EPOLLEXCLUSIVE) && 1304 !(pollflags & POLLFREE)) { 1305 switch (pollflags & EPOLLINOUT_BITS) { 1306 case EPOLLIN: 1307 if (epi->event.events & EPOLLIN) 1308 ewake = 1; 1309 break; 1310 case EPOLLOUT: 1311 if (epi->event.events & EPOLLOUT) 1312 ewake = 1; 1313 break; 1314 case 0: 1315 ewake = 1; 1316 break; 1317 } 1318 } 1319 if (sync) 1320 wake_up_sync(&ep->wq); 1321 else 1322 wake_up(&ep->wq); 1323 } 1324 if (waitqueue_active(&ep->poll_wait)) 1325 pwake++; 1326 1327 out_unlock: 1328 spin_unlock_irqrestore(&ep->lock, flags); 1329 1330 /* We have to call this outside the lock */ 1331 if (pwake) 1332 ep_poll_safewake(ep, epi, pollflags & EPOLL_URING_WAKE); 1333 1334 if (!(epi->event.events & EPOLLEXCLUSIVE)) 1335 ewake = 1; 1336 1337 if (pollflags & POLLFREE) { 1338 /* 1339 * If we race with ep_remove_wait_queue() it can miss 1340 * ->whead = NULL and do another remove_wait_queue() after 1341 * us, so we can't use __remove_wait_queue(). 1342 */ 1343 list_del_init(&wait->entry); 1344 /* 1345 * ->whead != NULL protects us from the race with 1346 * ep_clear_and_put() or ep_remove(), ep_remove_wait_queue() 1347 * takes whead->lock held by the caller. Once we nullify it, 1348 * nothing protects ep/epi or even wait. 1349 */ 1350 smp_store_release(&ep_pwq_from_wait(wait)->whead, NULL); 1351 } 1352 1353 return ewake; 1354 } 1355 1356 /* 1357 * This is the callback that is used to add our wait queue to the 1358 * target file wakeup lists. 1359 */ 1360 static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead, 1361 poll_table *pt) 1362 { 1363 struct ep_pqueue *epq = container_of(pt, struct ep_pqueue, pt); 1364 struct epitem *epi = epq->epi; 1365 struct eppoll_entry *pwq; 1366 1367 if (unlikely(!epi)) // an earlier allocation has failed 1368 return; 1369 1370 pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL); 1371 if (unlikely(!pwq)) { 1372 epq->epi = NULL; 1373 return; 1374 } 1375 1376 init_waitqueue_func_entry(&pwq->wait, ep_poll_callback); 1377 pwq->whead = whead; 1378 pwq->base = epi; 1379 if (epi->event.events & EPOLLEXCLUSIVE) 1380 add_wait_queue_exclusive(whead, &pwq->wait); 1381 else 1382 add_wait_queue(whead, &pwq->wait); 1383 pwq->next = epi->pwqlist; 1384 epi->pwqlist = pwq; 1385 } 1386 1387 static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi) 1388 { 1389 int kcmp; 1390 struct rb_node **p = &ep->rbr.rb_root.rb_node, *parent = NULL; 1391 struct epitem *epic; 1392 bool leftmost = true; 1393 1394 while (*p) { 1395 parent = *p; 1396 epic = rb_entry(parent, struct epitem, rbn); 1397 kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd); 1398 if (kcmp > 0) { 1399 p = &parent->rb_right; 1400 leftmost = false; 1401 } else 1402 p = &parent->rb_left; 1403 } 1404 rb_link_node(&epi->rbn, parent, p); 1405 rb_insert_color_cached(&epi->rbn, &ep->rbr, leftmost); 1406 } 1407 1408 1409 1410 #define PATH_ARR_SIZE 5 1411 /* 1412 * These are the number paths of length 1 to 5, that we are allowing to emanate 1413 * from a single file of interest. For example, we allow 1000 paths of length 1414 * 1, to emanate from each file of interest. This essentially represents the 1415 * potential wakeup paths, which need to be limited in order to avoid massive 1416 * uncontrolled wakeup storms. The common use case should be a single ep which 1417 * is connected to n file sources. In this case each file source has 1 path 1418 * of length 1. Thus, the numbers below should be more than sufficient. These 1419 * path limits are enforced during an EPOLL_CTL_ADD operation, since a modify 1420 * and delete can't add additional paths. Protected by the epnested_mutex. 1421 */ 1422 static const int path_limits[PATH_ARR_SIZE] = { 1000, 500, 100, 50, 10 }; 1423 static int path_count[PATH_ARR_SIZE]; 1424 1425 static int path_count_inc(int nests) 1426 { 1427 /* Allow an arbitrary number of depth 1 paths */ 1428 if (nests == 0) 1429 return 0; 1430 1431 if (++path_count[nests] > path_limits[nests]) 1432 return -1; 1433 return 0; 1434 } 1435 1436 static void path_count_init(void) 1437 { 1438 int i; 1439 1440 for (i = 0; i < PATH_ARR_SIZE; i++) 1441 path_count[i] = 0; 1442 } 1443 1444 static int reverse_path_check_proc(struct hlist_head *refs, int depth) 1445 { 1446 int error = 0; 1447 struct epitem *epi; 1448 1449 if (depth > EP_MAX_NESTS) /* too deep nesting */ 1450 return -1; 1451 1452 /* CTL_DEL can remove links here, but that can't increase our count */ 1453 hlist_for_each_entry_rcu(epi, refs, fllink) { 1454 struct hlist_head *refs = &epi->ep->refs; 1455 if (hlist_empty(refs)) 1456 error = path_count_inc(depth); 1457 else 1458 error = reverse_path_check_proc(refs, depth + 1); 1459 if (error != 0) 1460 break; 1461 } 1462 return error; 1463 } 1464 1465 /** 1466 * reverse_path_check - The tfile_check_list is list of epitem_head, which have 1467 * links that are proposed to be newly added. We need to 1468 * make sure that those added links don't add too many 1469 * paths such that we will spend all our time waking up 1470 * eventpoll objects. 1471 * 1472 * Return: %zero if the proposed links don't create too many paths, 1473 * %-1 otherwise. 1474 */ 1475 static int reverse_path_check(void) 1476 { 1477 struct epitems_head *p; 1478 1479 for (p = tfile_check_list; p != EP_UNACTIVE_PTR; p = p->next) { 1480 int error; 1481 path_count_init(); 1482 rcu_read_lock(); 1483 error = reverse_path_check_proc(&p->epitems, 0); 1484 rcu_read_unlock(); 1485 if (error) 1486 return error; 1487 } 1488 return 0; 1489 } 1490 1491 static int ep_create_wakeup_source(struct epitem *epi) 1492 { 1493 struct name_snapshot n; 1494 struct wakeup_source *ws; 1495 1496 if (!epi->ep->ws) { 1497 epi->ep->ws = wakeup_source_register(NULL, "eventpoll"); 1498 if (!epi->ep->ws) 1499 return -ENOMEM; 1500 } 1501 1502 take_dentry_name_snapshot(&n, epi->ffd.file->f_path.dentry); 1503 ws = wakeup_source_register(NULL, n.name.name); 1504 release_dentry_name_snapshot(&n); 1505 1506 if (!ws) 1507 return -ENOMEM; 1508 rcu_assign_pointer(epi->ws, ws); 1509 1510 return 0; 1511 } 1512 1513 /* rare code path, only used when EPOLL_CTL_MOD removes a wakeup source */ 1514 static noinline void ep_destroy_wakeup_source(struct epitem *epi) 1515 { 1516 struct wakeup_source *ws = ep_wakeup_source(epi); 1517 1518 RCU_INIT_POINTER(epi->ws, NULL); 1519 1520 /* 1521 * wait for ep_pm_stay_awake_rcu to finish, synchronize_rcu is 1522 * used internally by wakeup_source_remove, too (called by 1523 * wakeup_source_unregister), so we cannot use call_rcu 1524 */ 1525 synchronize_rcu(); 1526 wakeup_source_unregister(ws); 1527 } 1528 1529 static int attach_epitem(struct file *file, struct epitem *epi) 1530 { 1531 struct epitems_head *to_free = NULL; 1532 struct hlist_head *head = NULL; 1533 struct eventpoll *ep = NULL; 1534 1535 if (is_file_epoll(file)) 1536 ep = file->private_data; 1537 1538 if (ep) { 1539 head = &ep->refs; 1540 } else if (!READ_ONCE(file->f_ep)) { 1541 allocate: 1542 to_free = kmem_cache_zalloc(ephead_cache, GFP_KERNEL); 1543 if (!to_free) 1544 return -ENOMEM; 1545 head = &to_free->epitems; 1546 } 1547 spin_lock(&file->f_lock); 1548 if (!file->f_ep) { 1549 if (unlikely(!head)) { 1550 spin_unlock(&file->f_lock); 1551 goto allocate; 1552 } 1553 /* See eventpoll_release() for details. */ 1554 WRITE_ONCE(file->f_ep, head); 1555 to_free = NULL; 1556 } 1557 hlist_add_head_rcu(&epi->fllink, file->f_ep); 1558 spin_unlock(&file->f_lock); 1559 free_ephead(to_free); 1560 return 0; 1561 } 1562 1563 /* 1564 * Must be called with "mtx" held. 1565 */ 1566 static int ep_insert(struct eventpoll *ep, const struct epoll_event *event, 1567 struct file *tfile, int fd, int full_check) 1568 { 1569 int error, pwake = 0; 1570 __poll_t revents; 1571 struct epitem *epi; 1572 struct ep_pqueue epq; 1573 struct eventpoll *tep = NULL; 1574 1575 if (is_file_epoll(tfile)) 1576 tep = tfile->private_data; 1577 1578 lockdep_assert_irqs_enabled(); 1579 1580 if (unlikely(percpu_counter_compare(&ep->user->epoll_watches, 1581 max_user_watches) >= 0)) 1582 return -ENOSPC; 1583 percpu_counter_inc(&ep->user->epoll_watches); 1584 1585 if (!(epi = kmem_cache_zalloc(epi_cache, GFP_KERNEL))) { 1586 percpu_counter_dec(&ep->user->epoll_watches); 1587 return -ENOMEM; 1588 } 1589 1590 /* Item initialization follow here ... */ 1591 INIT_LIST_HEAD(&epi->rdllink); 1592 epi->ep = ep; 1593 ep_set_ffd(&epi->ffd, tfile, fd); 1594 epi->event = *event; 1595 epi->next = EP_UNACTIVE_PTR; 1596 1597 if (tep) 1598 mutex_lock_nested(&tep->mtx, 1); 1599 /* Add the current item to the list of active epoll hook for this file */ 1600 if (unlikely(attach_epitem(tfile, epi) < 0)) { 1601 if (tep) 1602 mutex_unlock(&tep->mtx); 1603 kmem_cache_free(epi_cache, epi); 1604 percpu_counter_dec(&ep->user->epoll_watches); 1605 return -ENOMEM; 1606 } 1607 1608 if (full_check && !tep) 1609 list_file(tfile); 1610 1611 /* 1612 * Add the current item to the RB tree. All RB tree operations are 1613 * protected by "mtx", and ep_insert() is called with "mtx" held. 1614 */ 1615 ep_rbtree_insert(ep, epi); 1616 if (tep) 1617 mutex_unlock(&tep->mtx); 1618 1619 /* 1620 * ep_remove() calls in the later error paths can't lead to 1621 * ep_free() as the ep file itself still holds an ep reference. 1622 */ 1623 ep_get(ep); 1624 1625 /* now check if we've created too many backpaths */ 1626 if (unlikely(full_check && reverse_path_check())) { 1627 ep_remove(ep, epi); 1628 return -EINVAL; 1629 } 1630 1631 if (epi->event.events & EPOLLWAKEUP) { 1632 error = ep_create_wakeup_source(epi); 1633 if (error) { 1634 ep_remove(ep, epi); 1635 return error; 1636 } 1637 } 1638 1639 /* Initialize the poll table using the queue callback */ 1640 epq.epi = epi; 1641 init_poll_funcptr(&epq.pt, ep_ptable_queue_proc); 1642 1643 /* 1644 * Attach the item to the poll hooks and get current event bits. 1645 * We can safely use the file* here because its usage count has 1646 * been increased by the caller of this function. Note that after 1647 * this operation completes, the poll callback can start hitting 1648 * the new item. 1649 */ 1650 revents = ep_item_poll(epi, &epq.pt, 1); 1651 1652 /* 1653 * We have to check if something went wrong during the poll wait queue 1654 * install process. Namely an allocation for a wait queue failed due 1655 * high memory pressure. 1656 */ 1657 if (unlikely(!epq.epi)) { 1658 ep_remove(ep, epi); 1659 return -ENOMEM; 1660 } 1661 1662 /* We have to drop the new item inside our item list to keep track of it */ 1663 spin_lock_irq(&ep->lock); 1664 1665 /* record NAPI ID of new item if present */ 1666 ep_set_busy_poll_napi_id(epi); 1667 1668 /* If the file is already "ready" we drop it inside the ready list */ 1669 if (revents && !ep_is_linked(epi)) { 1670 list_add_tail(&epi->rdllink, &ep->rdllist); 1671 ep_pm_stay_awake(epi); 1672 1673 /* Notify waiting tasks that events are available */ 1674 if (waitqueue_active(&ep->wq)) 1675 wake_up(&ep->wq); 1676 if (waitqueue_active(&ep->poll_wait)) 1677 pwake++; 1678 } 1679 1680 spin_unlock_irq(&ep->lock); 1681 1682 /* We have to call this outside the lock */ 1683 if (pwake) 1684 ep_poll_safewake(ep, NULL, 0); 1685 1686 return 0; 1687 } 1688 1689 /* 1690 * Modify the interest event mask by dropping an event if the new mask 1691 * has a match in the current file status. Must be called with "mtx" held. 1692 */ 1693 static int ep_modify(struct eventpoll *ep, struct epitem *epi, 1694 const struct epoll_event *event) 1695 { 1696 int pwake = 0; 1697 poll_table pt; 1698 1699 lockdep_assert_irqs_enabled(); 1700 1701 init_poll_funcptr(&pt, NULL); 1702 1703 /* 1704 * Set the new event interest mask before calling f_op->poll(); 1705 * otherwise we might miss an event that happens between the 1706 * f_op->poll() call and the new event set registering. 1707 */ 1708 epi->event.events = event->events; /* need barrier below */ 1709 epi->event.data = event->data; /* protected by mtx */ 1710 if (epi->event.events & EPOLLWAKEUP) { 1711 if (!ep_has_wakeup_source(epi)) 1712 ep_create_wakeup_source(epi); 1713 } else if (ep_has_wakeup_source(epi)) { 1714 ep_destroy_wakeup_source(epi); 1715 } 1716 1717 /* 1718 * The following barrier has two effects: 1719 * 1720 * 1) Flush epi changes above to other CPUs. This ensures 1721 * we do not miss events from ep_poll_callback if an 1722 * event occurs immediately after we call f_op->poll(). 1723 * We need this because we did not take ep->lock while 1724 * changing epi above (but ep_poll_callback does take 1725 * ep->lock). 1726 * 1727 * 2) We also need to ensure we do not miss _past_ events 1728 * when calling f_op->poll(). This barrier also 1729 * pairs with the barrier in wq_has_sleeper (see 1730 * comments for wq_has_sleeper). 1731 * 1732 * This barrier will now guarantee ep_poll_callback or f_op->poll 1733 * (or both) will notice the readiness of an item. 1734 */ 1735 smp_mb(); 1736 1737 /* 1738 * Get current event bits. We can safely use the file* here because 1739 * its usage count has been increased by the caller of this function. 1740 * If the item is "hot" and it is not registered inside the ready 1741 * list, push it inside. 1742 */ 1743 if (ep_item_poll(epi, &pt, 1)) { 1744 spin_lock_irq(&ep->lock); 1745 if (!ep_is_linked(epi)) { 1746 list_add_tail(&epi->rdllink, &ep->rdllist); 1747 ep_pm_stay_awake(epi); 1748 1749 /* Notify waiting tasks that events are available */ 1750 if (waitqueue_active(&ep->wq)) 1751 wake_up(&ep->wq); 1752 if (waitqueue_active(&ep->poll_wait)) 1753 pwake++; 1754 } 1755 spin_unlock_irq(&ep->lock); 1756 } 1757 1758 /* We have to call this outside the lock */ 1759 if (pwake) 1760 ep_poll_safewake(ep, NULL, 0); 1761 1762 return 0; 1763 } 1764 1765 static int ep_send_events(struct eventpoll *ep, 1766 struct epoll_event __user *events, int maxevents) 1767 { 1768 struct epitem *epi, *tmp; 1769 LIST_HEAD(txlist); 1770 poll_table pt; 1771 int res = 0; 1772 1773 /* 1774 * Always short-circuit for fatal signals to allow threads to make a 1775 * timely exit without the chance of finding more events available and 1776 * fetching repeatedly. 1777 */ 1778 if (fatal_signal_pending(current)) 1779 return -EINTR; 1780 1781 init_poll_funcptr(&pt, NULL); 1782 1783 mutex_lock(&ep->mtx); 1784 ep_start_scan(ep, &txlist); 1785 1786 /* 1787 * We can loop without lock because we are passed a task private list. 1788 * Items cannot vanish during the loop we are holding ep->mtx. 1789 */ 1790 list_for_each_entry_safe(epi, tmp, &txlist, rdllink) { 1791 struct wakeup_source *ws; 1792 __poll_t revents; 1793 1794 if (res >= maxevents) 1795 break; 1796 1797 /* 1798 * Activate ep->ws before deactivating epi->ws to prevent 1799 * triggering auto-suspend here (in case we reactive epi->ws 1800 * below). 1801 * 1802 * This could be rearranged to delay the deactivation of epi->ws 1803 * instead, but then epi->ws would temporarily be out of sync 1804 * with ep_is_linked(). 1805 */ 1806 ws = ep_wakeup_source(epi); 1807 if (ws) { 1808 if (ws->active) 1809 __pm_stay_awake(ep->ws); 1810 __pm_relax(ws); 1811 } 1812 1813 list_del_init(&epi->rdllink); 1814 1815 /* 1816 * If the event mask intersect the caller-requested one, 1817 * deliver the event to userspace. Again, we are holding ep->mtx, 1818 * so no operations coming from userspace can change the item. 1819 */ 1820 revents = ep_item_poll(epi, &pt, 1); 1821 if (!revents) 1822 continue; 1823 1824 events = epoll_put_uevent(revents, epi->event.data, events); 1825 if (!events) { 1826 list_add(&epi->rdllink, &txlist); 1827 ep_pm_stay_awake(epi); 1828 if (!res) 1829 res = -EFAULT; 1830 break; 1831 } 1832 res++; 1833 if (epi->event.events & EPOLLONESHOT) 1834 epi->event.events &= EP_PRIVATE_BITS; 1835 else if (!(epi->event.events & EPOLLET)) { 1836 /* 1837 * If this file has been added with Level 1838 * Trigger mode, we need to insert back inside 1839 * the ready list, so that the next call to 1840 * epoll_wait() will check again the events 1841 * availability. At this point, no one can insert 1842 * into ep->rdllist besides us. The epoll_ctl() 1843 * callers are locked out by 1844 * ep_send_events() holding "mtx" and the 1845 * poll callback will queue them in ep->ovflist. 1846 */ 1847 list_add_tail(&epi->rdllink, &ep->rdllist); 1848 ep_pm_stay_awake(epi); 1849 } 1850 } 1851 ep_done_scan(ep, &txlist); 1852 mutex_unlock(&ep->mtx); 1853 1854 return res; 1855 } 1856 1857 static struct timespec64 *ep_timeout_to_timespec(struct timespec64 *to, long ms) 1858 { 1859 struct timespec64 now; 1860 1861 if (ms < 0) 1862 return NULL; 1863 1864 if (!ms) { 1865 to->tv_sec = 0; 1866 to->tv_nsec = 0; 1867 return to; 1868 } 1869 1870 to->tv_sec = ms / MSEC_PER_SEC; 1871 to->tv_nsec = NSEC_PER_MSEC * (ms % MSEC_PER_SEC); 1872 1873 ktime_get_ts64(&now); 1874 *to = timespec64_add_safe(now, *to); 1875 return to; 1876 } 1877 1878 /* 1879 * autoremove_wake_function, but remove even on failure to wake up, because we 1880 * know that default_wake_function/ttwu will only fail if the thread is already 1881 * woken, and in that case the ep_poll loop will remove the entry anyways, not 1882 * try to reuse it. 1883 */ 1884 static int ep_autoremove_wake_function(struct wait_queue_entry *wq_entry, 1885 unsigned int mode, int sync, void *key) 1886 { 1887 int ret = default_wake_function(wq_entry, mode, sync, key); 1888 1889 /* 1890 * Pairs with list_empty_careful in ep_poll, and ensures future loop 1891 * iterations see the cause of this wakeup. 1892 */ 1893 list_del_init_careful(&wq_entry->entry); 1894 return ret; 1895 } 1896 1897 static int ep_try_send_events(struct eventpoll *ep, 1898 struct epoll_event __user *events, int maxevents) 1899 { 1900 int res; 1901 1902 /* 1903 * Try to transfer events to user space. In case we get 0 events and 1904 * there's still timeout left over, we go trying again in search of 1905 * more luck. 1906 */ 1907 res = ep_send_events(ep, events, maxevents); 1908 if (res > 0) 1909 ep_suspend_napi_irqs(ep); 1910 return res; 1911 } 1912 1913 static int ep_schedule_timeout(ktime_t *to) 1914 { 1915 if (to) 1916 return ktime_after(*to, ktime_get()); 1917 else 1918 return 1; 1919 } 1920 1921 /** 1922 * ep_poll - Retrieves ready events, and delivers them to the caller-supplied 1923 * event buffer. 1924 * 1925 * @ep: Pointer to the eventpoll context. 1926 * @events: Pointer to the userspace buffer where the ready events should be 1927 * stored. 1928 * @maxevents: Size (in terms of number of events) of the caller event buffer. 1929 * @timeout: Maximum timeout for the ready events fetch operation, in 1930 * timespec. If the timeout is zero, the function will not block, 1931 * while if the @timeout ptr is NULL, the function will block 1932 * until at least one event has been retrieved (or an error 1933 * occurred). 1934 * 1935 * Return: the number of ready events which have been fetched, or an 1936 * error code, in case of error. 1937 */ 1938 static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events, 1939 int maxevents, struct timespec64 *timeout) 1940 { 1941 int res, eavail, timed_out = 0; 1942 u64 slack = 0; 1943 wait_queue_entry_t wait; 1944 ktime_t expires, *to = NULL; 1945 1946 lockdep_assert_irqs_enabled(); 1947 1948 if (timeout && (timeout->tv_sec | timeout->tv_nsec)) { 1949 slack = select_estimate_accuracy(timeout); 1950 to = &expires; 1951 *to = timespec64_to_ktime(*timeout); 1952 } else if (timeout) { 1953 /* 1954 * Avoid the unnecessary trip to the wait queue loop, if the 1955 * caller specified a non blocking operation. 1956 */ 1957 timed_out = 1; 1958 } 1959 1960 /* 1961 * This call is racy: We may or may not see events that are being added 1962 * to the ready list under the lock (e.g., in IRQ callbacks). For cases 1963 * with a non-zero timeout, this thread will check the ready list under 1964 * lock and will add to the wait queue. For cases with a zero 1965 * timeout, the user by definition should not care and will have to 1966 * recheck again. 1967 */ 1968 eavail = ep_events_available(ep); 1969 1970 while (1) { 1971 if (eavail) { 1972 res = ep_try_send_events(ep, events, maxevents); 1973 if (res) 1974 return res; 1975 } 1976 1977 if (timed_out) 1978 return 0; 1979 1980 eavail = ep_busy_loop(ep); 1981 if (eavail) 1982 continue; 1983 1984 if (signal_pending(current)) 1985 return -EINTR; 1986 1987 /* 1988 * Internally init_wait() uses autoremove_wake_function(), 1989 * thus wait entry is removed from the wait queue on each 1990 * wakeup. Why it is important? In case of several waiters 1991 * each new wakeup will hit the next waiter, giving it the 1992 * chance to harvest new event. Otherwise wakeup can be 1993 * lost. This is also good performance-wise, because on 1994 * normal wakeup path no need to call __remove_wait_queue() 1995 * explicitly, thus ep->lock is not taken, which halts the 1996 * event delivery. 1997 * 1998 * In fact, we now use an even more aggressive function that 1999 * unconditionally removes, because we don't reuse the wait 2000 * entry between loop iterations. This lets us also avoid the 2001 * performance issue if a process is killed, causing all of its 2002 * threads to wake up without being removed normally. 2003 */ 2004 init_wait(&wait); 2005 wait.func = ep_autoremove_wake_function; 2006 2007 spin_lock_irq(&ep->lock); 2008 /* 2009 * Barrierless variant, waitqueue_active() is called under 2010 * the same lock on wakeup ep_poll_callback() side, so it 2011 * is safe to avoid an explicit barrier. 2012 */ 2013 __set_current_state(TASK_INTERRUPTIBLE); 2014 2015 /* 2016 * Do the final check under the lock. ep_start/done_scan() 2017 * plays with two lists (->rdllist and ->ovflist) and there 2018 * is always a race when both lists are empty for short 2019 * period of time although events are pending, so lock is 2020 * important. 2021 */ 2022 eavail = ep_events_available(ep); 2023 if (!eavail) 2024 __add_wait_queue_exclusive(&ep->wq, &wait); 2025 2026 spin_unlock_irq(&ep->lock); 2027 2028 if (!eavail) 2029 timed_out = !ep_schedule_timeout(to) || 2030 !schedule_hrtimeout_range(to, slack, 2031 HRTIMER_MODE_ABS); 2032 __set_current_state(TASK_RUNNING); 2033 2034 /* 2035 * We were woken up, thus go and try to harvest some events. 2036 * If timed out and still on the wait queue, recheck eavail 2037 * carefully under lock, below. 2038 */ 2039 eavail = 1; 2040 2041 if (!list_empty_careful(&wait.entry)) { 2042 spin_lock_irq(&ep->lock); 2043 /* 2044 * If the thread timed out and is not on the wait queue, 2045 * it means that the thread was woken up after its 2046 * timeout expired before it could reacquire the lock. 2047 * Thus, when wait.entry is empty, it needs to harvest 2048 * events. 2049 */ 2050 if (timed_out) 2051 eavail = list_empty(&wait.entry); 2052 __remove_wait_queue(&ep->wq, &wait); 2053 spin_unlock_irq(&ep->lock); 2054 } 2055 } 2056 } 2057 2058 /** 2059 * ep_loop_check_proc - verify that adding an epoll file @ep inside another 2060 * epoll file does not create closed loops, and 2061 * determine the depth of the subtree starting at @ep 2062 * 2063 * @ep: the &struct eventpoll to be currently checked. 2064 * @depth: Current depth of the path being checked. 2065 * 2066 * Return: depth of the subtree, or a value bigger than EP_MAX_NESTS if we found 2067 * a loop or went too deep. 2068 */ 2069 static int ep_loop_check_proc(struct eventpoll *ep, int depth) 2070 { 2071 int result = 0; 2072 struct rb_node *rbp; 2073 struct epitem *epi; 2074 2075 if (ep->gen == loop_check_gen) 2076 return ep->loop_check_depth; 2077 2078 mutex_lock_nested(&ep->mtx, depth + 1); 2079 ep->gen = loop_check_gen; 2080 for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) { 2081 epi = rb_entry(rbp, struct epitem, rbn); 2082 if (unlikely(is_file_epoll(epi->ffd.file))) { 2083 struct eventpoll *ep_tovisit; 2084 ep_tovisit = epi->ffd.file->private_data; 2085 if (ep_tovisit == inserting_into || depth > EP_MAX_NESTS) 2086 result = EP_MAX_NESTS+1; 2087 else 2088 result = max(result, ep_loop_check_proc(ep_tovisit, depth + 1) + 1); 2089 if (result > EP_MAX_NESTS) 2090 break; 2091 } else { 2092 /* 2093 * If we've reached a file that is not associated with 2094 * an ep, then we need to check if the newly added 2095 * links are going to add too many wakeup paths. We do 2096 * this by adding it to the tfile_check_list, if it's 2097 * not already there, and calling reverse_path_check() 2098 * during ep_insert(). 2099 */ 2100 list_file(epi->ffd.file); 2101 } 2102 } 2103 ep->loop_check_depth = result; 2104 mutex_unlock(&ep->mtx); 2105 2106 return result; 2107 } 2108 2109 /* ep_get_upwards_depth_proc - determine depth of @ep when traversed upwards */ 2110 static int ep_get_upwards_depth_proc(struct eventpoll *ep, int depth) 2111 { 2112 int result = 0; 2113 struct epitem *epi; 2114 2115 if (ep->gen == loop_check_gen) 2116 return ep->loop_check_depth; 2117 hlist_for_each_entry_rcu(epi, &ep->refs, fllink) 2118 result = max(result, ep_get_upwards_depth_proc(epi->ep, depth + 1) + 1); 2119 ep->gen = loop_check_gen; 2120 ep->loop_check_depth = result; 2121 return result; 2122 } 2123 2124 /** 2125 * ep_loop_check - Performs a check to verify that adding an epoll file (@to) 2126 * into another epoll file (represented by @ep) does not create 2127 * closed loops or too deep chains. 2128 * 2129 * @ep: Pointer to the epoll we are inserting into. 2130 * @to: Pointer to the epoll to be inserted. 2131 * 2132 * Return: %zero if adding the epoll @to inside the epoll @from 2133 * does not violate the constraints, or %-1 otherwise. 2134 */ 2135 static int ep_loop_check(struct eventpoll *ep, struct eventpoll *to) 2136 { 2137 int depth, upwards_depth; 2138 2139 inserting_into = ep; 2140 /* 2141 * Check how deep down we can get from @to, and whether it is possible 2142 * to loop up to @ep. 2143 */ 2144 depth = ep_loop_check_proc(to, 0); 2145 if (depth > EP_MAX_NESTS) 2146 return -1; 2147 /* Check how far up we can go from @ep. */ 2148 rcu_read_lock(); 2149 upwards_depth = ep_get_upwards_depth_proc(ep, 0); 2150 rcu_read_unlock(); 2151 2152 return (depth+1+upwards_depth > EP_MAX_NESTS) ? -1 : 0; 2153 } 2154 2155 static void clear_tfile_check_list(void) 2156 { 2157 rcu_read_lock(); 2158 while (tfile_check_list != EP_UNACTIVE_PTR) { 2159 struct epitems_head *head = tfile_check_list; 2160 tfile_check_list = head->next; 2161 unlist_file(head); 2162 } 2163 rcu_read_unlock(); 2164 } 2165 2166 /* 2167 * Open an eventpoll file descriptor. 2168 */ 2169 static int do_epoll_create(int flags) 2170 { 2171 int error; 2172 struct eventpoll *ep; 2173 2174 /* Check the EPOLL_* constant for consistency. */ 2175 BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC); 2176 2177 if (flags & ~EPOLL_CLOEXEC) 2178 return -EINVAL; 2179 /* 2180 * Create the internal data structure ("struct eventpoll"). 2181 */ 2182 error = ep_alloc(&ep); 2183 if (error < 0) 2184 return error; 2185 /* 2186 * Creates all the items needed to setup an eventpoll file. That is, 2187 * a file structure and a free file descriptor. 2188 */ 2189 FD_PREPARE(fdf, O_RDWR | (flags & O_CLOEXEC), 2190 anon_inode_getfile("[eventpoll]", &eventpoll_fops, ep, 2191 O_RDWR | (flags & O_CLOEXEC))); 2192 if (fdf.err) { 2193 ep_clear_and_put(ep); 2194 return fdf.err; 2195 } 2196 ep->file = fd_prepare_file(fdf); 2197 return fd_publish(fdf); 2198 } 2199 2200 SYSCALL_DEFINE1(epoll_create1, int, flags) 2201 { 2202 return do_epoll_create(flags); 2203 } 2204 2205 SYSCALL_DEFINE1(epoll_create, int, size) 2206 { 2207 if (size <= 0) 2208 return -EINVAL; 2209 2210 return do_epoll_create(0); 2211 } 2212 2213 #ifdef CONFIG_PM_SLEEP 2214 static inline void ep_take_care_of_epollwakeup(struct epoll_event *epev) 2215 { 2216 if ((epev->events & EPOLLWAKEUP) && !capable(CAP_BLOCK_SUSPEND)) 2217 epev->events &= ~EPOLLWAKEUP; 2218 } 2219 #else 2220 static inline void ep_take_care_of_epollwakeup(struct epoll_event *epev) 2221 { 2222 epev->events &= ~EPOLLWAKEUP; 2223 } 2224 #endif 2225 2226 static inline int epoll_mutex_lock(struct mutex *mutex, int depth, 2227 bool nonblock) 2228 { 2229 if (!nonblock) { 2230 mutex_lock_nested(mutex, depth); 2231 return 0; 2232 } 2233 if (mutex_trylock(mutex)) 2234 return 0; 2235 return -EAGAIN; 2236 } 2237 2238 int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds, 2239 bool nonblock) 2240 { 2241 int error; 2242 int full_check = 0; 2243 struct eventpoll *ep; 2244 struct epitem *epi; 2245 struct eventpoll *tep = NULL; 2246 2247 CLASS(fd, f)(epfd); 2248 if (fd_empty(f)) 2249 return -EBADF; 2250 2251 /* Get the "struct file *" for the target file */ 2252 CLASS(fd, tf)(fd); 2253 if (fd_empty(tf)) 2254 return -EBADF; 2255 2256 /* The target file descriptor must support poll */ 2257 if (!file_can_poll(fd_file(tf))) 2258 return -EPERM; 2259 2260 /* Check if EPOLLWAKEUP is allowed */ 2261 if (ep_op_has_event(op)) 2262 ep_take_care_of_epollwakeup(epds); 2263 2264 /* 2265 * We have to check that the file structure underneath the file descriptor 2266 * the user passed to us _is_ an eventpoll file. And also we do not permit 2267 * adding an epoll file descriptor inside itself. 2268 */ 2269 error = -EINVAL; 2270 if (fd_file(f) == fd_file(tf) || !is_file_epoll(fd_file(f))) 2271 goto error_tgt_fput; 2272 2273 /* 2274 * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only, 2275 * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation. 2276 * Also, we do not currently supported nested exclusive wakeups. 2277 */ 2278 if (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) { 2279 if (op == EPOLL_CTL_MOD) 2280 goto error_tgt_fput; 2281 if (op == EPOLL_CTL_ADD && (is_file_epoll(fd_file(tf)) || 2282 (epds->events & ~EPOLLEXCLUSIVE_OK_BITS))) 2283 goto error_tgt_fput; 2284 } 2285 2286 /* 2287 * At this point it is safe to assume that the "private_data" contains 2288 * our own data structure. 2289 */ 2290 ep = fd_file(f)->private_data; 2291 2292 /* 2293 * When we insert an epoll file descriptor inside another epoll file 2294 * descriptor, there is the chance of creating closed loops, which are 2295 * better be handled here, than in more critical paths. While we are 2296 * checking for loops we also determine the list of files reachable 2297 * and hang them on the tfile_check_list, so we can check that we 2298 * haven't created too many possible wakeup paths. 2299 * 2300 * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when 2301 * the epoll file descriptor is attaching directly to a wakeup source, 2302 * unless the epoll file descriptor is nested. The purpose of taking the 2303 * 'epnested_mutex' on add is to prevent complex toplogies such as loops and 2304 * deep wakeup paths from forming in parallel through multiple 2305 * EPOLL_CTL_ADD operations. 2306 */ 2307 error = epoll_mutex_lock(&ep->mtx, 0, nonblock); 2308 if (error) 2309 goto error_tgt_fput; 2310 if (op == EPOLL_CTL_ADD) { 2311 if (READ_ONCE(fd_file(f)->f_ep) || ep->gen == loop_check_gen || 2312 is_file_epoll(fd_file(tf))) { 2313 mutex_unlock(&ep->mtx); 2314 error = epoll_mutex_lock(&epnested_mutex, 0, nonblock); 2315 if (error) 2316 goto error_tgt_fput; 2317 loop_check_gen++; 2318 full_check = 1; 2319 if (is_file_epoll(fd_file(tf))) { 2320 tep = fd_file(tf)->private_data; 2321 error = -ELOOP; 2322 if (ep_loop_check(ep, tep) != 0) 2323 goto error_tgt_fput; 2324 } 2325 error = epoll_mutex_lock(&ep->mtx, 0, nonblock); 2326 if (error) 2327 goto error_tgt_fput; 2328 } 2329 } 2330 2331 /* 2332 * Try to lookup the file inside our RB tree. Since we grabbed "mtx" 2333 * above, we can be sure to be able to use the item looked up by 2334 * ep_find() till we release the mutex. 2335 */ 2336 epi = ep_find(ep, fd_file(tf), fd); 2337 2338 error = -EINVAL; 2339 switch (op) { 2340 case EPOLL_CTL_ADD: 2341 if (!epi) { 2342 epds->events |= EPOLLERR | EPOLLHUP; 2343 error = ep_insert(ep, epds, fd_file(tf), fd, full_check); 2344 } else 2345 error = -EEXIST; 2346 break; 2347 case EPOLL_CTL_DEL: 2348 if (epi) { 2349 /* 2350 * The eventpoll itself is still alive: the refcount 2351 * can't go to zero here. 2352 */ 2353 ep_remove(ep, epi); 2354 error = 0; 2355 } else { 2356 error = -ENOENT; 2357 } 2358 break; 2359 case EPOLL_CTL_MOD: 2360 if (epi) { 2361 if (!(epi->event.events & EPOLLEXCLUSIVE)) { 2362 epds->events |= EPOLLERR | EPOLLHUP; 2363 error = ep_modify(ep, epi, epds); 2364 } 2365 } else 2366 error = -ENOENT; 2367 break; 2368 } 2369 mutex_unlock(&ep->mtx); 2370 2371 error_tgt_fput: 2372 if (full_check) { 2373 clear_tfile_check_list(); 2374 loop_check_gen++; 2375 mutex_unlock(&epnested_mutex); 2376 } 2377 return error; 2378 } 2379 2380 /* 2381 * The following function implements the controller interface for 2382 * the eventpoll file that enables the insertion/removal/change of 2383 * file descriptors inside the interest set. 2384 */ 2385 SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd, 2386 struct epoll_event __user *, event) 2387 { 2388 struct epoll_event epds; 2389 2390 if (ep_op_has_event(op) && 2391 copy_from_user(&epds, event, sizeof(struct epoll_event))) 2392 return -EFAULT; 2393 2394 return do_epoll_ctl(epfd, op, fd, &epds, false); 2395 } 2396 2397 static int ep_check_params(struct file *file, struct epoll_event __user *evs, 2398 int maxevents) 2399 { 2400 /* The maximum number of event must be greater than zero */ 2401 if (maxevents <= 0 || maxevents > EP_MAX_EVENTS) 2402 return -EINVAL; 2403 2404 /* Verify that the area passed by the user is writeable */ 2405 if (!access_ok(evs, maxevents * sizeof(struct epoll_event))) 2406 return -EFAULT; 2407 2408 /* 2409 * We have to check that the file structure underneath the fd 2410 * the user passed to us _is_ an eventpoll file. 2411 */ 2412 if (!is_file_epoll(file)) 2413 return -EINVAL; 2414 2415 return 0; 2416 } 2417 2418 int epoll_sendevents(struct file *file, struct epoll_event __user *events, 2419 int maxevents) 2420 { 2421 struct eventpoll *ep; 2422 int ret; 2423 2424 ret = ep_check_params(file, events, maxevents); 2425 if (unlikely(ret)) 2426 return ret; 2427 2428 ep = file->private_data; 2429 /* 2430 * Racy call, but that's ok - it should get retried based on 2431 * poll readiness anyway. 2432 */ 2433 if (ep_events_available(ep)) 2434 return ep_try_send_events(ep, events, maxevents); 2435 return 0; 2436 } 2437 2438 /* 2439 * Implement the event wait interface for the eventpoll file. It is the kernel 2440 * part of the user space epoll_wait(2). 2441 */ 2442 static int do_epoll_wait(int epfd, struct epoll_event __user *events, 2443 int maxevents, struct timespec64 *to) 2444 { 2445 struct eventpoll *ep; 2446 int ret; 2447 2448 /* Get the "struct file *" for the eventpoll file */ 2449 CLASS(fd, f)(epfd); 2450 if (fd_empty(f)) 2451 return -EBADF; 2452 2453 ret = ep_check_params(fd_file(f), events, maxevents); 2454 if (unlikely(ret)) 2455 return ret; 2456 2457 /* 2458 * At this point it is safe to assume that the "private_data" contains 2459 * our own data structure. 2460 */ 2461 ep = fd_file(f)->private_data; 2462 2463 /* Time to fish for events ... */ 2464 return ep_poll(ep, events, maxevents, to); 2465 } 2466 2467 SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events, 2468 int, maxevents, int, timeout) 2469 { 2470 struct timespec64 to; 2471 2472 return do_epoll_wait(epfd, events, maxevents, 2473 ep_timeout_to_timespec(&to, timeout)); 2474 } 2475 2476 /* 2477 * Implement the event wait interface for the eventpoll file. It is the kernel 2478 * part of the user space epoll_pwait(2). 2479 */ 2480 static int do_epoll_pwait(int epfd, struct epoll_event __user *events, 2481 int maxevents, struct timespec64 *to, 2482 const sigset_t __user *sigmask, size_t sigsetsize) 2483 { 2484 int error; 2485 2486 /* 2487 * If the caller wants a certain signal mask to be set during the wait, 2488 * we apply it here. 2489 */ 2490 error = set_user_sigmask(sigmask, sigsetsize); 2491 if (error) 2492 return error; 2493 2494 error = do_epoll_wait(epfd, events, maxevents, to); 2495 2496 restore_saved_sigmask_unless(error == -EINTR); 2497 2498 return error; 2499 } 2500 2501 SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events, 2502 int, maxevents, int, timeout, const sigset_t __user *, sigmask, 2503 size_t, sigsetsize) 2504 { 2505 struct timespec64 to; 2506 2507 return do_epoll_pwait(epfd, events, maxevents, 2508 ep_timeout_to_timespec(&to, timeout), 2509 sigmask, sigsetsize); 2510 } 2511 2512 SYSCALL_DEFINE6(epoll_pwait2, int, epfd, struct epoll_event __user *, events, 2513 int, maxevents, const struct __kernel_timespec __user *, timeout, 2514 const sigset_t __user *, sigmask, size_t, sigsetsize) 2515 { 2516 struct timespec64 ts, *to = NULL; 2517 2518 if (timeout) { 2519 if (get_timespec64(&ts, timeout)) 2520 return -EFAULT; 2521 to = &ts; 2522 if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec)) 2523 return -EINVAL; 2524 } 2525 2526 return do_epoll_pwait(epfd, events, maxevents, to, 2527 sigmask, sigsetsize); 2528 } 2529 2530 #ifdef CONFIG_COMPAT 2531 static int do_compat_epoll_pwait(int epfd, struct epoll_event __user *events, 2532 int maxevents, struct timespec64 *timeout, 2533 const compat_sigset_t __user *sigmask, 2534 compat_size_t sigsetsize) 2535 { 2536 long err; 2537 2538 /* 2539 * If the caller wants a certain signal mask to be set during the wait, 2540 * we apply it here. 2541 */ 2542 err = set_compat_user_sigmask(sigmask, sigsetsize); 2543 if (err) 2544 return err; 2545 2546 err = do_epoll_wait(epfd, events, maxevents, timeout); 2547 2548 restore_saved_sigmask_unless(err == -EINTR); 2549 2550 return err; 2551 } 2552 2553 COMPAT_SYSCALL_DEFINE6(epoll_pwait, int, epfd, 2554 struct epoll_event __user *, events, 2555 int, maxevents, int, timeout, 2556 const compat_sigset_t __user *, sigmask, 2557 compat_size_t, sigsetsize) 2558 { 2559 struct timespec64 to; 2560 2561 return do_compat_epoll_pwait(epfd, events, maxevents, 2562 ep_timeout_to_timespec(&to, timeout), 2563 sigmask, sigsetsize); 2564 } 2565 2566 COMPAT_SYSCALL_DEFINE6(epoll_pwait2, int, epfd, 2567 struct epoll_event __user *, events, 2568 int, maxevents, 2569 const struct __kernel_timespec __user *, timeout, 2570 const compat_sigset_t __user *, sigmask, 2571 compat_size_t, sigsetsize) 2572 { 2573 struct timespec64 ts, *to = NULL; 2574 2575 if (timeout) { 2576 if (get_timespec64(&ts, timeout)) 2577 return -EFAULT; 2578 to = &ts; 2579 if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec)) 2580 return -EINVAL; 2581 } 2582 2583 return do_compat_epoll_pwait(epfd, events, maxevents, to, 2584 sigmask, sigsetsize); 2585 } 2586 2587 #endif 2588 2589 static int __init eventpoll_init(void) 2590 { 2591 struct sysinfo si; 2592 2593 si_meminfo(&si); 2594 /* 2595 * Allows top 4% of lomem to be allocated for epoll watches (per user). 2596 */ 2597 max_user_watches = (((si.totalram - si.totalhigh) / 25) << PAGE_SHIFT) / 2598 EP_ITEM_COST; 2599 BUG_ON(max_user_watches < 0); 2600 2601 /* 2602 * We can have many thousands of epitems, so prevent this from 2603 * using an extra cache line on 64-bit (and smaller) CPUs 2604 */ 2605 BUILD_BUG_ON(sizeof(void *) <= 8 && sizeof(struct epitem) > 128); 2606 2607 /* Allocates slab cache used to allocate "struct epitem" items */ 2608 epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem), 2609 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, NULL); 2610 2611 /* Allocates slab cache used to allocate "struct eppoll_entry" */ 2612 pwq_cache = kmem_cache_create("eventpoll_pwq", 2613 sizeof(struct eppoll_entry), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL); 2614 epoll_sysctls_init(); 2615 2616 ephead_cache = kmem_cache_create("ep_head", 2617 sizeof(struct epitems_head), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL); 2618 2619 return 0; 2620 } 2621 fs_initcall(eventpoll_init); 2622