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