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