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