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