xref: /linux/fs/eventpoll.c (revision ad692c9e3ea3a72659ae8e695bfb52cc104c5631)
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 		pwq->wait.flags |= WQ_FLAG_POLL_EXCLUSIVE;
1630 	add_wait_queue(whead, &pwq->wait);
1631 	pwq->next = epi->pwqlist;
1632 	epi->pwqlist = pwq;
1633 }
1634 
1635 static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)
1636 {
1637 	int kcmp;
1638 	struct rb_node **p = &ep->rbr.rb_root.rb_node, *parent = NULL;
1639 	struct epitem *epic;
1640 	bool leftmost = true;
1641 
1642 	while (*p) {
1643 		parent = *p;
1644 		epic = rb_entry(parent, struct epitem, rbn);
1645 		kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd);
1646 		if (kcmp > 0) {
1647 			p = &parent->rb_right;
1648 			leftmost = false;
1649 		} else
1650 			p = &parent->rb_left;
1651 	}
1652 	rb_link_node(&epi->rbn, parent, p);
1653 	rb_insert_color_cached(&epi->rbn, &ep->rbr, leftmost);
1654 }
1655 
1656 
1657 
1658 /*
1659  * Upper bound on wakeup paths emanating from any one watched file,
1660  * indexed by path depth (1..PATH_ARR_SIZE). For example, we allow
1661  * 1000 paths of length 1 from each watched file. These caps limit
1662  * the wakeup amplification that can be built from epoll-watches-
1663  * epoll topologies without rejecting reasonable usage.
1664  *
1665  * Enforced at EPOLL_CTL_ADD; CTL_MOD and CTL_DEL cannot add paths.
1666  * The running tallies live in ctx->path_count[] and are protected by
1667  * epnested_mutex.
1668  */
1669 static const int path_limits[PATH_ARR_SIZE] = { 1000, 500, 100, 50, 10 };
1670 
1671 static int path_count_inc(struct ep_ctl_ctx *ctx, int nests)
1672 {
1673 	/* Allow an arbitrary number of depth 1 paths */
1674 	if (nests == 0)
1675 		return 0;
1676 
1677 	if (++ctx->path_count[nests] > path_limits[nests])
1678 		return -1;
1679 	return 0;
1680 }
1681 
1682 static void path_count_init(struct ep_ctl_ctx *ctx)
1683 {
1684 	int i;
1685 
1686 	for (i = 0; i < PATH_ARR_SIZE; i++)
1687 		ctx->path_count[i] = 0;
1688 }
1689 
1690 static int reverse_path_check_proc(struct ep_ctl_ctx *ctx,
1691 				   struct hlist_head *refs, int depth)
1692 {
1693 	int error = 0;
1694 	struct epitem *epi;
1695 
1696 	if (depth > EP_MAX_NESTS) /* too deep nesting */
1697 		return -1;
1698 
1699 	/* CTL_DEL can remove links here, but that can't increase our count */
1700 	hlist_for_each_entry_rcu(epi, refs, fllink) {
1701 		struct hlist_head *refs = &epi->ep->refs;
1702 		if (hlist_empty(refs))
1703 			error = path_count_inc(ctx, depth);
1704 		else
1705 			error = reverse_path_check_proc(ctx, refs, depth + 1);
1706 		if (error != 0)
1707 			break;
1708 	}
1709 	return error;
1710 }
1711 
1712 /**
1713  * reverse_path_check - ctx->tfile_check_list is a list of epitems_head
1714  *                      anchoring files with newly proposed links; make
1715  *                      sure those links don't push any path-length bucket
1716  *                      over its limit in path_limits[].
1717  * @ctx: Per-do_epoll_ctl() scratch for the loop / path checks.
1718  *
1719  * Return: %zero if the proposed links don't create too many paths,
1720  *	    %-1 otherwise.
1721  */
1722 static int reverse_path_check(struct ep_ctl_ctx *ctx)
1723 {
1724 	struct epitems_head *p;
1725 
1726 	for (p = ctx->tfile_check_list; p != EP_UNACTIVE_PTR; p = p->next) {
1727 		int error;
1728 		path_count_init(ctx);
1729 		rcu_read_lock();
1730 		error = reverse_path_check_proc(ctx, &p->epitems, 0);
1731 		rcu_read_unlock();
1732 		if (error)
1733 			return error;
1734 	}
1735 	return 0;
1736 }
1737 
1738 static int ep_create_wakeup_source(struct epitem *epi)
1739 {
1740 	struct name_snapshot n;
1741 	struct wakeup_source *ws;
1742 
1743 	if (!epi->ep->ws) {
1744 		epi->ep->ws = wakeup_source_register(NULL, "eventpoll");
1745 		if (!epi->ep->ws)
1746 			return -ENOMEM;
1747 	}
1748 
1749 	take_dentry_name_snapshot(&n, epi->ffd.file->f_path.dentry);
1750 	ws = wakeup_source_register(NULL, n.name.name);
1751 	release_dentry_name_snapshot(&n);
1752 
1753 	if (!ws)
1754 		return -ENOMEM;
1755 	rcu_assign_pointer(epi->ws, ws);
1756 
1757 	return 0;
1758 }
1759 
1760 /* rare code path, only used when EPOLL_CTL_MOD removes a wakeup source */
1761 static noinline void ep_destroy_wakeup_source(struct epitem *epi)
1762 {
1763 	struct wakeup_source *ws = ep_wakeup_source(epi);
1764 
1765 	RCU_INIT_POINTER(epi->ws, NULL);
1766 
1767 	/*
1768 	 * wait for ep_pm_stay_awake_rcu to finish, synchronize_rcu is
1769 	 * used internally by wakeup_source_remove, too (called by
1770 	 * wakeup_source_unregister), so we cannot use call_rcu
1771 	 */
1772 	synchronize_rcu();
1773 	wakeup_source_unregister(ws);
1774 }
1775 
1776 static int ep_attach_file(struct file *file, struct epitem *epi)
1777 {
1778 	struct epitems_head *to_free = NULL;
1779 	struct hlist_head *head = NULL;
1780 	struct eventpoll *ep = NULL;
1781 
1782 	if (is_file_epoll(file))
1783 		ep = file->private_data;
1784 
1785 	if (ep) {
1786 		head = &ep->refs;
1787 	} else if (!READ_ONCE(file->f_ep)) {
1788 allocate:
1789 		to_free = kmem_cache_zalloc(ephead_cache, GFP_KERNEL);
1790 		if (!to_free)
1791 			return -ENOMEM;
1792 		head = &to_free->epitems;
1793 	}
1794 	spin_lock(&file->f_lock);
1795 	if (!file->f_ep) {
1796 		if (unlikely(!head)) {
1797 			spin_unlock(&file->f_lock);
1798 			goto allocate;
1799 		}
1800 		/* See eventpoll_release() for details. */
1801 		WRITE_ONCE(file->f_ep, head);
1802 		to_free = NULL;
1803 	}
1804 	hlist_add_head_rcu(&epi->fllink, file->f_ep);
1805 	spin_unlock(&file->f_lock);
1806 	free_ephead(to_free);
1807 	return 0;
1808 }
1809 
1810 /*
1811  * Charge the user's epoll_watches quota, allocate a fresh epitem for
1812  * @tf, and initialize its fields. The returned item is not yet linked
1813  * into any data structure; the caller must install it via
1814  * ep_register_epitem() (which takes over on success) or kmem_cache_free()
1815  * it and decrement epoll_watches on its own.
1816  *
1817  * Returns ERR_PTR(-ENOSPC) if the quota is exceeded, ERR_PTR(-ENOMEM)
1818  * if the slab allocation fails.
1819  */
1820 static struct epitem *ep_alloc_epitem(struct eventpoll *ep,
1821 				      const struct epoll_event *event,
1822 				      struct epoll_key *tf)
1823 {
1824 	struct epitem *epi;
1825 
1826 	if (unlikely(percpu_counter_compare(&ep->user->epoll_watches,
1827 					    max_user_watches) >= 0))
1828 		return ERR_PTR(-ENOSPC);
1829 	percpu_counter_inc(&ep->user->epoll_watches);
1830 
1831 	epi = kmem_cache_zalloc(epi_cache, GFP_KERNEL);
1832 	if (unlikely(!epi)) {
1833 		percpu_counter_dec(&ep->user->epoll_watches);
1834 		return ERR_PTR(-ENOMEM);
1835 	}
1836 
1837 	INIT_LIST_HEAD(&epi->rdllink);
1838 	epi->ep = ep;
1839 	epi->ffd = *tf;
1840 	epi->event = *event;
1841 	epi_clear_ovflist(epi);
1842 
1843 	return epi;
1844 }
1845 
1846 /*
1847  * Install @epi into its target file's f_ep hlist and into @ep's rbtree,
1848  * taking one additional reference on @ep for the lifetime of the item.
1849  *
1850  * If @tep is non-NULL, the target file is itself an eventpoll; we hold
1851  * tep->mtx at subclass 1 across the attach + rbtree insert to serialize
1852  * with the target side. RB tree ops are protected by @ep->mtx, which
1853  * the caller already holds.
1854  *
1855  * On failure the epi is freed and the epoll_watches counter decremented,
1856  * matching ep_alloc_epitem()'s allocation. After this returns
1857  * successfully, ep_insert()'s later error paths use ep_remove() for
1858  * unwind; that cannot drop @ep's refcount to zero because the ep file
1859  * itself still holds the original reference.
1860  */
1861 static int ep_register_epitem(struct ep_ctl_ctx *ctx, struct eventpoll *ep,
1862 			      struct epitem *epi, struct eventpoll *tep,
1863 			      int full_check)
1864 {
1865 	struct file *tfile = epi->ffd.file;
1866 	int error;
1867 
1868 	if (tep)
1869 		mutex_lock_nested(&tep->mtx, 1);
1870 
1871 	error = ep_attach_file(tfile, epi);
1872 	if (unlikely(error)) {
1873 		if (tep)
1874 			mutex_unlock(&tep->mtx);
1875 		kmem_cache_free(epi_cache, epi);
1876 		percpu_counter_dec(&ep->user->epoll_watches);
1877 		return error;
1878 	}
1879 
1880 	if (full_check && !tep)
1881 		list_file(tfile, ctx);
1882 
1883 	ep_rbtree_insert(ep, epi);
1884 
1885 	if (tep)
1886 		mutex_unlock(&tep->mtx);
1887 
1888 	ep_get(ep);
1889 	return 0;
1890 }
1891 
1892 /*
1893  * Must be called with "mtx" held.
1894  */
1895 static int ep_insert(struct ep_ctl_ctx *ctx, struct eventpoll *ep,
1896 		     const struct epoll_event *event, struct epoll_key *tf,
1897 		     int full_check)
1898 {
1899 	int error, pwake = 0;
1900 	__poll_t revents;
1901 	struct epitem *epi;
1902 	struct ep_pqueue epq;
1903 	struct eventpoll *tep = NULL;
1904 
1905 	if (is_file_epoll(tf->file))
1906 		tep = tf->file->private_data;
1907 
1908 	lockdep_assert_irqs_enabled();
1909 
1910 	epi = ep_alloc_epitem(ep, event, tf);
1911 	if (IS_ERR(epi))
1912 		return PTR_ERR(epi);
1913 
1914 	error = ep_register_epitem(ctx, ep, epi, tep, full_check);
1915 	if (error)
1916 		return error;
1917 
1918 	/* Reject the insert if the new link would create too many back-paths. */
1919 	if (unlikely(full_check && reverse_path_check(ctx))) {
1920 		ep_remove(ep, epi);
1921 		return -EINVAL;
1922 	}
1923 
1924 	if (epi->event.events & EPOLLWAKEUP) {
1925 		error = ep_create_wakeup_source(epi);
1926 		if (error) {
1927 			ep_remove(ep, epi);
1928 			return error;
1929 		}
1930 	}
1931 
1932 	/* Initialize the poll table using the queue callback */
1933 	epq.epi = epi;
1934 	init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
1935 
1936 	/*
1937 	 * Attach the item to the poll hooks and get current event bits.
1938 	 * We can safely use the file* here because its usage count has
1939 	 * been increased by the caller of this function. Note that after
1940 	 * this operation completes, the poll callback can start hitting
1941 	 * the new item.
1942 	 */
1943 	revents = ep_item_poll(epi, &epq.pt, 1);
1944 
1945 	/* ep_ptable_queue_proc() signals allocation failure by clearing epq.epi. */
1946 	if (unlikely(!epq.epi)) {
1947 		ep_remove(ep, epi);
1948 		return -ENOMEM;
1949 	}
1950 
1951 	/* Drop the new item onto the ready list if it is already ready. */
1952 	spin_lock_irq(&ep->lock);
1953 
1954 	ep_set_busy_poll_napi_id(epi);
1955 
1956 	if (revents && !ep_is_linked(epi)) {
1957 		list_add_tail(&epi->rdllink, &ep->rdllist);
1958 		ep_pm_stay_awake(epi);
1959 
1960 		if (waitqueue_active(&ep->wq))
1961 			wake_up(&ep->wq);
1962 		if (waitqueue_active(&ep->poll_wait))
1963 			pwake++;
1964 	}
1965 
1966 	spin_unlock_irq(&ep->lock);
1967 
1968 	/* We have to call this outside the lock */
1969 	if (pwake)
1970 		ep_poll_safewake(ep, NULL, 0);
1971 
1972 	return 0;
1973 }
1974 
1975 /*
1976  * Modify the interest event mask by dropping an event if the new mask
1977  * has a match in the current file status. Must be called with "mtx" held.
1978  */
1979 static int ep_modify(struct eventpoll *ep, struct epitem *epi,
1980 		     const struct epoll_event *event)
1981 {
1982 	int pwake = 0;
1983 	poll_table pt;
1984 	int error;
1985 
1986 	lockdep_assert_irqs_enabled();
1987 
1988 	init_poll_funcptr(&pt, NULL);
1989 
1990 	/*
1991 	 * Create the wakeup source before committing the new event mask.
1992 	 * Leave the old mask and data unchanged if allocation fails.
1993 	 */
1994 	if ((event->events & EPOLLWAKEUP) && !ep_has_wakeup_source(epi)) {
1995 		error = ep_create_wakeup_source(epi);
1996 		if (error)
1997 			return error;
1998 	}
1999 
2000 	/*
2001 	 * Set the new event interest mask before calling f_op->poll();
2002 	 * otherwise we might miss an event that happens between the
2003 	 * f_op->poll() call and the new event set registering.
2004 	 */
2005 	epi->event.events = event->events; /* need barrier below */
2006 	epi->event.data = event->data; /* protected by mtx */
2007 	if (!(epi->event.events & EPOLLWAKEUP) &&
2008 	    ep_has_wakeup_source(epi))
2009 		ep_destroy_wakeup_source(epi);
2010 
2011 	/*
2012 	 * The following barrier has two effects:
2013 	 *
2014 	 * 1) Flush epi changes above to other CPUs.  This ensures
2015 	 *    we do not miss events from ep_poll_callback if an
2016 	 *    event occurs immediately after we call f_op->poll().
2017 	 *    We need this because we did not take ep->lock while
2018 	 *    changing epi above (but ep_poll_callback does take
2019 	 *    ep->lock).
2020 	 *
2021 	 * 2) We also need to ensure we do not miss _past_ events
2022 	 *    when calling f_op->poll().  This barrier also
2023 	 *    pairs with the barrier in wq_has_sleeper (see
2024 	 *    comments for wq_has_sleeper).
2025 	 *
2026 	 * This barrier will now guarantee ep_poll_callback or f_op->poll
2027 	 * (or both) will notice the readiness of an item.
2028 	 */
2029 	smp_mb();
2030 
2031 	/*
2032 	 * Get current event bits. We can safely use the file* here because
2033 	 * its usage count has been increased by the caller of this function.
2034 	 * If the item is "hot" and it is not registered inside the ready
2035 	 * list, push it inside.
2036 	 */
2037 	if (ep_item_poll(epi, &pt, 1)) {
2038 		spin_lock_irq(&ep->lock);
2039 		if (!ep_is_linked(epi)) {
2040 			list_add_tail(&epi->rdllink, &ep->rdllist);
2041 			ep_pm_stay_awake(epi);
2042 
2043 			/* Notify waiting tasks that events are available */
2044 			if (waitqueue_active(&ep->wq))
2045 				wake_up(&ep->wq);
2046 			if (waitqueue_active(&ep->poll_wait))
2047 				pwake++;
2048 		}
2049 		spin_unlock_irq(&ep->lock);
2050 	}
2051 
2052 	/* We have to call this outside the lock */
2053 	if (pwake)
2054 		ep_poll_safewake(ep, NULL, 0);
2055 
2056 	return 0;
2057 }
2058 
2059 /*
2060  * Attempt to deliver one event for @epi into @*uevents.
2061  *
2062  * Returns 1 if an event was delivered (with *uevents advanced to the
2063  * next slot), 0 if the re-poll reported no caller-requested events
2064  * (@epi drops out of the ready list; a future callback will re-add
2065  * it), or -EFAULT if copy_to_user() faulted (in which case @epi is
2066  * re-inserted at the head of @scan_batch so ep_done_scan() merges it
2067  * back to rdllist for the next attempt).
2068  *
2069  * PM bookkeeping and level-triggered re-queue are handled here.
2070  * Caller holds ep->mtx and the scan is active.
2071  */
2072 static int ep_deliver_event(struct eventpoll *ep, struct epitem *epi,
2073 			    poll_table *pt,
2074 			    struct epoll_event __user **uevents,
2075 			    struct list_head *scan_batch)
2076 {
2077 	struct epoll_event __user *next;
2078 	struct wakeup_source *ws;
2079 	__poll_t revents;
2080 
2081 	/*
2082 	 * Activate ep->ws before deactivating epi->ws to prevent
2083 	 * triggering auto-suspend here (in case we reactivate epi->ws
2084 	 * below).  Rearranging to delay the deactivation would let
2085 	 * epi->ws drift out of sync with ep_is_linked().
2086 	 */
2087 	ws = ep_wakeup_source(epi);
2088 	if (ws) {
2089 		if (ws->active)
2090 			__pm_stay_awake(ep->ws);
2091 		__pm_relax(ws);
2092 	}
2093 
2094 	list_del_init(&epi->rdllink);
2095 
2096 	/*
2097 	 * Re-poll under ep->mtx so userspace cannot change the item
2098 	 * out from under us. If no caller-requested events remain,
2099 	 * @epi stays off the ready list; the poll callback will
2100 	 * re-queue it when events next appear.
2101 	 */
2102 	revents = ep_item_poll(epi, pt, 1);
2103 	if (!revents)
2104 		return 0;
2105 
2106 	next = epoll_put_uevent(revents, epi->event.data, *uevents);
2107 	if (!next) {
2108 		/*
2109 		 * copy_to_user() faulted: put the item back so
2110 		 * ep_done_scan() splices it onto rdllist for the next
2111 		 * attempt.
2112 		 */
2113 		list_add(&epi->rdllink, scan_batch);
2114 		ep_pm_stay_awake(epi);
2115 		return -EFAULT;
2116 	}
2117 	*uevents = next;
2118 
2119 	if (epi->event.events & EPOLLONESHOT) {
2120 		epi->event.events &= EP_PRIVATE_BITS;
2121 	} else if (!(epi->event.events & EPOLLET)) {
2122 		/*
2123 		 * Level-triggered: re-queue so the next epoll_wait()
2124 		 * rechecks availability. We are the sole writer to
2125 		 * rdllist here -- epoll_ctl() callers are locked out
2126 		 * by ep->mtx, and the poll callback queues to ovflist
2127 		 * during scans.
2128 		 */
2129 		list_add_tail(&epi->rdllink, &ep->rdllist);
2130 		ep_pm_stay_awake(epi);
2131 	}
2132 	return 1;
2133 }
2134 
2135 static int ep_send_events(struct eventpoll *ep,
2136 			  struct epoll_event __user *events, int maxevents)
2137 {
2138 	struct epitem *epi, *tmp;
2139 	LIST_HEAD(scan_batch);
2140 	poll_table pt;
2141 	int res = 0;
2142 
2143 	/*
2144 	 * Always short-circuit for fatal signals to allow threads to make a
2145 	 * timely exit without the chance of finding more events available and
2146 	 * fetching repeatedly. The wakeup that got us here may have been the
2147 	 * only one for the events on ->rdllist, so pass it on to the next
2148 	 * waiter, as ep_done_scan() would have.
2149 	 */
2150 	if (fatal_signal_pending(current)) {
2151 		spin_lock_irq(&ep->lock);
2152 		if (!list_empty(&ep->rdllist))
2153 			wake_up(&ep->wq);
2154 		spin_unlock_irq(&ep->lock);
2155 		return -EINTR;
2156 	}
2157 
2158 	init_poll_funcptr(&pt, NULL);
2159 
2160 	mutex_lock(&ep->mtx);
2161 	ep_start_scan(ep, &scan_batch);
2162 
2163 	/*
2164 	 * We can loop without lock because we are passed a task-private
2165 	 * scan_batch; items cannot vanish while we hold ep->mtx.
2166 	 */
2167 	list_for_each_entry_safe(epi, tmp, &scan_batch, rdllink) {
2168 		int delivered;
2169 
2170 		if (res >= maxevents)
2171 			break;
2172 
2173 		delivered = ep_deliver_event(ep, epi, &pt, &events, &scan_batch);
2174 		if (delivered < 0) {
2175 			if (!res)
2176 				res = delivered;
2177 			break;
2178 		}
2179 		res += delivered;
2180 	}
2181 
2182 	ep_done_scan(ep, &scan_batch);
2183 	mutex_unlock(&ep->mtx);
2184 
2185 	return res;
2186 }
2187 
2188 static struct timespec64 *ep_timeout_to_timespec(struct timespec64 *to, long ms)
2189 {
2190 	struct timespec64 now;
2191 
2192 	if (ms < 0)
2193 		return NULL;
2194 
2195 	if (!ms) {
2196 		to->tv_sec = 0;
2197 		to->tv_nsec = 0;
2198 		return to;
2199 	}
2200 
2201 	to->tv_sec = ms / MSEC_PER_SEC;
2202 	to->tv_nsec = NSEC_PER_MSEC * (ms % MSEC_PER_SEC);
2203 
2204 	ktime_get_ts64(&now);
2205 	*to = timespec64_add_safe(now, *to);
2206 	return to;
2207 }
2208 
2209 /*
2210  * autoremove_wake_function, but remove even on failure to wake up, because we
2211  * know that default_wake_function/ttwu will only fail if the thread is already
2212  * woken, and in that case the ep_poll loop will remove the entry anyways, not
2213  * try to reuse it.
2214  */
2215 static int ep_autoremove_wake_function(struct wait_queue_entry *wq_entry,
2216 				       unsigned int mode, int sync, void *key)
2217 {
2218 	int ret = default_wake_function(wq_entry, mode, sync, key);
2219 
2220 	/*
2221 	 * Pairs with list_empty_careful in ep_poll, and ensures future loop
2222 	 * iterations see the cause of this wakeup.
2223 	 */
2224 	list_del_init_careful(&wq_entry->entry);
2225 	return ret;
2226 }
2227 
2228 static int ep_try_send_events(struct eventpoll *ep,
2229 			      struct epoll_event __user *events, int maxevents)
2230 {
2231 	int res;
2232 
2233 	/*
2234 	 * Try to transfer events to user space. In case we get 0 events and
2235 	 * there's still timeout left over, we go trying again in search of
2236 	 * more luck.
2237 	 */
2238 	res = ep_send_events(ep, events, maxevents);
2239 	if (res > 0)
2240 		ep_suspend_napi_irqs(ep);
2241 	return res;
2242 }
2243 
2244 static int ep_schedule_timeout(ktime_t *to)
2245 {
2246 	if (to)
2247 		return ktime_after(*to, ktime_get());
2248 	else
2249 		return 1;
2250 }
2251 
2252 /**
2253  * ep_poll - Retrieves ready events, and delivers them to the caller-supplied
2254  *           event buffer.
2255  *
2256  * @ep: Pointer to the eventpoll context.
2257  * @events: Pointer to the userspace buffer where the ready events should be
2258  *          stored.
2259  * @maxevents: Size (in terms of number of events) of the caller event buffer.
2260  * @timeout: Maximum timeout for the ready events fetch operation, in
2261  *           timespec. If the timeout is zero, the function will not block,
2262  *           while if the @timeout ptr is NULL, the function will block
2263  *           until at least one event has been retrieved (or an error
2264  *           occurred).
2265  *
2266  * Return: the number of ready events which have been fetched, or an
2267  *          error code, in case of error.
2268  */
2269 static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
2270 		   int maxevents, struct timespec64 *timeout)
2271 {
2272 	int res, timed_out = 0;
2273 	bool eavail;
2274 	u64 slack = 0;
2275 	wait_queue_entry_t wait;
2276 	ktime_t expires, *to = NULL;
2277 
2278 	lockdep_assert_irqs_enabled();
2279 
2280 	if (timeout && (timeout->tv_sec | timeout->tv_nsec)) {
2281 		to = &expires;
2282 		*to = timespec64_to_ktime(*timeout);
2283 	} else if (timeout) {
2284 		/*
2285 		 * Avoid the unnecessary trip to the wait queue loop, if the
2286 		 * caller specified a non blocking operation.
2287 		 */
2288 		timed_out = 1;
2289 	}
2290 
2291 	/*
2292 	 * This call is racy: We may or may not see events that are being added
2293 	 * to the ready list under the lock (e.g., in IRQ callbacks). For cases
2294 	 * with a non-zero timeout, this thread will check the ready list under
2295 	 * lock and will add to the wait queue.  For cases with a zero
2296 	 * timeout, the user by definition should not care and will have to
2297 	 * recheck again.
2298 	 */
2299 	eavail = ep_events_available(ep);
2300 
2301 	while (1) {
2302 		if (eavail) {
2303 			res = ep_try_send_events(ep, events, maxevents);
2304 			if (res)
2305 				return res;
2306 		}
2307 
2308 		if (timed_out)
2309 			return 0;
2310 
2311 		eavail = ep_busy_loop(ep);
2312 		if (eavail)
2313 			continue;
2314 
2315 		if (signal_pending(current))
2316 			return -EINTR;
2317 
2318 		/*
2319 		 * Internally init_wait() uses autoremove_wake_function(),
2320 		 * thus wait entry is removed from the wait queue on each
2321 		 * wakeup. Why it is important? In case of several waiters
2322 		 * each new wakeup will hit the next waiter, giving it the
2323 		 * chance to harvest new event. Otherwise wakeup can be
2324 		 * lost. This is also good performance-wise, because on
2325 		 * normal wakeup path no need to call __remove_wait_queue()
2326 		 * explicitly, thus ep->lock is not taken, which halts the
2327 		 * event delivery.
2328 		 *
2329 		 * In fact, we now use an even more aggressive function that
2330 		 * unconditionally removes, because we don't reuse the wait
2331 		 * entry between loop iterations. This lets us also avoid the
2332 		 * performance issue if a process is killed, causing all of its
2333 		 * threads to wake up without being removed normally.
2334 		 */
2335 		init_wait(&wait);
2336 		wait.func = ep_autoremove_wake_function;
2337 
2338 		spin_lock_irq(&ep->lock);
2339 		/*
2340 		 * Barrierless variant, waitqueue_active() is called under
2341 		 * the same lock on wakeup ep_poll_callback() side, so it
2342 		 * is safe to avoid an explicit barrier.
2343 		 */
2344 		__set_current_state(TASK_INTERRUPTIBLE);
2345 
2346 		/*
2347 		 * Do the final check under the lock. ep_start/done_scan()
2348 		 * plays with two lists (->rdllist and ->ovflist) and there
2349 		 * is always a race when both lists are empty for short
2350 		 * period of time although events are pending, so lock is
2351 		 * important.
2352 		 */
2353 		eavail = ep_events_available(ep);
2354 		if (!eavail)
2355 			__add_wait_queue_exclusive(&ep->wq, &wait);
2356 
2357 		spin_unlock_irq(&ep->lock);
2358 
2359 		if (!eavail) {
2360 			if (to)
2361 				slack = select_estimate_accuracy(timeout);
2362 			timed_out = !ep_schedule_timeout(to) ||
2363 				!schedule_hrtimeout_range(to, slack,
2364 							  HRTIMER_MODE_ABS);
2365 		}
2366 		__set_current_state(TASK_RUNNING);
2367 
2368 		/*
2369 		 * We were woken up, thus go and try to harvest some events.
2370 		 * If timed out and still on the wait queue, recheck eavail
2371 		 * carefully under lock, below.
2372 		 */
2373 		eavail = true;
2374 
2375 		if (!list_empty_careful(&wait.entry)) {
2376 			spin_lock_irq(&ep->lock);
2377 			/*
2378 			 * If the thread timed out and is not on the wait queue,
2379 			 * it means that the thread was woken up after its
2380 			 * timeout expired before it could reacquire the lock.
2381 			 * Thus, when wait.entry is empty, it needs to harvest
2382 			 * events.
2383 			 */
2384 			if (timed_out)
2385 				eavail = list_empty(&wait.entry);
2386 			__remove_wait_queue(&ep->wq, &wait);
2387 			spin_unlock_irq(&ep->lock);
2388 		}
2389 	}
2390 }
2391 
2392 /**
2393  * ep_loop_check_proc - verify that adding an epoll file @ep inside another
2394  *                      epoll file does not create closed loops, and
2395  *                      determine the depth of the subtree starting at @ep
2396  *
2397  * @ctx: Per-do_epoll_ctl() scratch for the loop / path checks.
2398  * @ep: the &struct eventpoll to be currently checked.
2399  * @depth: Current depth of the path being checked.
2400  *
2401  * Return: depth of the subtree, or a value bigger than EP_MAX_NESTS if we found
2402  * a loop or went too deep.
2403  */
2404 static int ep_loop_check_proc(struct ep_ctl_ctx *ctx,
2405 			      struct eventpoll *ep, int depth)
2406 {
2407 	int result = 0;
2408 	struct rb_node *rbp;
2409 	struct epitem *epi;
2410 
2411 	if (ep->gen == loop_check_gen)
2412 		return ep->loop_check_depth;
2413 
2414 	mutex_lock_nested(&ep->mtx, depth + 1);
2415 	ep->gen = loop_check_gen;
2416 	for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
2417 		epi = rb_entry(rbp, struct epitem, rbn);
2418 		if (unlikely(is_file_epoll(epi->ffd.file))) {
2419 			struct eventpoll *ep_tovisit;
2420 			ep_tovisit = epi->ffd.file->private_data;
2421 			if (ep_tovisit == ctx->inserting_into ||
2422 			    depth > EP_MAX_NESTS)
2423 				result = EP_MAX_NESTS+1;
2424 			else
2425 				result = max(result,
2426 					     ep_loop_check_proc(ctx, ep_tovisit,
2427 								depth + 1) + 1);
2428 			if (result > EP_MAX_NESTS)
2429 				break;
2430 		} else {
2431 			/*
2432 			 * A non-epoll leaf. Queue it for the companion
2433 			 * reverse_path_check() that runs after this walk so
2434 			 * any new links we propose don't add too many wakeup
2435 			 * paths.
2436 			 */
2437 			list_file(epi->ffd.file, ctx);
2438 		}
2439 	}
2440 	ep->loop_check_depth = result;
2441 	mutex_unlock(&ep->mtx);
2442 
2443 	return result;
2444 }
2445 
2446 /* ep_get_upwards_depth_proc - determine depth of @ep when traversed upwards */
2447 static int ep_get_upwards_depth_proc(struct eventpoll *ep, int depth)
2448 {
2449 	int result = 0;
2450 	struct epitem *epi;
2451 
2452 	if (ep->gen == loop_check_gen)
2453 		return ep->loop_check_depth;
2454 	hlist_for_each_entry_rcu(epi, &ep->refs, fllink)
2455 		result = max(result, ep_get_upwards_depth_proc(epi->ep, depth + 1) + 1);
2456 	ep->gen = loop_check_gen;
2457 	ep->loop_check_depth = result;
2458 	return result;
2459 }
2460 
2461 /**
2462  * ep_loop_check - Performs a check to verify that adding an epoll file (@to)
2463  *                 into another epoll file (represented by @ep) does not create
2464  *                 closed loops or too deep chains.
2465  *
2466  * @ctx: Per-CTL_ADD scratch context.
2467  * @ep:  Pointer to the epoll we are inserting into.
2468  * @to:  Pointer to the epoll to be inserted.
2469  *
2470  * Return: %zero if adding the epoll @to inside the epoll @from
2471  * does not violate the constraints, or %-1 otherwise.
2472  */
2473 static int ep_loop_check(struct ep_ctl_ctx *ctx, struct eventpoll *ep,
2474 			 struct eventpoll *to)
2475 {
2476 	int depth, upwards_depth;
2477 
2478 	ctx->inserting_into = ep;
2479 	/*
2480 	 * Check how deep down we can get from @to, and whether it is possible
2481 	 * to loop up to @ep.
2482 	 */
2483 	depth = ep_loop_check_proc(ctx, to, 0);
2484 	if (depth > EP_MAX_NESTS)
2485 		return -1;
2486 	/* Check how far up we can go from @ep. */
2487 	rcu_read_lock();
2488 	upwards_depth = ep_get_upwards_depth_proc(ep, 0);
2489 	rcu_read_unlock();
2490 
2491 	return (depth+1+upwards_depth > EP_MAX_NESTS) ? -1 : 0;
2492 }
2493 
2494 static void clear_tfile_check_list(struct ep_ctl_ctx *ctx)
2495 {
2496 	rcu_read_lock();
2497 	while (ctx->tfile_check_list != EP_UNACTIVE_PTR) {
2498 		struct epitems_head *head = ctx->tfile_check_list;
2499 		ctx->tfile_check_list = head->next;
2500 		unlist_file(head);
2501 	}
2502 	rcu_read_unlock();
2503 }
2504 
2505 /*
2506  * Open an eventpoll file descriptor.
2507  */
2508 static int do_epoll_create(int flags)
2509 {
2510 	int error;
2511 	struct eventpoll *ep;
2512 
2513 	/* Check the EPOLL_* constant for consistency.  */
2514 	BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC);
2515 
2516 	if (flags & ~EPOLL_CLOEXEC)
2517 		return -EINVAL;
2518 	/*
2519 	 * Create the internal data structure ("struct eventpoll").
2520 	 */
2521 	error = ep_alloc(&ep);
2522 	if (error < 0)
2523 		return error;
2524 	/*
2525 	 * Creates all the items needed to setup an eventpoll file. That is,
2526 	 * a file structure and a free file descriptor.
2527 	 */
2528 	FD_PREPARE(fdf, O_RDWR | (flags & O_CLOEXEC),
2529 		   anon_inode_getfile("[eventpoll]", &eventpoll_fops, ep,
2530 				      O_RDWR | (flags & O_CLOEXEC)));
2531 	if (fdf->fd < 0) {
2532 		ep_clear_and_put(ep);
2533 		return fdf->fd;
2534 	}
2535 	ep->file = fdf->file;
2536 	return fd_publish(fdf);
2537 }
2538 
2539 SYSCALL_DEFINE1(epoll_create1, int, flags)
2540 {
2541 	return do_epoll_create(flags);
2542 }
2543 
2544 SYSCALL_DEFINE1(epoll_create, int, size)
2545 {
2546 	if (size <= 0)
2547 		return -EINVAL;
2548 
2549 	return do_epoll_create(0);
2550 }
2551 
2552 #ifdef CONFIG_PM_SLEEP
2553 static inline void ep_take_care_of_epollwakeup(struct epoll_event *epev)
2554 {
2555 	if ((epev->events & EPOLLWAKEUP) && !capable(CAP_BLOCK_SUSPEND))
2556 		epev->events &= ~EPOLLWAKEUP;
2557 }
2558 #else
2559 static inline void ep_take_care_of_epollwakeup(struct epoll_event *epev)
2560 {
2561 	epev->events &= ~EPOLLWAKEUP;
2562 }
2563 #endif
2564 
2565 static inline int epoll_mutex_lock(struct mutex *mutex, bool nonblock)
2566 {
2567 	if (!nonblock) {
2568 		mutex_lock(mutex);
2569 		return 0;
2570 	}
2571 	return mutex_trylock(mutex) ? 0 : -EAGAIN;
2572 }
2573 
2574 /*
2575  * Acquire the locks required for do_epoll_ctl() on @ep for @op.
2576  *
2577  * Always takes ep->mtx. For EPOLL_CTL_ADD, additionally runs the
2578  * loop / path check under epnested_mutex when the topology can
2579  * change: @ep is already watched (epfile->f_ep non-NULL), @ep was
2580  * recently loop-checked (ep->gen == loop_check_gen), or @tfile is
2581  * itself an eventpoll.
2582  *
2583  * Return value encodes both outcome and lock state:
2584  *
2585  *   0        success; ep->mtx held.
2586  *   1        success; ep->mtx held AND the full check ran under
2587  *            epnested_mutex (which is also still held). The value
2588  *            doubles as the @full_check argument to ep_insert().
2589  *   -errno   failure; no locks held.
2590  *
2591  * The caller releases what was taken with ep_ctl_unlock(ep, ret).
2592  *
2593  * Holding epnested_mutex on add is what prevents two racing
2594  * EPOLL_CTL_ADDs on different eps from building a cycle without
2595  * either walker observing it.
2596  */
2597 static int ep_ctl_lock(struct ep_ctl_ctx *ctx, struct eventpoll *ep, int op,
2598 		       struct file *epfile, struct file *tfile, bool nonblock)
2599 {
2600 	struct eventpoll *tep;
2601 	int error;
2602 
2603 	error = epoll_mutex_lock(&ep->mtx, nonblock);
2604 	if (error)
2605 		return error;
2606 
2607 	if (op != EPOLL_CTL_ADD)
2608 		return 0;
2609 	if (!READ_ONCE(epfile->f_ep) && ep->gen != loop_check_gen &&
2610 	    !is_file_epoll(tfile))
2611 		return 0;
2612 
2613 	/* Full check needed: drop ep->mtx so we can take epnested_mutex. */
2614 	mutex_unlock(&ep->mtx);
2615 	error = epoll_mutex_lock(&epnested_mutex, nonblock);
2616 	if (error)
2617 		return error;
2618 
2619 	loop_check_gen++;
2620 
2621 	if (is_file_epoll(tfile)) {
2622 		tep = tfile->private_data;
2623 		if (ep_loop_check(ctx, ep, tep) != 0) {
2624 			error = -ELOOP;
2625 			goto err_unlock_nested;
2626 		}
2627 	}
2628 
2629 	error = epoll_mutex_lock(&ep->mtx, nonblock);
2630 	if (error)
2631 		goto err_unlock_nested;
2632 
2633 	return 1;
2634 
2635 err_unlock_nested:
2636 	clear_tfile_check_list(ctx);
2637 	loop_check_gen++;
2638 	mutex_unlock(&epnested_mutex);
2639 	return error;
2640 }
2641 
2642 static void ep_ctl_unlock(struct ep_ctl_ctx *ctx, struct eventpoll *ep,
2643 			  int full_check)
2644 {
2645 	mutex_unlock(&ep->mtx);
2646 	if (full_check) {
2647 		clear_tfile_check_list(ctx);
2648 		loop_check_gen++;
2649 		mutex_unlock(&epnested_mutex);
2650 	}
2651 }
2652 
2653 int do_epoll_ctl_file(struct file *f, int op, struct epoll_key *tf,
2654 		      struct epoll_event *epds, bool nonblock)
2655 {
2656 	int error;
2657 	int full_check;
2658 	struct eventpoll *ep;
2659 	struct epitem *epi;
2660 	struct ep_ctl_ctx ctx = {
2661 		.tfile_check_list = EP_UNACTIVE_PTR,
2662 	};
2663 
2664 	/* The target file descriptor must support poll */
2665 	if (!file_can_poll(tf->file))
2666 		return -EPERM;
2667 
2668 	/* Check if EPOLLWAKEUP is allowed */
2669 	if (ep_op_has_event(op))
2670 		ep_take_care_of_epollwakeup(epds);
2671 
2672 	/*
2673 	 * The @f file must itself be an eventpoll, and we do not permit
2674 	 * adding an epoll file descriptor inside itself.
2675 	 */
2676 	if (f == tf->file || !is_file_epoll(f))
2677 		return -EINVAL;
2678 
2679 	/*
2680 	 * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only,
2681 	 * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation.
2682 	 * Also, nested exclusive wakeups are not supported.
2683 	 */
2684 	if (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) {
2685 		if (op == EPOLL_CTL_MOD)
2686 			return -EINVAL;
2687 		if (op == EPOLL_CTL_ADD && (is_file_epoll(tf->file) ||
2688 				(epds->events & ~EPOLLEXCLUSIVE_OK_BITS)))
2689 			return -EINVAL;
2690 	}
2691 
2692 	ep = f->private_data;
2693 
2694 	full_check = ep_ctl_lock(&ctx, ep, op, f, tf->file, nonblock);
2695 	if (full_check < 0)
2696 		return full_check;
2697 
2698 	/*
2699 	 * Look the target up in ep's RB tree. We hold ep->mtx, so the
2700 	 * item stays valid until we release.
2701 	 */
2702 	epi = ep_find(ep, tf);
2703 
2704 	error = -EINVAL;
2705 	switch (op) {
2706 	case EPOLL_CTL_ADD:
2707 		if (!epi) {
2708 			epds->events |= EPOLLERR | EPOLLHUP;
2709 			error = ep_insert(&ctx, ep, epds, tf, full_check);
2710 		} else
2711 			error = -EEXIST;
2712 		break;
2713 	case EPOLL_CTL_DEL:
2714 		if (epi) {
2715 			/*
2716 			 * The eventpoll itself is still alive: the refcount
2717 			 * can't go to zero here.
2718 			 */
2719 			ep_remove(ep, epi);
2720 			error = 0;
2721 		} else {
2722 			error = -ENOENT;
2723 		}
2724 		break;
2725 	case EPOLL_CTL_MOD:
2726 		if (epi) {
2727 			if (!(epi->event.events & EPOLLEXCLUSIVE)) {
2728 				epds->events |= EPOLLERR | EPOLLHUP;
2729 				error = ep_modify(ep, epi, epds);
2730 			}
2731 		} else
2732 			error = -ENOENT;
2733 		break;
2734 	}
2735 
2736 	ep_ctl_unlock(&ctx, ep, full_check);
2737 	return error;
2738 }
2739 
2740 int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds,
2741 		 bool nonblock)
2742 {
2743 	struct epoll_key efd;
2744 
2745 	CLASS(fd, f)(epfd);
2746 	if (fd_empty(f))
2747 		return -EBADF;
2748 
2749 	/* Get the "struct file *" for the target file */
2750 	CLASS(fd, tf)(fd);
2751 	if (fd_empty(tf))
2752 		return -EBADF;
2753 
2754 	efd.file = fd_file(tf);
2755 	efd.fd = fd;
2756 	return do_epoll_ctl_file(fd_file(f), op, &efd, epds, nonblock);
2757 }
2758 
2759 /*
2760  * The following function implements the controller interface for
2761  * the eventpoll file that enables the insertion/removal/change of
2762  * file descriptors inside the interest set.
2763  */
2764 SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
2765 		struct epoll_event __user *, event)
2766 {
2767 	struct epoll_event epds;
2768 
2769 	if (ep_op_has_event(op) &&
2770 	    copy_from_user(&epds, event, sizeof(struct epoll_event)))
2771 		return -EFAULT;
2772 
2773 	return do_epoll_ctl(epfd, op, fd, &epds, false);
2774 }
2775 
2776 static int ep_check_params(struct file *file, struct epoll_event __user *evs,
2777 			   int maxevents)
2778 {
2779 	/* The maximum number of event must be greater than zero */
2780 	if (maxevents <= 0 || maxevents > EP_MAX_EVENTS)
2781 		return -EINVAL;
2782 
2783 	/* Verify that the area passed by the user is writeable */
2784 	if (!access_ok(evs, maxevents * sizeof(struct epoll_event)))
2785 		return -EFAULT;
2786 
2787 	/*
2788 	 * We have to check that the file structure underneath the fd
2789 	 * the user passed to us _is_ an eventpoll file.
2790 	 */
2791 	if (!is_file_epoll(file))
2792 		return -EINVAL;
2793 
2794 	return 0;
2795 }
2796 
2797 int epoll_sendevents(struct file *file, struct epoll_event __user *events,
2798 		     int maxevents)
2799 {
2800 	struct eventpoll *ep;
2801 	int ret;
2802 
2803 	ret = ep_check_params(file, events, maxevents);
2804 	if (unlikely(ret))
2805 		return ret;
2806 
2807 	ep = file->private_data;
2808 	/*
2809 	 * Racy call, but that's ok - it should get retried based on
2810 	 * poll readiness anyway.
2811 	 */
2812 	if (ep_events_available(ep))
2813 		return ep_try_send_events(ep, events, maxevents);
2814 	return 0;
2815 }
2816 
2817 /*
2818  * Implement the event wait interface for the eventpoll file. It is the kernel
2819  * part of the user space epoll_wait(2).
2820  */
2821 static int do_epoll_wait(int epfd, struct epoll_event __user *events,
2822 			 int maxevents, struct timespec64 *to)
2823 {
2824 	struct eventpoll *ep;
2825 	int ret;
2826 
2827 	/* Get the "struct file *" for the eventpoll file */
2828 	CLASS(fd, f)(epfd);
2829 	if (fd_empty(f))
2830 		return -EBADF;
2831 
2832 	ret = ep_check_params(fd_file(f), events, maxevents);
2833 	if (unlikely(ret))
2834 		return ret;
2835 
2836 	/*
2837 	 * At this point it is safe to assume that the "private_data" contains
2838 	 * our own data structure.
2839 	 */
2840 	ep = fd_file(f)->private_data;
2841 
2842 	/* Time to fish for events ... */
2843 	return ep_poll(ep, events, maxevents, to);
2844 }
2845 
2846 SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events,
2847 		int, maxevents, int, timeout)
2848 {
2849 	struct timespec64 to;
2850 
2851 	return do_epoll_wait(epfd, events, maxevents,
2852 			     ep_timeout_to_timespec(&to, timeout));
2853 }
2854 
2855 /*
2856  * Implement the event wait interface for the eventpoll file. It is the kernel
2857  * part of the user space epoll_pwait(2).
2858  */
2859 static int do_epoll_pwait(int epfd, struct epoll_event __user *events,
2860 			  int maxevents, struct timespec64 *to,
2861 			  const sigset_t __user *sigmask, size_t sigsetsize)
2862 {
2863 	int error;
2864 
2865 	/*
2866 	 * If the caller wants a certain signal mask to be set during the wait,
2867 	 * we apply it here.
2868 	 */
2869 	error = set_user_sigmask(sigmask, sigsetsize);
2870 	if (error)
2871 		return error;
2872 
2873 	error = do_epoll_wait(epfd, events, maxevents, to);
2874 
2875 	restore_saved_sigmask_unless(error == -EINTR);
2876 
2877 	return error;
2878 }
2879 
2880 SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
2881 		int, maxevents, int, timeout, const sigset_t __user *, sigmask,
2882 		size_t, sigsetsize)
2883 {
2884 	struct timespec64 to;
2885 
2886 	return do_epoll_pwait(epfd, events, maxevents,
2887 			      ep_timeout_to_timespec(&to, timeout),
2888 			      sigmask, sigsetsize);
2889 }
2890 
2891 SYSCALL_DEFINE6(epoll_pwait2, int, epfd, struct epoll_event __user *, events,
2892 		int, maxevents, const struct __kernel_timespec __user *, timeout,
2893 		const sigset_t __user *, sigmask, size_t, sigsetsize)
2894 {
2895 	struct timespec64 ts, *to = NULL;
2896 
2897 	if (timeout) {
2898 		if (get_timespec64(&ts, timeout))
2899 			return -EFAULT;
2900 		to = &ts;
2901 		if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
2902 			return -EINVAL;
2903 	}
2904 
2905 	return do_epoll_pwait(epfd, events, maxevents, to,
2906 			      sigmask, sigsetsize);
2907 }
2908 
2909 #ifdef CONFIG_KCMP
2910 static struct epitem *ep_find_tfd(struct eventpoll *ep, int tfd, unsigned long toff)
2911 {
2912 	struct rb_node *rbp;
2913 	struct epitem *epi;
2914 
2915 	for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
2916 		epi = rb_entry(rbp, struct epitem, rbn);
2917 		if (epi->ffd.fd == tfd) {
2918 			if (toff == 0)
2919 				return epi;
2920 			else
2921 				toff--;
2922 		}
2923 		cond_resched();
2924 	}
2925 
2926 	return NULL;
2927 }
2928 
2929 struct file *get_epoll_tfile_raw_ptr(struct file *file, int tfd,
2930 				     unsigned long toff)
2931 {
2932 	struct file *file_raw;
2933 	struct eventpoll *ep;
2934 	struct epitem *epi;
2935 
2936 	if (!is_file_epoll(file))
2937 		return ERR_PTR(-EINVAL);
2938 
2939 	ep = file->private_data;
2940 
2941 	mutex_lock(&ep->mtx);
2942 	epi = ep_find_tfd(ep, tfd, toff);
2943 	if (epi)
2944 		file_raw = epi->ffd.file;
2945 	else
2946 		file_raw = ERR_PTR(-ENOENT);
2947 	mutex_unlock(&ep->mtx);
2948 
2949 	return file_raw;
2950 }
2951 #endif /* CONFIG_KCMP */
2952 
2953 #ifdef CONFIG_COMPAT
2954 static int do_compat_epoll_pwait(int epfd, struct epoll_event __user *events,
2955 				 int maxevents, struct timespec64 *timeout,
2956 				 const compat_sigset_t __user *sigmask,
2957 				 compat_size_t sigsetsize)
2958 {
2959 	long err;
2960 
2961 	/*
2962 	 * If the caller wants a certain signal mask to be set during the wait,
2963 	 * we apply it here.
2964 	 */
2965 	err = set_compat_user_sigmask(sigmask, sigsetsize);
2966 	if (err)
2967 		return err;
2968 
2969 	err = do_epoll_wait(epfd, events, maxevents, timeout);
2970 
2971 	restore_saved_sigmask_unless(err == -EINTR);
2972 
2973 	return err;
2974 }
2975 
2976 COMPAT_SYSCALL_DEFINE6(epoll_pwait, int, epfd,
2977 		       struct epoll_event __user *, events,
2978 		       int, maxevents, int, timeout,
2979 		       const compat_sigset_t __user *, sigmask,
2980 		       compat_size_t, sigsetsize)
2981 {
2982 	struct timespec64 to;
2983 
2984 	return do_compat_epoll_pwait(epfd, events, maxevents,
2985 				     ep_timeout_to_timespec(&to, timeout),
2986 				     sigmask, sigsetsize);
2987 }
2988 
2989 COMPAT_SYSCALL_DEFINE6(epoll_pwait2, int, epfd,
2990 		       struct epoll_event __user *, events,
2991 		       int, maxevents,
2992 		       const struct __kernel_timespec __user *, timeout,
2993 		       const compat_sigset_t __user *, sigmask,
2994 		       compat_size_t, sigsetsize)
2995 {
2996 	struct timespec64 ts, *to = NULL;
2997 
2998 	if (timeout) {
2999 		if (get_timespec64(&ts, timeout))
3000 			return -EFAULT;
3001 		to = &ts;
3002 		if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
3003 			return -EINVAL;
3004 	}
3005 
3006 	return do_compat_epoll_pwait(epfd, events, maxevents, to,
3007 				     sigmask, sigsetsize);
3008 }
3009 
3010 #endif
3011 
3012 static int __init eventpoll_init(void)
3013 {
3014 	struct sysinfo si;
3015 
3016 	si_meminfo(&si);
3017 	/*
3018 	 * Allows top 4% of lomem to be allocated for epoll watches (per user).
3019 	 */
3020 	max_user_watches = (((si.totalram - si.totalhigh) / 25) << PAGE_SHIFT) /
3021 		EP_ITEM_COST;
3022 	BUG_ON(max_user_watches < 0);
3023 
3024 	/*
3025 	 * We can have many thousands of epitems, so prevent this from
3026 	 * using an extra cache line on 64-bit (and smaller) CPUs
3027 	 */
3028 	BUILD_BUG_ON(sizeof(void *) <= 8 && sizeof(struct epitem) > 128);
3029 
3030 	/* Allocates slab cache used to allocate "struct epitem" items */
3031 	epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
3032 			0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, NULL);
3033 
3034 	/* Allocates slab cache used to allocate "struct eppoll_entry" */
3035 	pwq_cache = kmem_cache_create("eventpoll_pwq",
3036 		sizeof(struct eppoll_entry), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL);
3037 	epoll_sysctls_init();
3038 
3039 	ephead_cache = kmem_cache_create("ep_head",
3040 		sizeof(struct epitems_head), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL);
3041 
3042 	return 0;
3043 }
3044 fs_initcall(eventpoll_init);
3045