xref: /openbmc/linux/fs/eventpoll.c (revision 55e43d6abd078ed6d219902ce8cb4d68e3c993ba)
12874c5fdSThomas Gleixner // SPDX-License-Identifier: GPL-2.0-or-later
21da177e4SLinus Torvalds /*
35071f97eSDavide Libenzi  *  fs/eventpoll.c (Efficient event retrieval implementation)
45071f97eSDavide Libenzi  *  Copyright (C) 2001,...,2009	 Davide Libenzi
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *  Davide Libenzi <davidel@xmailserver.org>
71da177e4SLinus Torvalds  */
81da177e4SLinus Torvalds 
91da177e4SLinus Torvalds #include <linux/init.h>
101da177e4SLinus Torvalds #include <linux/kernel.h>
11174cd4b1SIngo Molnar #include <linux/sched/signal.h>
121da177e4SLinus Torvalds #include <linux/fs.h>
131da177e4SLinus Torvalds #include <linux/file.h>
141da177e4SLinus Torvalds #include <linux/signal.h>
151da177e4SLinus Torvalds #include <linux/errno.h>
161da177e4SLinus Torvalds #include <linux/mm.h>
171da177e4SLinus Torvalds #include <linux/slab.h>
181da177e4SLinus Torvalds #include <linux/poll.h>
191da177e4SLinus Torvalds #include <linux/string.h>
201da177e4SLinus Torvalds #include <linux/list.h>
211da177e4SLinus Torvalds #include <linux/hash.h>
221da177e4SLinus Torvalds #include <linux/spinlock.h>
231da177e4SLinus Torvalds #include <linux/syscalls.h>
241da177e4SLinus Torvalds #include <linux/rbtree.h>
251da177e4SLinus Torvalds #include <linux/wait.h>
261da177e4SLinus Torvalds #include <linux/eventpoll.h>
271da177e4SLinus Torvalds #include <linux/mount.h>
281da177e4SLinus Torvalds #include <linux/bitops.h>
29144efe3eSArjan van de Ven #include <linux/mutex.h>
30da66f7cbSDavide Libenzi #include <linux/anon_inodes.h>
314d7e30d9SArve Hjønnevåg #include <linux/device.h>
327c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
331da177e4SLinus Torvalds #include <asm/io.h>
341da177e4SLinus Torvalds #include <asm/mman.h>
3560063497SArun Sharma #include <linux/atomic.h>
36138d22b5SCyrill Gorcunov #include <linux/proc_fs.h>
37138d22b5SCyrill Gorcunov #include <linux/seq_file.h>
3835280bd4SAl Viro #include <linux/compat.h>
39ae10b2b4SJason Baron #include <linux/rculist.h>
40bf3b9f63SSridhar Samudrala #include <net/busy_poll.h>
411da177e4SLinus Torvalds 
421da177e4SLinus Torvalds /*
431da177e4SLinus Torvalds  * LOCKING:
441da177e4SLinus Torvalds  * There are three level of locking required by epoll :
451da177e4SLinus Torvalds  *
46d4cb626dSDavidlohr Bueso  * 1) epnested_mutex (mutex)
47c7ea7630SDavide Libenzi  * 2) ep->mtx (mutex)
48a218cc49SRoman Penyaev  * 3) ep->lock (rwlock)
491da177e4SLinus Torvalds  *
501da177e4SLinus Torvalds  * The acquire order is the one listed above, from 1 to 3.
51a218cc49SRoman Penyaev  * We need a rwlock (ep->lock) because we manipulate objects
521da177e4SLinus Torvalds  * from inside the poll callback, that might be triggered from
531da177e4SLinus Torvalds  * a wake_up() that in turn might be called from IRQ context.
541da177e4SLinus Torvalds  * So we can't sleep inside the poll callback and hence we need
551da177e4SLinus Torvalds  * a spinlock. During the event transfer loop (from kernel to
561da177e4SLinus Torvalds  * user space) we could end up sleeping due a copy_to_user(), so
571da177e4SLinus Torvalds  * we need a lock that will allow us to sleep. This lock is a
58d47de16cSDavide Libenzi  * mutex (ep->mtx). It is acquired during the event transfer loop,
59d47de16cSDavide Libenzi  * during epoll_ctl(EPOLL_CTL_DEL) and during eventpoll_release_file().
60d4cb626dSDavidlohr Bueso  * The epnested_mutex is acquired when inserting an epoll fd onto another
61d4cb626dSDavidlohr Bueso  * epoll fd. We do this so that we walk the epoll tree and ensure that this
6222bacca4SDavide Libenzi  * insertion does not create a cycle of epoll file descriptors, which
6322bacca4SDavide Libenzi  * could lead to deadlock. We need a global mutex to prevent two
6422bacca4SDavide Libenzi  * simultaneous inserts (A into B and B into A) from racing and
6522bacca4SDavide Libenzi  * constructing a cycle without either insert observing that it is
6622bacca4SDavide Libenzi  * going to.
67d8805e63SNelson Elhage  * It is necessary to acquire multiple "ep->mtx"es at once in the
68d8805e63SNelson Elhage  * case when one epoll fd is added to another. In this case, we
69d8805e63SNelson Elhage  * always acquire the locks in the order of nesting (i.e. after
70d8805e63SNelson Elhage  * epoll_ctl(e1, EPOLL_CTL_ADD, e2), e1->mtx will always be acquired
71d8805e63SNelson Elhage  * before e2->mtx). Since we disallow cycles of epoll file
72d8805e63SNelson Elhage  * descriptors, this ensures that the mutexes are well-ordered. In
73d8805e63SNelson Elhage  * order to communicate this nesting to lockdep, when walking a tree
74d8805e63SNelson Elhage  * of epoll file descriptors, we use the current recursion depth as
75d8805e63SNelson Elhage  * the lockdep subkey.
76d47de16cSDavide Libenzi  * It is possible to drop the "ep->mtx" and to use the global
77d4cb626dSDavidlohr Bueso  * mutex "epnested_mutex" (together with "ep->lock") to have it working,
78d47de16cSDavide Libenzi  * but having "ep->mtx" will make the interface more scalable.
79d4cb626dSDavidlohr Bueso  * Events that require holding "epnested_mutex" are very rare, while for
80d47de16cSDavide Libenzi  * normal operations the epoll private "ep->mtx" will guarantee
81d47de16cSDavide Libenzi  * a better scalability.
821da177e4SLinus Torvalds  */
831da177e4SLinus Torvalds 
841da177e4SLinus Torvalds /* Epoll private bits inside the event mask */
85df0108c5SJason Baron #define EP_PRIVATE_BITS (EPOLLWAKEUP | EPOLLONESHOT | EPOLLET | EPOLLEXCLUSIVE)
861da177e4SLinus Torvalds 
87a9a08845SLinus Torvalds #define EPOLLINOUT_BITS (EPOLLIN | EPOLLOUT)
88b6a515c8SJason Baron 
89a9a08845SLinus Torvalds #define EPOLLEXCLUSIVE_OK_BITS (EPOLLINOUT_BITS | EPOLLERR | EPOLLHUP | \
90b6a515c8SJason Baron 				EPOLLWAKEUP | EPOLLET | EPOLLEXCLUSIVE)
91b6a515c8SJason Baron 
925071f97eSDavide Libenzi /* Maximum number of nesting allowed inside epoll sets */
935071f97eSDavide Libenzi #define EP_MAX_NESTS 4
941da177e4SLinus Torvalds 
95b611967dSDavide Libenzi #define EP_MAX_EVENTS (INT_MAX / sizeof(struct epoll_event))
96b611967dSDavide Libenzi 
97d47de16cSDavide Libenzi #define EP_UNACTIVE_PTR ((void *) -1L)
98d47de16cSDavide Libenzi 
997ef9964eSDavide Libenzi #define EP_ITEM_COST (sizeof(struct epitem) + sizeof(struct eppoll_entry))
1007ef9964eSDavide Libenzi 
1011da177e4SLinus Torvalds struct epoll_filefd {
1021da177e4SLinus Torvalds 	struct file *file;
1031da177e4SLinus Torvalds 	int fd;
10439732ca5SEric Wong } __packed;
1051da177e4SLinus Torvalds 
10680285b75SAl Viro /* Wait structure used by the poll hooks */
10780285b75SAl Viro struct eppoll_entry {
10880285b75SAl Viro 	/* List header used to link this structure to the "struct epitem" */
10980285b75SAl Viro 	struct eppoll_entry *next;
11080285b75SAl Viro 
11180285b75SAl Viro 	/* The "base" pointer is set to the container "struct epitem" */
11280285b75SAl Viro 	struct epitem *base;
1131da177e4SLinus Torvalds 
1141da177e4SLinus Torvalds 	/*
11580285b75SAl Viro 	 * Wait queue item that will be linked to the target file wait
11680285b75SAl Viro 	 * queue head.
1171da177e4SLinus Torvalds 	 */
11880285b75SAl Viro 	wait_queue_entry_t wait;
11980285b75SAl Viro 
12080285b75SAl Viro 	/* The wait queue head that linked the "wait" wait queue item */
12180285b75SAl Viro 	wait_queue_head_t *whead;
1221da177e4SLinus Torvalds };
1231da177e4SLinus Torvalds 
1241da177e4SLinus Torvalds /*
1251da177e4SLinus Torvalds  * Each file descriptor added to the eventpoll interface will
1266192bd53SDavide Libenzi  * have an entry of this type linked to the "rbr" RB tree.
12739732ca5SEric Wong  * Avoid increasing the size of this struct, there can be many thousands
12839732ca5SEric Wong  * of these on a server and we do not want this to take another cache line.
1291da177e4SLinus Torvalds  */
1301da177e4SLinus Torvalds struct epitem {
131ae10b2b4SJason Baron 	union {
132ae10b2b4SJason Baron 		/* RB tree node links this structure to the eventpoll RB tree */
1331da177e4SLinus Torvalds 		struct rb_node rbn;
134ae10b2b4SJason Baron 		/* Used to free the struct epitem */
135ae10b2b4SJason Baron 		struct rcu_head rcu;
136ae10b2b4SJason Baron 	};
1371da177e4SLinus Torvalds 
1381da177e4SLinus Torvalds 	/* List header used to link this structure to the eventpoll ready list */
1391da177e4SLinus Torvalds 	struct list_head rdllink;
1401da177e4SLinus Torvalds 
141c7ea7630SDavide Libenzi 	/*
142c7ea7630SDavide Libenzi 	 * Works together "struct eventpoll"->ovflist in keeping the
143c7ea7630SDavide Libenzi 	 * single linked chain of items.
144c7ea7630SDavide Libenzi 	 */
145c7ea7630SDavide Libenzi 	struct epitem *next;
146c7ea7630SDavide Libenzi 
1471da177e4SLinus Torvalds 	/* The file descriptor information this item refers to */
1481da177e4SLinus Torvalds 	struct epoll_filefd ffd;
1491da177e4SLinus Torvalds 
15058c9b016SPaolo Abeni 	/*
15158c9b016SPaolo Abeni 	 * Protected by file->f_lock, true for to-be-released epitem already
15258c9b016SPaolo Abeni 	 * removed from the "struct file" items list; together with
15358c9b016SPaolo Abeni 	 * eventpoll->refcount orchestrates "struct eventpoll" disposal
15458c9b016SPaolo Abeni 	 */
15558c9b016SPaolo Abeni 	bool dying;
15658c9b016SPaolo Abeni 
1571da177e4SLinus Torvalds 	/* List containing poll wait queues */
15880285b75SAl Viro 	struct eppoll_entry *pwqlist;
1591da177e4SLinus Torvalds 
1601da177e4SLinus Torvalds 	/* The "container" of this item */
1611da177e4SLinus Torvalds 	struct eventpoll *ep;
1621da177e4SLinus Torvalds 
1631da177e4SLinus Torvalds 	/* List header used to link this item to the "struct file" items list */
16444cdc1d9SAl Viro 	struct hlist_node fllink;
165d47de16cSDavide Libenzi 
1664d7e30d9SArve Hjønnevåg 	/* wakeup_source used when EPOLLWAKEUP is set */
167eea1d585SEric Wong 	struct wakeup_source __rcu *ws;
1684d7e30d9SArve Hjønnevåg 
169c7ea7630SDavide Libenzi 	/* The structure that describe the interested events and the source fd */
170c7ea7630SDavide Libenzi 	struct epoll_event event;
171d47de16cSDavide Libenzi };
172d47de16cSDavide Libenzi 
173d47de16cSDavide Libenzi /*
174d47de16cSDavide Libenzi  * This structure is stored inside the "private_data" member of the file
175bf6a41dbSDaniel Baluta  * structure and represents the main data structure for the eventpoll
176d47de16cSDavide Libenzi  * interface.
177d47de16cSDavide Libenzi  */
178d47de16cSDavide Libenzi struct eventpoll {
179d47de16cSDavide Libenzi 	/*
180d47de16cSDavide Libenzi 	 * This mutex is used to ensure that files are not removed
181d47de16cSDavide Libenzi 	 * while epoll is using them. This is held during the event
182d47de16cSDavide Libenzi 	 * collection loop, the file cleanup path, the epoll file exit
183d47de16cSDavide Libenzi 	 * code and the ctl operations.
184d47de16cSDavide Libenzi 	 */
185d47de16cSDavide Libenzi 	struct mutex mtx;
186d47de16cSDavide Libenzi 
187d47de16cSDavide Libenzi 	/* Wait queue used by sys_epoll_wait() */
188d47de16cSDavide Libenzi 	wait_queue_head_t wq;
189d47de16cSDavide Libenzi 
190d47de16cSDavide Libenzi 	/* Wait queue used by file->poll() */
191d47de16cSDavide Libenzi 	wait_queue_head_t poll_wait;
192d47de16cSDavide Libenzi 
193d47de16cSDavide Libenzi 	/* List of ready file descriptors */
194d47de16cSDavide Libenzi 	struct list_head rdllist;
195d47de16cSDavide Libenzi 
196a218cc49SRoman Penyaev 	/* Lock which protects rdllist and ovflist */
197a218cc49SRoman Penyaev 	rwlock_t lock;
198a218cc49SRoman Penyaev 
19967647d0fSDavide Libenzi 	/* RB tree root used to store monitored fd structs */
200b2ac2ea6SDavidlohr Bueso 	struct rb_root_cached rbr;
201d47de16cSDavide Libenzi 
202d47de16cSDavide Libenzi 	/*
203d47de16cSDavide Libenzi 	 * This is a single linked list that chains all the "struct epitem" that
20425985edcSLucas De Marchi 	 * happened while transferring ready events to userspace w/out
205a218cc49SRoman Penyaev 	 * holding ->lock.
206d47de16cSDavide Libenzi 	 */
207d47de16cSDavide Libenzi 	struct epitem *ovflist;
2087ef9964eSDavide Libenzi 
2094d7e30d9SArve Hjønnevåg 	/* wakeup_source used when ep_scan_ready_list is running */
2104d7e30d9SArve Hjønnevåg 	struct wakeup_source *ws;
2114d7e30d9SArve Hjønnevåg 
2127ef9964eSDavide Libenzi 	/* The user that created the eventpoll descriptor */
2137ef9964eSDavide Libenzi 	struct user_struct *user;
21428d82dc1SJason Baron 
21528d82dc1SJason Baron 	struct file *file;
21628d82dc1SJason Baron 
21728d82dc1SJason Baron 	/* used to optimize loop detection check */
21818306c40SAl Viro 	u64 gen;
219319c1517SAl Viro 	struct hlist_head refs;
220bf3b9f63SSridhar Samudrala 
22158c9b016SPaolo Abeni 	/*
22258c9b016SPaolo Abeni 	 * usage count, used together with epitem->dying to
22358c9b016SPaolo Abeni 	 * orchestrate the disposal of this struct
22458c9b016SPaolo Abeni 	 */
22558c9b016SPaolo Abeni 	refcount_t refcount;
22658c9b016SPaolo Abeni 
227bf3b9f63SSridhar Samudrala #ifdef CONFIG_NET_RX_BUSY_POLL
228bf3b9f63SSridhar Samudrala 	/* used to track busy poll napi_id */
229bf3b9f63SSridhar Samudrala 	unsigned int napi_id;
230bf3b9f63SSridhar Samudrala #endif
231efcdd350SJason Baron 
232efcdd350SJason Baron #ifdef CONFIG_DEBUG_LOCK_ALLOC
233efcdd350SJason Baron 	/* tracks wakeup nests for lockdep validation */
234efcdd350SJason Baron 	u8 nests;
235efcdd350SJason Baron #endif
236d47de16cSDavide Libenzi };
237d47de16cSDavide Libenzi 
2381da177e4SLinus Torvalds /* Wrapper struct used by poll queueing */
2391da177e4SLinus Torvalds struct ep_pqueue {
2401da177e4SLinus Torvalds 	poll_table pt;
2411da177e4SLinus Torvalds 	struct epitem *epi;
2421da177e4SLinus Torvalds };
2431da177e4SLinus Torvalds 
2441da177e4SLinus Torvalds /*
2457ef9964eSDavide Libenzi  * Configuration options available inside /proc/sys/fs/epoll/
2467ef9964eSDavide Libenzi  */
2477ef9964eSDavide Libenzi /* Maximum number of epoll watched descriptors, per user */
24852bd19f7SRobin Holt static long max_user_watches __read_mostly;
2497ef9964eSDavide Libenzi 
25058c9b016SPaolo Abeni /* Used for cycles detection */
251d4cb626dSDavidlohr Bueso static DEFINE_MUTEX(epnested_mutex);
2521da177e4SLinus Torvalds 
25318306c40SAl Viro static u64 loop_check_gen = 0;
25418306c40SAl Viro 
25522bacca4SDavide Libenzi /* Used to check for epoll file descriptor inclusion loops */
2566a3890c4SAl Viro static struct eventpoll *inserting_into;
25722bacca4SDavide Libenzi 
2581da177e4SLinus Torvalds /* Slab cache used to allocate "struct epitem" */
259e18b890bSChristoph Lameter static struct kmem_cache *epi_cache __read_mostly;
2601da177e4SLinus Torvalds 
2611da177e4SLinus Torvalds /* Slab cache used to allocate "struct eppoll_entry" */
262e18b890bSChristoph Lameter static struct kmem_cache *pwq_cache __read_mostly;
2631da177e4SLinus Torvalds 
26428d82dc1SJason Baron /*
26528d82dc1SJason Baron  * List of files with newly added links, where we may need to limit the number
266d4cb626dSDavidlohr Bueso  * of emanating paths. Protected by the epnested_mutex.
26728d82dc1SJason Baron  */
268319c1517SAl Viro struct epitems_head {
269319c1517SAl Viro 	struct hlist_head epitems;
270319c1517SAl Viro 	struct epitems_head *next;
271319c1517SAl Viro };
272319c1517SAl Viro static struct epitems_head *tfile_check_list = EP_UNACTIVE_PTR;
273319c1517SAl Viro 
274319c1517SAl Viro static struct kmem_cache *ephead_cache __read_mostly;
275319c1517SAl Viro 
free_ephead(struct epitems_head * head)276319c1517SAl Viro static inline void free_ephead(struct epitems_head *head)
277319c1517SAl Viro {
278319c1517SAl Viro 	if (head)
279319c1517SAl Viro 		kmem_cache_free(ephead_cache, head);
280319c1517SAl Viro }
281319c1517SAl Viro 
list_file(struct file * file)282319c1517SAl Viro static void list_file(struct file *file)
283319c1517SAl Viro {
284319c1517SAl Viro 	struct epitems_head *head;
285319c1517SAl Viro 
286319c1517SAl Viro 	head = container_of(file->f_ep, struct epitems_head, epitems);
287319c1517SAl Viro 	if (!head->next) {
288319c1517SAl Viro 		head->next = tfile_check_list;
289319c1517SAl Viro 		tfile_check_list = head;
290319c1517SAl Viro 	}
291319c1517SAl Viro }
292319c1517SAl Viro 
unlist_file(struct epitems_head * head)293319c1517SAl Viro static void unlist_file(struct epitems_head *head)
294319c1517SAl Viro {
295319c1517SAl Viro 	struct epitems_head *to_free = head;
296319c1517SAl Viro 	struct hlist_node *p = rcu_dereference(hlist_first_rcu(&head->epitems));
297319c1517SAl Viro 	if (p) {
298319c1517SAl Viro 		struct epitem *epi= container_of(p, struct epitem, fllink);
299319c1517SAl Viro 		spin_lock(&epi->ffd.file->f_lock);
300319c1517SAl Viro 		if (!hlist_empty(&head->epitems))
301319c1517SAl Viro 			to_free = NULL;
302319c1517SAl Viro 		head->next = NULL;
303319c1517SAl Viro 		spin_unlock(&epi->ffd.file->f_lock);
304319c1517SAl Viro 	}
305319c1517SAl Viro 	free_ephead(to_free);
306319c1517SAl Viro }
30728d82dc1SJason Baron 
3087ef9964eSDavide Libenzi #ifdef CONFIG_SYSCTL
3097ef9964eSDavide Libenzi 
3107ef9964eSDavide Libenzi #include <linux/sysctl.h>
3117ef9964eSDavide Libenzi 
312eec4844fSMatteo Croce static long long_zero;
31352bd19f7SRobin Holt static long long_max = LONG_MAX;
3147ef9964eSDavide Libenzi 
315a8f5de89SXiaoming Ni static struct ctl_table epoll_table[] = {
3167ef9964eSDavide Libenzi 	{
3177ef9964eSDavide Libenzi 		.procname	= "max_user_watches",
3187ef9964eSDavide Libenzi 		.data		= &max_user_watches,
31952bd19f7SRobin Holt 		.maxlen		= sizeof(max_user_watches),
3207ef9964eSDavide Libenzi 		.mode		= 0644,
32152bd19f7SRobin Holt 		.proc_handler	= proc_doulongvec_minmax,
322eec4844fSMatteo Croce 		.extra1		= &long_zero,
32352bd19f7SRobin Holt 		.extra2		= &long_max,
3247ef9964eSDavide Libenzi 	},
325ab09203eSEric W. Biederman 	{ }
3267ef9964eSDavide Libenzi };
327a8f5de89SXiaoming Ni 
epoll_sysctls_init(void)328a8f5de89SXiaoming Ni static void __init epoll_sysctls_init(void)
329a8f5de89SXiaoming Ni {
330a8f5de89SXiaoming Ni 	register_sysctl("fs/epoll", epoll_table);
331a8f5de89SXiaoming Ni }
332a8f5de89SXiaoming Ni #else
333a8f5de89SXiaoming Ni #define epoll_sysctls_init() do { } while (0)
3347ef9964eSDavide Libenzi #endif /* CONFIG_SYSCTL */
3357ef9964eSDavide Libenzi 
33628d82dc1SJason Baron static const struct file_operations eventpoll_fops;
33728d82dc1SJason Baron 
is_file_epoll(struct file * f)33828d82dc1SJason Baron static inline int is_file_epoll(struct file *f)
33928d82dc1SJason Baron {
34028d82dc1SJason Baron 	return f->f_op == &eventpoll_fops;
34128d82dc1SJason Baron }
342b030a4ddSPekka Enberg 
34367647d0fSDavide Libenzi /* Setup the structure that is used as key for the RB tree */
ep_set_ffd(struct epoll_filefd * ffd,struct file * file,int fd)344b030a4ddSPekka Enberg static inline void ep_set_ffd(struct epoll_filefd *ffd,
345b030a4ddSPekka Enberg 			      struct file *file, int fd)
346b030a4ddSPekka Enberg {
347b030a4ddSPekka Enberg 	ffd->file = file;
348b030a4ddSPekka Enberg 	ffd->fd = fd;
349b030a4ddSPekka Enberg }
350b030a4ddSPekka Enberg 
35167647d0fSDavide Libenzi /* Compare RB tree keys */
ep_cmp_ffd(struct epoll_filefd * p1,struct epoll_filefd * p2)352b030a4ddSPekka Enberg static inline int ep_cmp_ffd(struct epoll_filefd *p1,
353b030a4ddSPekka Enberg 			     struct epoll_filefd *p2)
354b030a4ddSPekka Enberg {
355b030a4ddSPekka Enberg 	return (p1->file > p2->file ? +1:
356b030a4ddSPekka Enberg 	        (p1->file < p2->file ? -1 : p1->fd - p2->fd));
357b030a4ddSPekka Enberg }
358b030a4ddSPekka Enberg 
359b030a4ddSPekka Enberg /* Tells us if the item is currently linked */
ep_is_linked(struct epitem * epi)360992991c0SDavidlohr Bueso static inline int ep_is_linked(struct epitem *epi)
361b030a4ddSPekka Enberg {
362992991c0SDavidlohr Bueso 	return !list_empty(&epi->rdllink);
363b030a4ddSPekka Enberg }
364b030a4ddSPekka Enberg 
ep_pwq_from_wait(wait_queue_entry_t * p)365ac6424b9SIngo Molnar static inline struct eppoll_entry *ep_pwq_from_wait(wait_queue_entry_t *p)
366971316f0SOleg Nesterov {
367971316f0SOleg Nesterov 	return container_of(p, struct eppoll_entry, wait);
368971316f0SOleg Nesterov }
369971316f0SOleg Nesterov 
370b030a4ddSPekka Enberg /* Get the "struct epitem" from a wait queue pointer */
ep_item_from_wait(wait_queue_entry_t * p)371ac6424b9SIngo Molnar static inline struct epitem *ep_item_from_wait(wait_queue_entry_t *p)
372b030a4ddSPekka Enberg {
373b030a4ddSPekka Enberg 	return container_of(p, struct eppoll_entry, wait)->base;
374b030a4ddSPekka Enberg }
375b030a4ddSPekka Enberg 
3765071f97eSDavide Libenzi /**
3773fb0e584SDavide Libenzi  * ep_events_available - Checks if ready events might be available.
3783fb0e584SDavide Libenzi  *
3793fb0e584SDavide Libenzi  * @ep: Pointer to the eventpoll context.
3803fb0e584SDavide Libenzi  *
381a6c67feeSRandy Dunlap  * Return: a value different than %zero if ready events are available,
382a6c67feeSRandy Dunlap  *          or %zero otherwise.
3833fb0e584SDavide Libenzi  */
ep_events_available(struct eventpoll * ep)3843fb0e584SDavide Libenzi static inline int ep_events_available(struct eventpoll *ep)
3853fb0e584SDavide Libenzi {
386c5a282e9SDavidlohr Bueso 	return !list_empty_careful(&ep->rdllist) ||
387c5a282e9SDavidlohr Bueso 		READ_ONCE(ep->ovflist) != EP_UNACTIVE_PTR;
3883fb0e584SDavide Libenzi }
3893fb0e584SDavide Libenzi 
390bf3b9f63SSridhar Samudrala #ifdef CONFIG_NET_RX_BUSY_POLL
ep_busy_loop_end(void * p,unsigned long start_time)391bf3b9f63SSridhar Samudrala static bool ep_busy_loop_end(void *p, unsigned long start_time)
392bf3b9f63SSridhar Samudrala {
393bf3b9f63SSridhar Samudrala 	struct eventpoll *ep = p;
394bf3b9f63SSridhar Samudrala 
395bf3b9f63SSridhar Samudrala 	return ep_events_available(ep) || busy_loop_timeout(start_time);
396bf3b9f63SSridhar Samudrala }
397bf3b9f63SSridhar Samudrala 
398bf3b9f63SSridhar Samudrala /*
399bf3b9f63SSridhar Samudrala  * Busy poll if globally on and supporting sockets found && no events,
400bf3b9f63SSridhar Samudrala  * busy loop will return if need_resched or ep_events_available.
401bf3b9f63SSridhar Samudrala  *
402bf3b9f63SSridhar Samudrala  * we must do our busy polling with irqs enabled
403bf3b9f63SSridhar Samudrala  */
ep_busy_loop(struct eventpoll * ep,int nonblock)4041493c47fSSoheil Hassas Yeganeh static bool ep_busy_loop(struct eventpoll *ep, int nonblock)
405bf3b9f63SSridhar Samudrala {
406bf3b9f63SSridhar Samudrala 	unsigned int napi_id = READ_ONCE(ep->napi_id);
407bf3b9f63SSridhar Samudrala 
4081493c47fSSoheil Hassas Yeganeh 	if ((napi_id >= MIN_NAPI_ID) && net_busy_loop_on()) {
4097c951cafSBjörn Töpel 		napi_busy_loop(napi_id, nonblock ? NULL : ep_busy_loop_end, ep, false,
4107c951cafSBjörn Töpel 			       BUSY_POLL_BUDGET);
4111493c47fSSoheil Hassas Yeganeh 		if (ep_events_available(ep))
4121493c47fSSoheil Hassas Yeganeh 			return true;
4131493c47fSSoheil Hassas Yeganeh 		/*
4141493c47fSSoheil Hassas Yeganeh 		 * Busy poll timed out.  Drop NAPI ID for now, we can add
4151493c47fSSoheil Hassas Yeganeh 		 * it back in when we have moved a socket with a valid NAPI
4161493c47fSSoheil Hassas Yeganeh 		 * ID onto the ready list.
4171493c47fSSoheil Hassas Yeganeh 		 */
418bf3b9f63SSridhar Samudrala 		ep->napi_id = 0;
4191493c47fSSoheil Hassas Yeganeh 		return false;
4201493c47fSSoheil Hassas Yeganeh 	}
4211493c47fSSoheil Hassas Yeganeh 	return false;
422bf3b9f63SSridhar Samudrala }
423bf3b9f63SSridhar Samudrala 
424bf3b9f63SSridhar Samudrala /*
425bf3b9f63SSridhar Samudrala  * Set epoll busy poll NAPI ID from sk.
426bf3b9f63SSridhar Samudrala  */
ep_set_busy_poll_napi_id(struct epitem * epi)427bf3b9f63SSridhar Samudrala static inline void ep_set_busy_poll_napi_id(struct epitem *epi)
428bf3b9f63SSridhar Samudrala {
429bf3b9f63SSridhar Samudrala 	struct eventpoll *ep;
430bf3b9f63SSridhar Samudrala 	unsigned int napi_id;
431bf3b9f63SSridhar Samudrala 	struct socket *sock;
432bf3b9f63SSridhar Samudrala 	struct sock *sk;
433bf3b9f63SSridhar Samudrala 
434bf3b9f63SSridhar Samudrala 	if (!net_busy_loop_on())
435bf3b9f63SSridhar Samudrala 		return;
436bf3b9f63SSridhar Samudrala 
437dba4a925SFlorent Revest 	sock = sock_from_file(epi->ffd.file);
438bf3b9f63SSridhar Samudrala 	if (!sock)
439bf3b9f63SSridhar Samudrala 		return;
440bf3b9f63SSridhar Samudrala 
441bf3b9f63SSridhar Samudrala 	sk = sock->sk;
442bf3b9f63SSridhar Samudrala 	if (!sk)
443bf3b9f63SSridhar Samudrala 		return;
444bf3b9f63SSridhar Samudrala 
445bf3b9f63SSridhar Samudrala 	napi_id = READ_ONCE(sk->sk_napi_id);
446bf3b9f63SSridhar Samudrala 	ep = epi->ep;
447bf3b9f63SSridhar Samudrala 
448bf3b9f63SSridhar Samudrala 	/* Non-NAPI IDs can be rejected
449bf3b9f63SSridhar Samudrala 	 *	or
450bf3b9f63SSridhar Samudrala 	 * Nothing to do if we already have this ID
451bf3b9f63SSridhar Samudrala 	 */
452bf3b9f63SSridhar Samudrala 	if (napi_id < MIN_NAPI_ID || napi_id == ep->napi_id)
453bf3b9f63SSridhar Samudrala 		return;
454bf3b9f63SSridhar Samudrala 
455bf3b9f63SSridhar Samudrala 	/* record NAPI ID for use in next busy poll */
456bf3b9f63SSridhar Samudrala 	ep->napi_id = napi_id;
457bf3b9f63SSridhar Samudrala }
458bf3b9f63SSridhar Samudrala 
459514056d5SDavidlohr Bueso #else
460514056d5SDavidlohr Bueso 
ep_busy_loop(struct eventpoll * ep,int nonblock)4611493c47fSSoheil Hassas Yeganeh static inline bool ep_busy_loop(struct eventpoll *ep, int nonblock)
462514056d5SDavidlohr Bueso {
4631493c47fSSoheil Hassas Yeganeh 	return false;
464514056d5SDavidlohr Bueso }
465514056d5SDavidlohr Bueso 
ep_set_busy_poll_napi_id(struct epitem * epi)466514056d5SDavidlohr Bueso static inline void ep_set_busy_poll_napi_id(struct epitem *epi)
467514056d5SDavidlohr Bueso {
468514056d5SDavidlohr Bueso }
469514056d5SDavidlohr Bueso 
470514056d5SDavidlohr Bueso #endif /* CONFIG_NET_RX_BUSY_POLL */
471514056d5SDavidlohr Bueso 
47202edc6fcSSteven Rostedt /*
47302edc6fcSSteven Rostedt  * As described in commit 0ccf831cb lockdep: annotate epoll
47402edc6fcSSteven Rostedt  * the use of wait queues used by epoll is done in a very controlled
47502edc6fcSSteven Rostedt  * manner. Wake ups can nest inside each other, but are never done
47602edc6fcSSteven Rostedt  * with the same locking. For example:
47702edc6fcSSteven Rostedt  *
47802edc6fcSSteven Rostedt  *   dfd = socket(...);
47902edc6fcSSteven Rostedt  *   efd1 = epoll_create();
48002edc6fcSSteven Rostedt  *   efd2 = epoll_create();
48102edc6fcSSteven Rostedt  *   epoll_ctl(efd1, EPOLL_CTL_ADD, dfd, ...);
48202edc6fcSSteven Rostedt  *   epoll_ctl(efd2, EPOLL_CTL_ADD, efd1, ...);
48302edc6fcSSteven Rostedt  *
48402edc6fcSSteven Rostedt  * When a packet arrives to the device underneath "dfd", the net code will
48502edc6fcSSteven Rostedt  * issue a wake_up() on its poll wake list. Epoll (efd1) has installed a
48602edc6fcSSteven Rostedt  * callback wakeup entry on that queue, and the wake_up() performed by the
48702edc6fcSSteven Rostedt  * "dfd" net code will end up in ep_poll_callback(). At this point epoll
48802edc6fcSSteven Rostedt  * (efd1) notices that it may have some event ready, so it needs to wake up
48902edc6fcSSteven Rostedt  * the waiters on its poll wait list (efd2). So it calls ep_poll_safewake()
49002edc6fcSSteven Rostedt  * that ends up in another wake_up(), after having checked about the
4917059a9aaSChangcheng Liu  * recursion constraints. That are, no more than EP_MAX_NESTS, to avoid
4927059a9aaSChangcheng Liu  * stack blasting.
49302edc6fcSSteven Rostedt  *
49402edc6fcSSteven Rostedt  * When CONFIG_DEBUG_LOCK_ALLOC is enabled, make sure lockdep can handle
49502edc6fcSSteven Rostedt  * this special case of epoll.
49602edc6fcSSteven Rostedt  */
4972dfa4eeaSDavide Libenzi #ifdef CONFIG_DEBUG_LOCK_ALLOC
4982dfa4eeaSDavide Libenzi 
ep_poll_safewake(struct eventpoll * ep,struct epitem * epi,unsigned pollflags)499caf1aeafSJens Axboe static void ep_poll_safewake(struct eventpoll *ep, struct epitem *epi,
500caf1aeafSJens Axboe 			     unsigned pollflags)
5011da177e4SLinus Torvalds {
502efcdd350SJason Baron 	struct eventpoll *ep_src;
503f6520c52SJason Baron 	unsigned long flags;
504efcdd350SJason Baron 	u8 nests = 0;
5053fe4a975SDavide Libenzi 
506efcdd350SJason Baron 	/*
507efcdd350SJason Baron 	 * To set the subclass or nesting level for spin_lock_irqsave_nested()
508efcdd350SJason Baron 	 * it might be natural to create a per-cpu nest count. However, since
509efcdd350SJason Baron 	 * we can recurse on ep->poll_wait.lock, and a non-raw spinlock can
510efcdd350SJason Baron 	 * schedule() in the -rt kernel, the per-cpu variable are no longer
511efcdd350SJason Baron 	 * protected. Thus, we are introducing a per eventpoll nest field.
512efcdd350SJason Baron 	 * If we are not being call from ep_poll_callback(), epi is NULL and
513efcdd350SJason Baron 	 * we are at the first level of nesting, 0. Otherwise, we are being
514efcdd350SJason Baron 	 * called from ep_poll_callback() and if a previous wakeup source is
515efcdd350SJason Baron 	 * not an epoll file itself, we are at depth 1 since the wakeup source
516efcdd350SJason Baron 	 * is depth 0. If the wakeup source is a previous epoll file in the
517efcdd350SJason Baron 	 * wakeup chain then we use its nests value and record ours as
518efcdd350SJason Baron 	 * nests + 1. The previous epoll file nests value is stable since its
519efcdd350SJason Baron 	 * already holding its own poll_wait.lock.
520efcdd350SJason Baron 	 */
521efcdd350SJason Baron 	if (epi) {
522efcdd350SJason Baron 		if ((is_file_epoll(epi->ffd.file))) {
523efcdd350SJason Baron 			ep_src = epi->ffd.file->private_data;
524efcdd350SJason Baron 			nests = ep_src->nests;
525efcdd350SJason Baron 		} else {
526efcdd350SJason Baron 			nests = 1;
527efcdd350SJason Baron 		}
528efcdd350SJason Baron 	}
529efcdd350SJason Baron 	spin_lock_irqsave_nested(&ep->poll_wait.lock, flags, nests);
530efcdd350SJason Baron 	ep->nests = nests + 1;
531caf1aeafSJens Axboe 	wake_up_locked_poll(&ep->poll_wait, EPOLLIN | pollflags);
532efcdd350SJason Baron 	ep->nests = 0;
533efcdd350SJason Baron 	spin_unlock_irqrestore(&ep->poll_wait.lock, flags);
5341da177e4SLinus Torvalds }
5351da177e4SLinus Torvalds 
53657a173bdSJason Baron #else
53757a173bdSJason Baron 
ep_poll_safewake(struct eventpoll * ep,struct epitem * epi,__poll_t pollflags)538caf1aeafSJens Axboe static void ep_poll_safewake(struct eventpoll *ep, struct epitem *epi,
53938f1755aSMin-Hua Chen 			     __poll_t pollflags)
54057a173bdSJason Baron {
541caf1aeafSJens Axboe 	wake_up_poll(&ep->poll_wait, EPOLLIN | pollflags);
54257a173bdSJason Baron }
54357a173bdSJason Baron 
54457a173bdSJason Baron #endif
54557a173bdSJason Baron 
ep_remove_wait_queue(struct eppoll_entry * pwq)546971316f0SOleg Nesterov static void ep_remove_wait_queue(struct eppoll_entry *pwq)
547971316f0SOleg Nesterov {
548971316f0SOleg Nesterov 	wait_queue_head_t *whead;
549971316f0SOleg Nesterov 
550971316f0SOleg Nesterov 	rcu_read_lock();
551138e4ad6SOleg Nesterov 	/*
552138e4ad6SOleg Nesterov 	 * If it is cleared by POLLFREE, it should be rcu-safe.
553138e4ad6SOleg Nesterov 	 * If we read NULL we need a barrier paired with
554138e4ad6SOleg Nesterov 	 * smp_store_release() in ep_poll_callback(), otherwise
555138e4ad6SOleg Nesterov 	 * we rely on whead->lock.
556138e4ad6SOleg Nesterov 	 */
557138e4ad6SOleg Nesterov 	whead = smp_load_acquire(&pwq->whead);
558971316f0SOleg Nesterov 	if (whead)
559971316f0SOleg Nesterov 		remove_wait_queue(whead, &pwq->wait);
560971316f0SOleg Nesterov 	rcu_read_unlock();
561971316f0SOleg Nesterov }
562971316f0SOleg Nesterov 
5631da177e4SLinus Torvalds /*
564d1bc90ddSTony Battersby  * This function unregisters poll callbacks from the associated file
56558c9b016SPaolo Abeni  * descriptor.  Must be called with "mtx" held.
5661da177e4SLinus Torvalds  */
ep_unregister_pollwait(struct eventpoll * ep,struct epitem * epi)5677699acd1SDavide Libenzi static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi)
5681da177e4SLinus Torvalds {
56980285b75SAl Viro 	struct eppoll_entry **p = &epi->pwqlist;
5707699acd1SDavide Libenzi 	struct eppoll_entry *pwq;
5711da177e4SLinus Torvalds 
57280285b75SAl Viro 	while ((pwq = *p) != NULL) {
57380285b75SAl Viro 		*p = pwq->next;
574971316f0SOleg Nesterov 		ep_remove_wait_queue(pwq);
5757699acd1SDavide Libenzi 		kmem_cache_free(pwq_cache, pwq);
5761da177e4SLinus Torvalds 	}
5771da177e4SLinus Torvalds }
5781da177e4SLinus Torvalds 
579eea1d585SEric Wong /* call only when ep->mtx is held */
ep_wakeup_source(struct epitem * epi)580eea1d585SEric Wong static inline struct wakeup_source *ep_wakeup_source(struct epitem *epi)
581eea1d585SEric Wong {
582eea1d585SEric Wong 	return rcu_dereference_check(epi->ws, lockdep_is_held(&epi->ep->mtx));
583eea1d585SEric Wong }
584eea1d585SEric Wong 
585eea1d585SEric Wong /* call only when ep->mtx is held */
ep_pm_stay_awake(struct epitem * epi)586eea1d585SEric Wong static inline void ep_pm_stay_awake(struct epitem *epi)
587eea1d585SEric Wong {
588eea1d585SEric Wong 	struct wakeup_source *ws = ep_wakeup_source(epi);
589eea1d585SEric Wong 
590eea1d585SEric Wong 	if (ws)
591eea1d585SEric Wong 		__pm_stay_awake(ws);
592eea1d585SEric Wong }
593eea1d585SEric Wong 
ep_has_wakeup_source(struct epitem * epi)594eea1d585SEric Wong static inline bool ep_has_wakeup_source(struct epitem *epi)
595eea1d585SEric Wong {
596eea1d585SEric Wong 	return rcu_access_pointer(epi->ws) ? true : false;
597eea1d585SEric Wong }
598eea1d585SEric Wong 
599eea1d585SEric Wong /* call when ep->mtx cannot be held (ep_poll_callback) */
ep_pm_stay_awake_rcu(struct epitem * epi)600eea1d585SEric Wong static inline void ep_pm_stay_awake_rcu(struct epitem *epi)
601eea1d585SEric Wong {
602eea1d585SEric Wong 	struct wakeup_source *ws;
603eea1d585SEric Wong 
604eea1d585SEric Wong 	rcu_read_lock();
605eea1d585SEric Wong 	ws = rcu_dereference(epi->ws);
606eea1d585SEric Wong 	if (ws)
607eea1d585SEric Wong 		__pm_stay_awake(ws);
608eea1d585SEric Wong 	rcu_read_unlock();
609eea1d585SEric Wong }
610eea1d585SEric Wong 
61192e64178SDavidlohr Bueso 
6125071f97eSDavide Libenzi /*
61357804b1cSAl Viro  * ep->mutex needs to be held because we could be hit by
614e057e15fSTony Battersby  * eventpoll_release_file() and epoll_ctl().
6155071f97eSDavide Libenzi  */
ep_start_scan(struct eventpoll * ep,struct list_head * txlist)61657804b1cSAl Viro static void ep_start_scan(struct eventpoll *ep, struct list_head *txlist)
61757804b1cSAl Viro {
6185071f97eSDavide Libenzi 	/*
6195071f97eSDavide Libenzi 	 * Steal the ready list, and re-init the original one to the
6205071f97eSDavide Libenzi 	 * empty list. Also, set ep->ovflist to NULL so that events
6215071f97eSDavide Libenzi 	 * happening while looping w/out locks, are not lost. We cannot
6225071f97eSDavide Libenzi 	 * have the poll callback to queue directly on ep->rdllist,
6235071f97eSDavide Libenzi 	 * because we want the "sproc" callback to be able to do it
6245071f97eSDavide Libenzi 	 * in a lockless way.
6255071f97eSDavide Libenzi 	 */
62657804b1cSAl Viro 	lockdep_assert_irqs_enabled();
627a218cc49SRoman Penyaev 	write_lock_irq(&ep->lock);
628db502f8aSAl Viro 	list_splice_init(&ep->rdllist, txlist);
629c5a282e9SDavidlohr Bueso 	WRITE_ONCE(ep->ovflist, NULL);
630a218cc49SRoman Penyaev 	write_unlock_irq(&ep->lock);
631db502f8aSAl Viro }
6325071f97eSDavide Libenzi 
ep_done_scan(struct eventpoll * ep,struct list_head * txlist)633db502f8aSAl Viro static void ep_done_scan(struct eventpoll *ep,
634db502f8aSAl Viro 			 struct list_head *txlist)
635db502f8aSAl Viro {
636db502f8aSAl Viro 	struct epitem *epi, *nepi;
6375071f97eSDavide Libenzi 
638a218cc49SRoman Penyaev 	write_lock_irq(&ep->lock);
6395071f97eSDavide Libenzi 	/*
6405071f97eSDavide Libenzi 	 * During the time we spent inside the "sproc" callback, some
6415071f97eSDavide Libenzi 	 * other events might have been queued by the poll callback.
6425071f97eSDavide Libenzi 	 * We re-insert them inside the main ready-list here.
6435071f97eSDavide Libenzi 	 */
644c5a282e9SDavidlohr Bueso 	for (nepi = READ_ONCE(ep->ovflist); (epi = nepi) != NULL;
6455071f97eSDavide Libenzi 	     nepi = epi->next, epi->next = EP_UNACTIVE_PTR) {
6465071f97eSDavide Libenzi 		/*
6475071f97eSDavide Libenzi 		 * We need to check if the item is already in the list.
6485071f97eSDavide Libenzi 		 * During the "sproc" callback execution time, items are
6495071f97eSDavide Libenzi 		 * queued into ->ovflist but the "txlist" might already
6505071f97eSDavide Libenzi 		 * contain them, and the list_splice() below takes care of them.
6515071f97eSDavide Libenzi 		 */
652992991c0SDavidlohr Bueso 		if (!ep_is_linked(epi)) {
653c141175dSRoman Penyaev 			/*
654c141175dSRoman Penyaev 			 * ->ovflist is LIFO, so we have to reverse it in order
655c141175dSRoman Penyaev 			 * to keep in FIFO.
656c141175dSRoman Penyaev 			 */
657c141175dSRoman Penyaev 			list_add(&epi->rdllink, &ep->rdllist);
658eea1d585SEric Wong 			ep_pm_stay_awake(epi);
6594d7e30d9SArve Hjønnevåg 		}
6605071f97eSDavide Libenzi 	}
6615071f97eSDavide Libenzi 	/*
6625071f97eSDavide Libenzi 	 * We need to set back ep->ovflist to EP_UNACTIVE_PTR, so that after
6635071f97eSDavide Libenzi 	 * releasing the lock, events will be queued in the normal way inside
6645071f97eSDavide Libenzi 	 * ep->rdllist.
6655071f97eSDavide Libenzi 	 */
666c5a282e9SDavidlohr Bueso 	WRITE_ONCE(ep->ovflist, EP_UNACTIVE_PTR);
6675071f97eSDavide Libenzi 
6685071f97eSDavide Libenzi 	/*
6695071f97eSDavide Libenzi 	 * Quickly re-inject items left on "txlist".
6705071f97eSDavide Libenzi 	 */
671db502f8aSAl Viro 	list_splice(txlist, &ep->rdllist);
6724d7e30d9SArve Hjønnevåg 	__pm_relax(ep->ws);
6737fab29e3SDavidlohr Bueso 
6747fab29e3SDavidlohr Bueso 	if (!list_empty(&ep->rdllist)) {
6757fab29e3SDavidlohr Bueso 		if (waitqueue_active(&ep->wq))
6767fab29e3SDavidlohr Bueso 			wake_up(&ep->wq);
6777fab29e3SDavidlohr Bueso 	}
6787fab29e3SDavidlohr Bueso 
679a218cc49SRoman Penyaev 	write_unlock_irq(&ep->lock);
6805071f97eSDavide Libenzi }
6815071f97eSDavide Libenzi 
epi_rcu_free(struct rcu_head * head)682ae10b2b4SJason Baron static void epi_rcu_free(struct rcu_head *head)
683ae10b2b4SJason Baron {
684ae10b2b4SJason Baron 	struct epitem *epi = container_of(head, struct epitem, rcu);
685ae10b2b4SJason Baron 	kmem_cache_free(epi_cache, epi);
686ae10b2b4SJason Baron }
687ae10b2b4SJason Baron 
ep_get(struct eventpoll * ep)68858c9b016SPaolo Abeni static void ep_get(struct eventpoll *ep)
68958c9b016SPaolo Abeni {
69058c9b016SPaolo Abeni 	refcount_inc(&ep->refcount);
69158c9b016SPaolo Abeni }
69258c9b016SPaolo Abeni 
69358c9b016SPaolo Abeni /*
69458c9b016SPaolo Abeni  * Returns true if the event poll can be disposed
69558c9b016SPaolo Abeni  */
ep_refcount_dec_and_test(struct eventpoll * ep)69658c9b016SPaolo Abeni static bool ep_refcount_dec_and_test(struct eventpoll *ep)
69758c9b016SPaolo Abeni {
69858c9b016SPaolo Abeni 	if (!refcount_dec_and_test(&ep->refcount))
69958c9b016SPaolo Abeni 		return false;
70058c9b016SPaolo Abeni 
70158c9b016SPaolo Abeni 	WARN_ON_ONCE(!RB_EMPTY_ROOT(&ep->rbr.rb_root));
70258c9b016SPaolo Abeni 	return true;
70358c9b016SPaolo Abeni }
70458c9b016SPaolo Abeni 
ep_free(struct eventpoll * ep)70558c9b016SPaolo Abeni static void ep_free(struct eventpoll *ep)
70658c9b016SPaolo Abeni {
70758c9b016SPaolo Abeni 	mutex_destroy(&ep->mtx);
70858c9b016SPaolo Abeni 	free_uid(ep->user);
70958c9b016SPaolo Abeni 	wakeup_source_unregister(ep->ws);
71058c9b016SPaolo Abeni 	kfree(ep);
71158c9b016SPaolo Abeni }
71258c9b016SPaolo Abeni 
7131da177e4SLinus Torvalds /*
7147699acd1SDavide Libenzi  * Removes a "struct epitem" from the eventpoll RB tree and deallocates
715c7ea7630SDavide Libenzi  * all the associated resources. Must be called with "mtx" held.
71658c9b016SPaolo Abeni  * If the dying flag is set, do the removal only if force is true.
71758c9b016SPaolo Abeni  * This prevents ep_clear_and_put() from dropping all the ep references
71858c9b016SPaolo Abeni  * while running concurrently with eventpoll_release_file().
71958c9b016SPaolo Abeni  * Returns true if the eventpoll can be disposed.
7207699acd1SDavide Libenzi  */
__ep_remove(struct eventpoll * ep,struct epitem * epi,bool force)72158c9b016SPaolo Abeni static bool __ep_remove(struct eventpoll *ep, struct epitem *epi, bool force)
7227699acd1SDavide Libenzi {
7237699acd1SDavide Libenzi 	struct file *file = epi->ffd.file;
724319c1517SAl Viro 	struct epitems_head *to_free;
725319c1517SAl Viro 	struct hlist_head *head;
7267699acd1SDavide Libenzi 
72792e64178SDavidlohr Bueso 	lockdep_assert_irqs_enabled();
72892e64178SDavidlohr Bueso 
7297699acd1SDavide Libenzi 	/*
730ee8ef0a4SChristoph Hellwig 	 * Removes poll wait queue hooks.
7317699acd1SDavide Libenzi 	 */
7327699acd1SDavide Libenzi 	ep_unregister_pollwait(ep, epi);
7337699acd1SDavide Libenzi 
7347699acd1SDavide Libenzi 	/* Remove the current item from the list of epoll hooks */
73568499914SJonathan Corbet 	spin_lock(&file->f_lock);
73658c9b016SPaolo Abeni 	if (epi->dying && !force) {
73758c9b016SPaolo Abeni 		spin_unlock(&file->f_lock);
73858c9b016SPaolo Abeni 		return false;
73958c9b016SPaolo Abeni 	}
74058c9b016SPaolo Abeni 
741319c1517SAl Viro 	to_free = NULL;
742319c1517SAl Viro 	head = file->f_ep;
743319c1517SAl Viro 	if (head->first == &epi->fllink && !epi->fllink.next) {
74461005057SChristian Brauner 		/* See eventpoll_release() for details. */
74561005057SChristian Brauner 		WRITE_ONCE(file->f_ep, NULL);
746319c1517SAl Viro 		if (!is_file_epoll(file)) {
747319c1517SAl Viro 			struct epitems_head *v;
748319c1517SAl Viro 			v = container_of(head, struct epitems_head, epitems);
749319c1517SAl Viro 			if (!smp_load_acquire(&v->next))
750319c1517SAl Viro 				to_free = v;
751319c1517SAl Viro 		}
752319c1517SAl Viro 	}
75344cdc1d9SAl Viro 	hlist_del_rcu(&epi->fllink);
75468499914SJonathan Corbet 	spin_unlock(&file->f_lock);
755319c1517SAl Viro 	free_ephead(to_free);
7567699acd1SDavide Libenzi 
757b2ac2ea6SDavidlohr Bueso 	rb_erase_cached(&epi->rbn, &ep->rbr);
7587699acd1SDavide Libenzi 
759a218cc49SRoman Penyaev 	write_lock_irq(&ep->lock);
760992991c0SDavidlohr Bueso 	if (ep_is_linked(epi))
761c7ea7630SDavide Libenzi 		list_del_init(&epi->rdllink);
762a218cc49SRoman Penyaev 	write_unlock_irq(&ep->lock);
7637699acd1SDavide Libenzi 
764eea1d585SEric Wong 	wakeup_source_unregister(ep_wakeup_source(epi));
765ae10b2b4SJason Baron 	/*
766ae10b2b4SJason Baron 	 * At this point it is safe to free the eventpoll item. Use the union
767ae10b2b4SJason Baron 	 * field epi->rcu, since we are trying to minimize the size of
768ae10b2b4SJason Baron 	 * 'struct epitem'. The 'rbn' field is no longer in use. Protected by
769ae10b2b4SJason Baron 	 * ep->mtx. The rcu read side, reverse_path_check_proc(), does not make
770ae10b2b4SJason Baron 	 * use of the rbn field.
771ae10b2b4SJason Baron 	 */
772ae10b2b4SJason Baron 	call_rcu(&epi->rcu, epi_rcu_free);
7731da177e4SLinus Torvalds 
7741e1c1583SNicholas Piggin 	percpu_counter_dec(&ep->user->epoll_watches);
77558c9b016SPaolo Abeni 	return ep_refcount_dec_and_test(ep);
7761da177e4SLinus Torvalds }
7771da177e4SLinus Torvalds 
77858c9b016SPaolo Abeni /*
77958c9b016SPaolo Abeni  * ep_remove variant for callers owing an additional reference to the ep
78058c9b016SPaolo Abeni  */
ep_remove_safe(struct eventpoll * ep,struct epitem * epi)78158c9b016SPaolo Abeni static void ep_remove_safe(struct eventpoll *ep, struct epitem *epi)
7821da177e4SLinus Torvalds {
78358c9b016SPaolo Abeni 	WARN_ON_ONCE(__ep_remove(ep, epi, false));
78458c9b016SPaolo Abeni }
78558c9b016SPaolo Abeni 
ep_clear_and_put(struct eventpoll * ep)78658c9b016SPaolo Abeni static void ep_clear_and_put(struct eventpoll *ep)
78758c9b016SPaolo Abeni {
78858c9b016SPaolo Abeni 	struct rb_node *rbp, *next;
7891da177e4SLinus Torvalds 	struct epitem *epi;
79058c9b016SPaolo Abeni 	bool dispose;
7911da177e4SLinus Torvalds 
7921da177e4SLinus Torvalds 	/* We need to release all tasks waiting for these file */
7931da177e4SLinus Torvalds 	if (waitqueue_active(&ep->poll_wait))
794caf1aeafSJens Axboe 		ep_poll_safewake(ep, NULL, 0);
7951da177e4SLinus Torvalds 
79658c9b016SPaolo Abeni 	mutex_lock(&ep->mtx);
7971da177e4SLinus Torvalds 
7981da177e4SLinus Torvalds 	/*
7991da177e4SLinus Torvalds 	 * Walks through the whole tree by unregistering poll callbacks.
8001da177e4SLinus Torvalds 	 */
801b2ac2ea6SDavidlohr Bueso 	for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
8021da177e4SLinus Torvalds 		epi = rb_entry(rbp, struct epitem, rbn);
8031da177e4SLinus Torvalds 
8041da177e4SLinus Torvalds 		ep_unregister_pollwait(ep, epi);
80591cf5ab6SEric Dumazet 		cond_resched();
8061da177e4SLinus Torvalds 	}
8071da177e4SLinus Torvalds 
8081da177e4SLinus Torvalds 	/*
80958c9b016SPaolo Abeni 	 * Walks through the whole tree and try to free each "struct epitem".
81058c9b016SPaolo Abeni 	 * Note that ep_remove_safe() will not remove the epitem in case of a
81158c9b016SPaolo Abeni 	 * racing eventpoll_release_file(); the latter will do the removal.
81258c9b016SPaolo Abeni 	 * At this point we are sure no poll callbacks will be lingering around.
81358c9b016SPaolo Abeni 	 * Since we still own a reference to the eventpoll struct, the loop can't
81458c9b016SPaolo Abeni 	 * dispose it.
8151da177e4SLinus Torvalds 	 */
81658c9b016SPaolo Abeni 	for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = next) {
81758c9b016SPaolo Abeni 		next = rb_next(rbp);
8181da177e4SLinus Torvalds 		epi = rb_entry(rbp, struct epitem, rbn);
81958c9b016SPaolo Abeni 		ep_remove_safe(ep, epi);
82091cf5ab6SEric Dumazet 		cond_resched();
8211da177e4SLinus Torvalds 	}
82258c9b016SPaolo Abeni 
82358c9b016SPaolo Abeni 	dispose = ep_refcount_dec_and_test(ep);
824ddf676c3SEric Wong 	mutex_unlock(&ep->mtx);
8251da177e4SLinus Torvalds 
82658c9b016SPaolo Abeni 	if (dispose)
82758c9b016SPaolo Abeni 		ep_free(ep);
8281da177e4SLinus Torvalds }
8291da177e4SLinus Torvalds 
ep_eventpoll_release(struct inode * inode,struct file * file)8307699acd1SDavide Libenzi static int ep_eventpoll_release(struct inode *inode, struct file *file)
8317699acd1SDavide Libenzi {
8327699acd1SDavide Libenzi 	struct eventpoll *ep = file->private_data;
8337699acd1SDavide Libenzi 
834f0ee9aabSDavide Libenzi 	if (ep)
83558c9b016SPaolo Abeni 		ep_clear_and_put(ep);
8367699acd1SDavide Libenzi 
8377699acd1SDavide Libenzi 	return 0;
8387699acd1SDavide Libenzi }
8397699acd1SDavide Libenzi 
8402c0b71c1SAl Viro static __poll_t ep_item_poll(const struct epitem *epi, poll_table *pt, int depth);
841450d89ecSEric Wong 
__ep_eventpoll_poll(struct file * file,poll_table * wait,int depth)842ad9366b1SAl Viro static __poll_t __ep_eventpoll_poll(struct file *file, poll_table *wait, int depth)
84337b5e521SJason Baron {
844ad9366b1SAl Viro 	struct eventpoll *ep = file->private_data;
845ad9366b1SAl Viro 	LIST_HEAD(txlist);
8465071f97eSDavide Libenzi 	struct epitem *epi, *tmp;
847626cf236SHans Verkuil 	poll_table pt;
8482c0b71c1SAl Viro 	__poll_t res = 0;
8495071f97eSDavide Libenzi 
850626cf236SHans Verkuil 	init_poll_funcptr(&pt, NULL);
851450d89ecSEric Wong 
852ad9366b1SAl Viro 	/* Insert inside our poll wait queue */
853ad9366b1SAl Viro 	poll_wait(file, &ep->poll_wait, wait);
854ad9366b1SAl Viro 
855ad9366b1SAl Viro 	/*
856ad9366b1SAl Viro 	 * Proceed to find out if wanted events are really available inside
857ad9366b1SAl Viro 	 * the ready list.
858ad9366b1SAl Viro 	 */
859ad9366b1SAl Viro 	mutex_lock_nested(&ep->mtx, depth);
860ad9366b1SAl Viro 	ep_start_scan(ep, &txlist);
8612c0b71c1SAl Viro 	list_for_each_entry_safe(epi, tmp, &txlist, rdllink) {
8622c0b71c1SAl Viro 		if (ep_item_poll(epi, &pt, depth + 1)) {
8632c0b71c1SAl Viro 			res = EPOLLIN | EPOLLRDNORM;
8642c0b71c1SAl Viro 			break;
86537b5e521SJason Baron 		} else {
8665071f97eSDavide Libenzi 			/*
8675071f97eSDavide Libenzi 			 * Item has been dropped into the ready list by the poll
8685071f97eSDavide Libenzi 			 * callback, but it's not actually ready, as far as
8695071f97eSDavide Libenzi 			 * caller requested events goes. We can remove it here.
8705071f97eSDavide Libenzi 			 */
871eea1d585SEric Wong 			__pm_relax(ep_wakeup_source(epi));
8725071f97eSDavide Libenzi 			list_del_init(&epi->rdllink);
8735071f97eSDavide Libenzi 		}
874296e236eSDavide Libenzi 	}
875ad9366b1SAl Viro 	ep_done_scan(ep, &txlist);
876ad9366b1SAl Viro 	mutex_unlock(&ep->mtx);
877ad9366b1SAl Viro 	return res;
878ad9366b1SAl Viro }
8795071f97eSDavide Libenzi 
8801da177e4SLinus Torvalds /*
8814f65f4deSLinus Torvalds  * The ffd.file pointer may be in the process of being torn down due to
8824f65f4deSLinus Torvalds  * being closed, but we may not have finished eventpoll_release() yet.
8834f65f4deSLinus Torvalds  *
8844f65f4deSLinus Torvalds  * Normally, even with the atomic_long_inc_not_zero, the file may have
8854f65f4deSLinus Torvalds  * been free'd and then gotten re-allocated to something else (since
8864f65f4deSLinus Torvalds  * files are not RCU-delayed, they are SLAB_TYPESAFE_BY_RCU).
8874f65f4deSLinus Torvalds  *
8884f65f4deSLinus Torvalds  * But for epoll, users hold the ep->mtx mutex, and as such any file in
8894f65f4deSLinus Torvalds  * the process of being free'd will block in eventpoll_release_file()
8904f65f4deSLinus Torvalds  * and thus the underlying file allocation will not be free'd, and the
8914f65f4deSLinus Torvalds  * file re-use cannot happen.
8924f65f4deSLinus Torvalds  *
8934f65f4deSLinus Torvalds  * For the same reason we can avoid a rcu_read_lock() around the
8944f65f4deSLinus Torvalds  * operation - 'ffd.file' cannot go away even if the refcount has
8954f65f4deSLinus Torvalds  * reached zero (but we must still not call out to ->poll() functions
8964f65f4deSLinus Torvalds  * etc).
8974f65f4deSLinus Torvalds  */
epi_fget(const struct epitem * epi)8984f65f4deSLinus Torvalds static struct file *epi_fget(const struct epitem *epi)
8994f65f4deSLinus Torvalds {
9004f65f4deSLinus Torvalds 	struct file *file;
9014f65f4deSLinus Torvalds 
9024f65f4deSLinus Torvalds 	file = epi->ffd.file;
9034f65f4deSLinus Torvalds 	if (!atomic_long_inc_not_zero(&file->f_count))
9044f65f4deSLinus Torvalds 		file = NULL;
9054f65f4deSLinus Torvalds 	return file;
9064f65f4deSLinus Torvalds }
9074f65f4deSLinus Torvalds 
9084f65f4deSLinus Torvalds /*
9091da177e4SLinus Torvalds  * Differs from ep_eventpoll_poll() in that internal callers already have
9101da177e4SLinus Torvalds  * the ep->mtx so we need to start from depth=1, such that mutex_lock_nested()
9111da177e4SLinus Torvalds  * is correctly annotated.
9121da177e4SLinus Torvalds  */
ep_item_poll(const struct epitem * epi,poll_table * pt,int depth)9131da177e4SLinus Torvalds static __poll_t ep_item_poll(const struct epitem *epi, poll_table *pt,
9141da177e4SLinus Torvalds 				 int depth)
9151da177e4SLinus Torvalds {
9164f65f4deSLinus Torvalds 	struct file *file = epi_fget(epi);
9171ec09974SAl Viro 	__poll_t res;
9181da177e4SLinus Torvalds 
9194f65f4deSLinus Torvalds 	/*
9204f65f4deSLinus Torvalds 	 * We could return EPOLLERR | EPOLLHUP or something, but let's
9214f65f4deSLinus Torvalds 	 * treat this more as "file doesn't exist, poll didn't happen".
9224f65f4deSLinus Torvalds 	 */
9234f65f4deSLinus Torvalds 	if (!file)
9244f65f4deSLinus Torvalds 		return 0;
9254f65f4deSLinus Torvalds 
9261da177e4SLinus Torvalds 	pt->_key = epi->event.events;
927ad9366b1SAl Viro 	if (!is_file_epoll(file))
928ad9366b1SAl Viro 		res = vfs_poll(file, pt);
929ad9366b1SAl Viro 	else
930ad9366b1SAl Viro 		res = __ep_eventpoll_poll(file, pt, depth);
9314f65f4deSLinus Torvalds 	fput(file);
9321ec09974SAl Viro 	return res & epi->event.events;
9335071f97eSDavide Libenzi }
9345071f97eSDavide Libenzi 
ep_eventpoll_poll(struct file * file,poll_table * wait)935a11e1d43SLinus Torvalds static __poll_t ep_eventpoll_poll(struct file *file, poll_table *wait)
9367699acd1SDavide Libenzi {
937ad9366b1SAl Viro 	return __ep_eventpoll_poll(file, wait, 0);
9387699acd1SDavide Libenzi }
9397699acd1SDavide Libenzi 
940138d22b5SCyrill Gorcunov #ifdef CONFIG_PROC_FS
ep_show_fdinfo(struct seq_file * m,struct file * f)941a3816ab0SJoe Perches static void ep_show_fdinfo(struct seq_file *m, struct file *f)
942138d22b5SCyrill Gorcunov {
943138d22b5SCyrill Gorcunov 	struct eventpoll *ep = f->private_data;
944138d22b5SCyrill Gorcunov 	struct rb_node *rbp;
945138d22b5SCyrill Gorcunov 
946138d22b5SCyrill Gorcunov 	mutex_lock(&ep->mtx);
947b2ac2ea6SDavidlohr Bueso 	for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
948138d22b5SCyrill Gorcunov 		struct epitem *epi = rb_entry(rbp, struct epitem, rbn);
94977493f04SCyrill Gorcunov 		struct inode *inode = file_inode(epi->ffd.file);
950138d22b5SCyrill Gorcunov 
95177493f04SCyrill Gorcunov 		seq_printf(m, "tfd: %8d events: %8x data: %16llx "
95277493f04SCyrill Gorcunov 			   " pos:%lli ino:%lx sdev:%x\n",
953138d22b5SCyrill Gorcunov 			   epi->ffd.fd, epi->event.events,
95477493f04SCyrill Gorcunov 			   (long long)epi->event.data,
95577493f04SCyrill Gorcunov 			   (long long)epi->ffd.file->f_pos,
95677493f04SCyrill Gorcunov 			   inode->i_ino, inode->i_sb->s_dev);
957a3816ab0SJoe Perches 		if (seq_has_overflowed(m))
958138d22b5SCyrill Gorcunov 			break;
959138d22b5SCyrill Gorcunov 	}
960138d22b5SCyrill Gorcunov 	mutex_unlock(&ep->mtx);
961138d22b5SCyrill Gorcunov }
962138d22b5SCyrill Gorcunov #endif
963138d22b5SCyrill Gorcunov 
9647699acd1SDavide Libenzi /* File callbacks that implement the eventpoll file behaviour */
9657699acd1SDavide Libenzi static const struct file_operations eventpoll_fops = {
966138d22b5SCyrill Gorcunov #ifdef CONFIG_PROC_FS
967138d22b5SCyrill Gorcunov 	.show_fdinfo	= ep_show_fdinfo,
968138d22b5SCyrill Gorcunov #endif
9697699acd1SDavide Libenzi 	.release	= ep_eventpoll_release,
970a11e1d43SLinus Torvalds 	.poll		= ep_eventpoll_poll,
9716038f373SArnd Bergmann 	.llseek		= noop_llseek,
9727699acd1SDavide Libenzi };
9737699acd1SDavide Libenzi 
9747699acd1SDavide Libenzi /*
9757699acd1SDavide Libenzi  * This is called from eventpoll_release() to unlink files from the eventpoll
9767699acd1SDavide Libenzi  * interface. We need to have this facility to cleanup correctly files that are
9777699acd1SDavide Libenzi  * closed without being removed from the eventpoll interface.
9787699acd1SDavide Libenzi  */
eventpoll_release_file(struct file * file)9797699acd1SDavide Libenzi void eventpoll_release_file(struct file *file)
9807699acd1SDavide Libenzi {
9817699acd1SDavide Libenzi 	struct eventpoll *ep;
98244cdc1d9SAl Viro 	struct epitem *epi;
98358c9b016SPaolo Abeni 	bool dispose;
9847699acd1SDavide Libenzi 
9857699acd1SDavide Libenzi 	/*
98658c9b016SPaolo Abeni 	 * Use the 'dying' flag to prevent a concurrent ep_clear_and_put() from
98758c9b016SPaolo Abeni 	 * touching the epitems list before eventpoll_release_file() can access
98858c9b016SPaolo Abeni 	 * the ep->mtx.
9897699acd1SDavide Libenzi 	 */
99058c9b016SPaolo Abeni again:
99158c9b016SPaolo Abeni 	spin_lock(&file->f_lock);
99258c9b016SPaolo Abeni 	if (file->f_ep && file->f_ep->first) {
99358c9b016SPaolo Abeni 		epi = hlist_entry(file->f_ep->first, struct epitem, fllink);
99458c9b016SPaolo Abeni 		epi->dying = true;
99558c9b016SPaolo Abeni 		spin_unlock(&file->f_lock);
99658c9b016SPaolo Abeni 
99758c9b016SPaolo Abeni 		/*
99858c9b016SPaolo Abeni 		 * ep access is safe as we still own a reference to the ep
99958c9b016SPaolo Abeni 		 * struct
100058c9b016SPaolo Abeni 		 */
10017699acd1SDavide Libenzi 		ep = epi->ep;
100258c9b016SPaolo Abeni 		mutex_lock(&ep->mtx);
100358c9b016SPaolo Abeni 		dispose = __ep_remove(ep, epi, true);
1004d47de16cSDavide Libenzi 		mutex_unlock(&ep->mtx);
100558c9b016SPaolo Abeni 
100658c9b016SPaolo Abeni 		if (dispose)
100758c9b016SPaolo Abeni 			ep_free(ep);
100858c9b016SPaolo Abeni 		goto again;
10097699acd1SDavide Libenzi 	}
101058c9b016SPaolo Abeni 	spin_unlock(&file->f_lock);
10117699acd1SDavide Libenzi }
10127699acd1SDavide Libenzi 
ep_alloc(struct eventpoll ** pep)10137699acd1SDavide Libenzi static int ep_alloc(struct eventpoll **pep)
10147699acd1SDavide Libenzi {
10157ef9964eSDavide Libenzi 	struct eventpoll *ep;
10167699acd1SDavide Libenzi 
10177ef9964eSDavide Libenzi 	ep = kzalloc(sizeof(*ep), GFP_KERNEL);
10187ef9964eSDavide Libenzi 	if (unlikely(!ep))
101905f26f86SZhen Lei 		return -ENOMEM;
10207699acd1SDavide Libenzi 
1021d47de16cSDavide Libenzi 	mutex_init(&ep->mtx);
1022a218cc49SRoman Penyaev 	rwlock_init(&ep->lock);
10237699acd1SDavide Libenzi 	init_waitqueue_head(&ep->wq);
10247699acd1SDavide Libenzi 	init_waitqueue_head(&ep->poll_wait);
10257699acd1SDavide Libenzi 	INIT_LIST_HEAD(&ep->rdllist);
1026b2ac2ea6SDavidlohr Bueso 	ep->rbr = RB_ROOT_CACHED;
1027d47de16cSDavide Libenzi 	ep->ovflist = EP_UNACTIVE_PTR;
102805f26f86SZhen Lei 	ep->user = get_current_user();
102958c9b016SPaolo Abeni 	refcount_set(&ep->refcount, 1);
10307699acd1SDavide Libenzi 
10317699acd1SDavide Libenzi 	*pep = ep;
10327699acd1SDavide Libenzi 
10337699acd1SDavide Libenzi 	return 0;
10347699acd1SDavide Libenzi }
10351da177e4SLinus Torvalds 
10361da177e4SLinus Torvalds /*
1037c7ea7630SDavide Libenzi  * Search the file inside the eventpoll tree. The RB tree operations
1038c7ea7630SDavide Libenzi  * are protected by the "mtx" mutex, and ep_find() must be called with
1039c7ea7630SDavide Libenzi  * "mtx" held.
10401da177e4SLinus Torvalds  */
ep_find(struct eventpoll * ep,struct file * file,int fd)10411da177e4SLinus Torvalds static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
10421da177e4SLinus Torvalds {
10431da177e4SLinus Torvalds 	int kcmp;
10441da177e4SLinus Torvalds 	struct rb_node *rbp;
10451da177e4SLinus Torvalds 	struct epitem *epi, *epir = NULL;
10461da177e4SLinus Torvalds 	struct epoll_filefd ffd;
10471da177e4SLinus Torvalds 
1048b030a4ddSPekka Enberg 	ep_set_ffd(&ffd, file, fd);
1049b2ac2ea6SDavidlohr Bueso 	for (rbp = ep->rbr.rb_root.rb_node; rbp; ) {
10501da177e4SLinus Torvalds 		epi = rb_entry(rbp, struct epitem, rbn);
1051b030a4ddSPekka Enberg 		kcmp = ep_cmp_ffd(&ffd, &epi->ffd);
10521da177e4SLinus Torvalds 		if (kcmp > 0)
10531da177e4SLinus Torvalds 			rbp = rbp->rb_right;
10541da177e4SLinus Torvalds 		else if (kcmp < 0)
10551da177e4SLinus Torvalds 			rbp = rbp->rb_left;
10561da177e4SLinus Torvalds 		else {
10571da177e4SLinus Torvalds 			epir = epi;
10581da177e4SLinus Torvalds 			break;
10591da177e4SLinus Torvalds 		}
10601da177e4SLinus Torvalds 	}
10611da177e4SLinus Torvalds 
10621da177e4SLinus Torvalds 	return epir;
10631da177e4SLinus Torvalds }
10641da177e4SLinus Torvalds 
1065bfe3911aSChris Wilson #ifdef CONFIG_KCMP
ep_find_tfd(struct eventpoll * ep,int tfd,unsigned long toff)10660791e364SCyrill Gorcunov static struct epitem *ep_find_tfd(struct eventpoll *ep, int tfd, unsigned long toff)
10670791e364SCyrill Gorcunov {
10680791e364SCyrill Gorcunov 	struct rb_node *rbp;
10690791e364SCyrill Gorcunov 	struct epitem *epi;
10700791e364SCyrill Gorcunov 
1071b2ac2ea6SDavidlohr Bueso 	for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
10720791e364SCyrill Gorcunov 		epi = rb_entry(rbp, struct epitem, rbn);
10730791e364SCyrill Gorcunov 		if (epi->ffd.fd == tfd) {
10740791e364SCyrill Gorcunov 			if (toff == 0)
10750791e364SCyrill Gorcunov 				return epi;
10760791e364SCyrill Gorcunov 			else
10770791e364SCyrill Gorcunov 				toff--;
10780791e364SCyrill Gorcunov 		}
10790791e364SCyrill Gorcunov 		cond_resched();
10800791e364SCyrill Gorcunov 	}
10810791e364SCyrill Gorcunov 
10820791e364SCyrill Gorcunov 	return NULL;
10830791e364SCyrill Gorcunov }
10840791e364SCyrill Gorcunov 
get_epoll_tfile_raw_ptr(struct file * file,int tfd,unsigned long toff)10850791e364SCyrill Gorcunov struct file *get_epoll_tfile_raw_ptr(struct file *file, int tfd,
10860791e364SCyrill Gorcunov 				     unsigned long toff)
10870791e364SCyrill Gorcunov {
10880791e364SCyrill Gorcunov 	struct file *file_raw;
10890791e364SCyrill Gorcunov 	struct eventpoll *ep;
10900791e364SCyrill Gorcunov 	struct epitem *epi;
10910791e364SCyrill Gorcunov 
10920791e364SCyrill Gorcunov 	if (!is_file_epoll(file))
10930791e364SCyrill Gorcunov 		return ERR_PTR(-EINVAL);
10940791e364SCyrill Gorcunov 
10950791e364SCyrill Gorcunov 	ep = file->private_data;
10960791e364SCyrill Gorcunov 
10970791e364SCyrill Gorcunov 	mutex_lock(&ep->mtx);
10980791e364SCyrill Gorcunov 	epi = ep_find_tfd(ep, tfd, toff);
10990791e364SCyrill Gorcunov 	if (epi)
11000791e364SCyrill Gorcunov 		file_raw = epi->ffd.file;
11010791e364SCyrill Gorcunov 	else
11020791e364SCyrill Gorcunov 		file_raw = ERR_PTR(-ENOENT);
11030791e364SCyrill Gorcunov 	mutex_unlock(&ep->mtx);
11040791e364SCyrill Gorcunov 
11050791e364SCyrill Gorcunov 	return file_raw;
11060791e364SCyrill Gorcunov }
1107bfe3911aSChris Wilson #endif /* CONFIG_KCMP */
11080791e364SCyrill Gorcunov 
1109a6c67feeSRandy Dunlap /*
1110a218cc49SRoman Penyaev  * Adds a new entry to the tail of the list in a lockless way, i.e.
1111a218cc49SRoman Penyaev  * multiple CPUs are allowed to call this function concurrently.
1112a218cc49SRoman Penyaev  *
1113a218cc49SRoman Penyaev  * Beware: it is necessary to prevent any other modifications of the
1114a218cc49SRoman Penyaev  *         existing list until all changes are completed, in other words
1115a218cc49SRoman Penyaev  *         concurrent list_add_tail_lockless() calls should be protected
1116a218cc49SRoman Penyaev  *         with a read lock, where write lock acts as a barrier which
1117a218cc49SRoman Penyaev  *         makes sure all list_add_tail_lockless() calls are fully
1118a218cc49SRoman Penyaev  *         completed.
1119a218cc49SRoman Penyaev  *
1120a218cc49SRoman Penyaev  *        Also an element can be locklessly added to the list only in one
1121a6c67feeSRandy Dunlap  *        direction i.e. either to the tail or to the head, otherwise
1122a218cc49SRoman Penyaev  *        concurrent access will corrupt the list.
1123a218cc49SRoman Penyaev  *
1124a6c67feeSRandy Dunlap  * Return: %false if element has been already added to the list, %true
1125a218cc49SRoman Penyaev  * otherwise.
1126a218cc49SRoman Penyaev  */
list_add_tail_lockless(struct list_head * new,struct list_head * head)1127a218cc49SRoman Penyaev static inline bool list_add_tail_lockless(struct list_head *new,
1128a218cc49SRoman Penyaev 					  struct list_head *head)
1129a218cc49SRoman Penyaev {
1130a218cc49SRoman Penyaev 	struct list_head *prev;
1131a218cc49SRoman Penyaev 
1132a218cc49SRoman Penyaev 	/*
1133a218cc49SRoman Penyaev 	 * This is simple 'new->next = head' operation, but cmpxchg()
1134a218cc49SRoman Penyaev 	 * is used in order to detect that same element has been just
1135a218cc49SRoman Penyaev 	 * added to the list from another CPU: the winner observes
1136a218cc49SRoman Penyaev 	 * new->next == new.
1137a218cc49SRoman Penyaev 	 */
1138693fc06eSUros Bizjak 	if (!try_cmpxchg(&new->next, &new, head))
1139a218cc49SRoman Penyaev 		return false;
1140a218cc49SRoman Penyaev 
1141a218cc49SRoman Penyaev 	/*
1142a218cc49SRoman Penyaev 	 * Initially ->next of a new element must be updated with the head
1143a218cc49SRoman Penyaev 	 * (we are inserting to the tail) and only then pointers are atomically
1144a218cc49SRoman Penyaev 	 * exchanged.  XCHG guarantees memory ordering, thus ->next should be
1145a218cc49SRoman Penyaev 	 * updated before pointers are actually swapped and pointers are
1146a218cc49SRoman Penyaev 	 * swapped before prev->next is updated.
1147a218cc49SRoman Penyaev 	 */
1148a218cc49SRoman Penyaev 
1149a218cc49SRoman Penyaev 	prev = xchg(&head->prev, new);
1150a218cc49SRoman Penyaev 
1151a218cc49SRoman Penyaev 	/*
1152a218cc49SRoman Penyaev 	 * It is safe to modify prev->next and new->prev, because a new element
1153a218cc49SRoman Penyaev 	 * is added only to the tail and new->next is updated before XCHG.
1154a218cc49SRoman Penyaev 	 */
1155a218cc49SRoman Penyaev 
1156a218cc49SRoman Penyaev 	prev->next = new;
1157a218cc49SRoman Penyaev 	new->prev = prev;
1158a218cc49SRoman Penyaev 
1159a218cc49SRoman Penyaev 	return true;
1160a218cc49SRoman Penyaev }
1161a218cc49SRoman Penyaev 
1162a6c67feeSRandy Dunlap /*
1163a218cc49SRoman Penyaev  * Chains a new epi entry to the tail of the ep->ovflist in a lockless way,
1164a218cc49SRoman Penyaev  * i.e. multiple CPUs are allowed to call this function concurrently.
1165a218cc49SRoman Penyaev  *
1166a6c67feeSRandy Dunlap  * Return: %false if epi element has been already chained, %true otherwise.
1167a218cc49SRoman Penyaev  */
chain_epi_lockless(struct epitem * epi)1168a218cc49SRoman Penyaev static inline bool chain_epi_lockless(struct epitem *epi)
1169a218cc49SRoman Penyaev {
1170a218cc49SRoman Penyaev 	struct eventpoll *ep = epi->ep;
1171a218cc49SRoman Penyaev 
11720c54a6a4SKhazhismel Kumykov 	/* Fast preliminary check */
11730c54a6a4SKhazhismel Kumykov 	if (epi->next != EP_UNACTIVE_PTR)
11740c54a6a4SKhazhismel Kumykov 		return false;
11750c54a6a4SKhazhismel Kumykov 
1176a218cc49SRoman Penyaev 	/* Check that the same epi has not been just chained from another CPU */
1177a218cc49SRoman Penyaev 	if (cmpxchg(&epi->next, EP_UNACTIVE_PTR, NULL) != EP_UNACTIVE_PTR)
1178a218cc49SRoman Penyaev 		return false;
1179a218cc49SRoman Penyaev 
1180a218cc49SRoman Penyaev 	/* Atomically exchange tail */
1181a218cc49SRoman Penyaev 	epi->next = xchg(&ep->ovflist, epi);
1182a218cc49SRoman Penyaev 
1183a218cc49SRoman Penyaev 	return true;
1184a218cc49SRoman Penyaev }
1185a218cc49SRoman Penyaev 
11867699acd1SDavide Libenzi /*
11877699acd1SDavide Libenzi  * This is the callback that is passed to the wait queue wakeup
1188bf6a41dbSDaniel Baluta  * mechanism. It is called by the stored file descriptors when they
11897699acd1SDavide Libenzi  * have events to report.
1190a218cc49SRoman Penyaev  *
1191a6c67feeSRandy Dunlap  * This callback takes a read lock in order not to contend with concurrent
1192a6c67feeSRandy Dunlap  * events from another file descriptor, thus all modifications to ->rdllist
1193a218cc49SRoman Penyaev  * or ->ovflist are lockless.  Read lock is paired with the write lock from
1194a218cc49SRoman Penyaev  * ep_scan_ready_list(), which stops all list modifications and guarantees
1195a218cc49SRoman Penyaev  * that lists state is seen correctly.
1196a218cc49SRoman Penyaev  *
1197a218cc49SRoman Penyaev  * Another thing worth to mention is that ep_poll_callback() can be called
1198a218cc49SRoman Penyaev  * concurrently for the same @epi from different CPUs if poll table was inited
1199a218cc49SRoman Penyaev  * with several wait queues entries.  Plural wakeup from different CPUs of a
1200a218cc49SRoman Penyaev  * single wait queue is serialized by wq.lock, but the case when multiple wait
1201a218cc49SRoman Penyaev  * queues are used should be detected accordingly.  This is detected using
1202a218cc49SRoman Penyaev  * cmpxchg() operation.
12037699acd1SDavide Libenzi  */
ep_poll_callback(wait_queue_entry_t * wait,unsigned mode,int sync,void * key)1204ac6424b9SIngo Molnar static int ep_poll_callback(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
12057699acd1SDavide Libenzi {
12067699acd1SDavide Libenzi 	int pwake = 0;
12077699acd1SDavide Libenzi 	struct epitem *epi = ep_item_from_wait(wait);
12087699acd1SDavide Libenzi 	struct eventpoll *ep = epi->ep;
12093ad6f93eSAl Viro 	__poll_t pollflags = key_to_poll(key);
1210a218cc49SRoman Penyaev 	unsigned long flags;
1211df0108c5SJason Baron 	int ewake = 0;
12127699acd1SDavide Libenzi 
1213a218cc49SRoman Penyaev 	read_lock_irqsave(&ep->lock, flags);
12141da177e4SLinus Torvalds 
1215bf3b9f63SSridhar Samudrala 	ep_set_busy_poll_napi_id(epi);
1216bf3b9f63SSridhar Samudrala 
12171da177e4SLinus Torvalds 	/*
12187699acd1SDavide Libenzi 	 * If the event mask does not contain any poll(2) event, we consider the
12197699acd1SDavide Libenzi 	 * descriptor to be disabled. This condition is likely the effect of the
12207699acd1SDavide Libenzi 	 * EPOLLONESHOT bit that disables the descriptor when an event is received,
12217699acd1SDavide Libenzi 	 * until the next EPOLL_CTL_MOD will be issued.
12221da177e4SLinus Torvalds 	 */
12237699acd1SDavide Libenzi 	if (!(epi->event.events & ~EP_PRIVATE_BITS))
1224d47de16cSDavide Libenzi 		goto out_unlock;
1225d47de16cSDavide Libenzi 
1226d47de16cSDavide Libenzi 	/*
12272dfa4eeaSDavide Libenzi 	 * Check the events coming with the callback. At this stage, not
12282dfa4eeaSDavide Libenzi 	 * every device reports the events in the "key" parameter of the
12292dfa4eeaSDavide Libenzi 	 * callback. We need to be able to handle both cases here, hence the
12302dfa4eeaSDavide Libenzi 	 * test for "key" != NULL before the event match test.
12312dfa4eeaSDavide Libenzi 	 */
12323ad6f93eSAl Viro 	if (pollflags && !(pollflags & epi->event.events))
12332dfa4eeaSDavide Libenzi 		goto out_unlock;
12342dfa4eeaSDavide Libenzi 
12352dfa4eeaSDavide Libenzi 	/*
1236bf6a41dbSDaniel Baluta 	 * If we are transferring events to userspace, we can hold no locks
1237d47de16cSDavide Libenzi 	 * (because we're accessing user memory, and because of linux f_op->poll()
1238bf6a41dbSDaniel Baluta 	 * semantics). All the events that happen during that period of time are
1239d47de16cSDavide Libenzi 	 * chained in ep->ovflist and requeued later on.
1240d47de16cSDavide Libenzi 	 */
1241c5a282e9SDavidlohr Bueso 	if (READ_ONCE(ep->ovflist) != EP_UNACTIVE_PTR) {
12420c54a6a4SKhazhismel Kumykov 		if (chain_epi_lockless(epi))
1243c3e320b6SRoman Penyaev 			ep_pm_stay_awake_rcu(epi);
12440c54a6a4SKhazhismel Kumykov 	} else if (!ep_is_linked(epi)) {
12450c54a6a4SKhazhismel Kumykov 		/* In the usual case, add event to ready list. */
12460c54a6a4SKhazhismel Kumykov 		if (list_add_tail_lockless(&epi->rdllink, &ep->rdllist))
1247eea1d585SEric Wong 			ep_pm_stay_awake_rcu(epi);
12484d7e30d9SArve Hjønnevåg 	}
12491da177e4SLinus Torvalds 
12501da177e4SLinus Torvalds 	/*
12517699acd1SDavide Libenzi 	 * Wake up ( if active ) both the eventpoll wait list and the ->poll()
12527699acd1SDavide Libenzi 	 * wait list.
12531da177e4SLinus Torvalds 	 */
1254df0108c5SJason Baron 	if (waitqueue_active(&ep->wq)) {
1255b6a515c8SJason Baron 		if ((epi->event.events & EPOLLEXCLUSIVE) &&
12563ad6f93eSAl Viro 					!(pollflags & POLLFREE)) {
12573ad6f93eSAl Viro 			switch (pollflags & EPOLLINOUT_BITS) {
1258a9a08845SLinus Torvalds 			case EPOLLIN:
1259a9a08845SLinus Torvalds 				if (epi->event.events & EPOLLIN)
1260df0108c5SJason Baron 					ewake = 1;
1261b6a515c8SJason Baron 				break;
1262a9a08845SLinus Torvalds 			case EPOLLOUT:
1263a9a08845SLinus Torvalds 				if (epi->event.events & EPOLLOUT)
1264b6a515c8SJason Baron 					ewake = 1;
1265b6a515c8SJason Baron 				break;
1266b6a515c8SJason Baron 			case 0:
1267b6a515c8SJason Baron 				ewake = 1;
1268b6a515c8SJason Baron 				break;
1269b6a515c8SJason Baron 			}
1270b6a515c8SJason Baron 		}
1271*d9831a65SXuewen Yan 		if (sync)
1272*d9831a65SXuewen Yan 			wake_up_sync(&ep->wq);
1273*d9831a65SXuewen Yan 		else
1274a218cc49SRoman Penyaev 			wake_up(&ep->wq);
1275df0108c5SJason Baron 	}
12767699acd1SDavide Libenzi 	if (waitqueue_active(&ep->poll_wait))
12777699acd1SDavide Libenzi 		pwake++;
12781da177e4SLinus Torvalds 
1279d47de16cSDavide Libenzi out_unlock:
1280a218cc49SRoman Penyaev 	read_unlock_irqrestore(&ep->lock, flags);
12817699acd1SDavide Libenzi 
12827699acd1SDavide Libenzi 	/* We have to call this outside the lock */
12837699acd1SDavide Libenzi 	if (pwake)
1284caf1aeafSJens Axboe 		ep_poll_safewake(ep, epi, pollflags & EPOLL_URING_WAKE);
12857699acd1SDavide Libenzi 
1286138e4ad6SOleg Nesterov 	if (!(epi->event.events & EPOLLEXCLUSIVE))
1287138e4ad6SOleg Nesterov 		ewake = 1;
1288df0108c5SJason Baron 
12893ad6f93eSAl Viro 	if (pollflags & POLLFREE) {
1290138e4ad6SOleg Nesterov 		/*
1291138e4ad6SOleg Nesterov 		 * If we race with ep_remove_wait_queue() it can miss
1292138e4ad6SOleg Nesterov 		 * ->whead = NULL and do another remove_wait_queue() after
1293138e4ad6SOleg Nesterov 		 * us, so we can't use __remove_wait_queue().
1294138e4ad6SOleg Nesterov 		 */
1295138e4ad6SOleg Nesterov 		list_del_init(&wait->entry);
1296138e4ad6SOleg Nesterov 		/*
129758c9b016SPaolo Abeni 		 * ->whead != NULL protects us from the race with
129858c9b016SPaolo Abeni 		 * ep_clear_and_put() or ep_remove(), ep_remove_wait_queue()
129958c9b016SPaolo Abeni 		 * takes whead->lock held by the caller. Once we nullify it,
130058c9b016SPaolo Abeni 		 * nothing protects ep/epi or even wait.
1301138e4ad6SOleg Nesterov 		 */
1302138e4ad6SOleg Nesterov 		smp_store_release(&ep_pwq_from_wait(wait)->whead, NULL);
1303138e4ad6SOleg Nesterov 	}
1304138e4ad6SOleg Nesterov 
1305138e4ad6SOleg Nesterov 	return ewake;
13061da177e4SLinus Torvalds }
13071da177e4SLinus Torvalds 
13081da177e4SLinus Torvalds /*
13091da177e4SLinus Torvalds  * This is the callback that is used to add our wait queue to the
13101da177e4SLinus Torvalds  * target file wakeup lists.
13111da177e4SLinus Torvalds  */
ep_ptable_queue_proc(struct file * file,wait_queue_head_t * whead,poll_table * pt)13121da177e4SLinus Torvalds static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
13131da177e4SLinus Torvalds 				 poll_table *pt)
13141da177e4SLinus Torvalds {
1315364f374fSAl Viro 	struct ep_pqueue *epq = container_of(pt, struct ep_pqueue, pt);
1316364f374fSAl Viro 	struct epitem *epi = epq->epi;
13171da177e4SLinus Torvalds 	struct eppoll_entry *pwq;
13181da177e4SLinus Torvalds 
1319364f374fSAl Viro 	if (unlikely(!epi))	// an earlier allocation has failed
1320364f374fSAl Viro 		return;
1321364f374fSAl Viro 
1322364f374fSAl Viro 	pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL);
1323364f374fSAl Viro 	if (unlikely(!pwq)) {
1324364f374fSAl Viro 		epq->epi = NULL;
1325364f374fSAl Viro 		return;
1326364f374fSAl Viro 	}
1327364f374fSAl Viro 
13281da177e4SLinus Torvalds 	init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
13291da177e4SLinus Torvalds 	pwq->whead = whead;
13301da177e4SLinus Torvalds 	pwq->base = epi;
1331df0108c5SJason Baron 	if (epi->event.events & EPOLLEXCLUSIVE)
1332df0108c5SJason Baron 		add_wait_queue_exclusive(whead, &pwq->wait);
1333df0108c5SJason Baron 	else
13341da177e4SLinus Torvalds 		add_wait_queue(whead, &pwq->wait);
133580285b75SAl Viro 	pwq->next = epi->pwqlist;
133680285b75SAl Viro 	epi->pwqlist = pwq;
1337296e236eSDavide Libenzi }
13381da177e4SLinus Torvalds 
ep_rbtree_insert(struct eventpoll * ep,struct epitem * epi)13391da177e4SLinus Torvalds static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)
13401da177e4SLinus Torvalds {
13411da177e4SLinus Torvalds 	int kcmp;
1342b2ac2ea6SDavidlohr Bueso 	struct rb_node **p = &ep->rbr.rb_root.rb_node, *parent = NULL;
13431da177e4SLinus Torvalds 	struct epitem *epic;
1344b2ac2ea6SDavidlohr Bueso 	bool leftmost = true;
13451da177e4SLinus Torvalds 
13461da177e4SLinus Torvalds 	while (*p) {
13471da177e4SLinus Torvalds 		parent = *p;
13481da177e4SLinus Torvalds 		epic = rb_entry(parent, struct epitem, rbn);
1349b030a4ddSPekka Enberg 		kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd);
1350b2ac2ea6SDavidlohr Bueso 		if (kcmp > 0) {
13511da177e4SLinus Torvalds 			p = &parent->rb_right;
1352b2ac2ea6SDavidlohr Bueso 			leftmost = false;
1353b2ac2ea6SDavidlohr Bueso 		} else
13541da177e4SLinus Torvalds 			p = &parent->rb_left;
13551da177e4SLinus Torvalds 	}
13561da177e4SLinus Torvalds 	rb_link_node(&epi->rbn, parent, p);
1357b2ac2ea6SDavidlohr Bueso 	rb_insert_color_cached(&epi->rbn, &ep->rbr, leftmost);
13581da177e4SLinus Torvalds }
13591da177e4SLinus Torvalds 
1360a80a6b85SAndrew Morton 
1361a80a6b85SAndrew Morton 
136228d82dc1SJason Baron #define PATH_ARR_SIZE 5
136328d82dc1SJason Baron /*
136428d82dc1SJason Baron  * These are the number paths of length 1 to 5, that we are allowing to emanate
136528d82dc1SJason Baron  * from a single file of interest. For example, we allow 1000 paths of length
136628d82dc1SJason Baron  * 1, to emanate from each file of interest. This essentially represents the
136728d82dc1SJason Baron  * potential wakeup paths, which need to be limited in order to avoid massive
136828d82dc1SJason Baron  * uncontrolled wakeup storms. The common use case should be a single ep which
136928d82dc1SJason Baron  * is connected to n file sources. In this case each file source has 1 path
137028d82dc1SJason Baron  * of length 1. Thus, the numbers below should be more than sufficient. These
137128d82dc1SJason Baron  * path limits are enforced during an EPOLL_CTL_ADD operation, since a modify
1372d4cb626dSDavidlohr Bueso  * and delete can't add additional paths. Protected by the epnested_mutex.
137328d82dc1SJason Baron  */
137428d82dc1SJason Baron static const int path_limits[PATH_ARR_SIZE] = { 1000, 500, 100, 50, 10 };
137528d82dc1SJason Baron static int path_count[PATH_ARR_SIZE];
137628d82dc1SJason Baron 
path_count_inc(int nests)137728d82dc1SJason Baron static int path_count_inc(int nests)
137828d82dc1SJason Baron {
137993dc6107SJason Baron 	/* Allow an arbitrary number of depth 1 paths */
138093dc6107SJason Baron 	if (nests == 0)
138193dc6107SJason Baron 		return 0;
138293dc6107SJason Baron 
138328d82dc1SJason Baron 	if (++path_count[nests] > path_limits[nests])
138428d82dc1SJason Baron 		return -1;
138528d82dc1SJason Baron 	return 0;
138628d82dc1SJason Baron }
138728d82dc1SJason Baron 
path_count_init(void)138828d82dc1SJason Baron static void path_count_init(void)
138928d82dc1SJason Baron {
139028d82dc1SJason Baron 	int i;
139128d82dc1SJason Baron 
139228d82dc1SJason Baron 	for (i = 0; i < PATH_ARR_SIZE; i++)
139328d82dc1SJason Baron 		path_count[i] = 0;
139428d82dc1SJason Baron }
139528d82dc1SJason Baron 
reverse_path_check_proc(struct hlist_head * refs,int depth)1396319c1517SAl Viro static int reverse_path_check_proc(struct hlist_head *refs, int depth)
139728d82dc1SJason Baron {
139828d82dc1SJason Baron 	int error = 0;
139928d82dc1SJason Baron 	struct epitem *epi;
140028d82dc1SJason Baron 
14010c320f77SAl Viro 	if (depth > EP_MAX_NESTS) /* too deep nesting */
140299d84d43SAl Viro 		return -1;
140399d84d43SAl Viro 
1404ae10b2b4SJason Baron 	/* CTL_DEL can remove links here, but that can't increase our count */
1405319c1517SAl Viro 	hlist_for_each_entry_rcu(epi, refs, fllink) {
1406319c1517SAl Viro 		struct hlist_head *refs = &epi->ep->refs;
1407319c1517SAl Viro 		if (hlist_empty(refs))
1408d16312a4SAl Viro 			error = path_count_inc(depth);
1409d16312a4SAl Viro 		else
1410319c1517SAl Viro 			error = reverse_path_check_proc(refs, depth + 1);
141128d82dc1SJason Baron 		if (error != 0)
141228d82dc1SJason Baron 			break;
141328d82dc1SJason Baron 	}
141428d82dc1SJason Baron 	return error;
141528d82dc1SJason Baron }
141628d82dc1SJason Baron 
141728d82dc1SJason Baron /**
1418319c1517SAl Viro  * reverse_path_check - The tfile_check_list is list of epitem_head, which have
141928d82dc1SJason Baron  *                      links that are proposed to be newly added. We need to
142028d82dc1SJason Baron  *                      make sure that those added links don't add too many
142128d82dc1SJason Baron  *                      paths such that we will spend all our time waking up
142228d82dc1SJason Baron  *                      eventpoll objects.
142328d82dc1SJason Baron  *
1424a6c67feeSRandy Dunlap  * Return: %zero if the proposed links don't create too many paths,
1425a6c67feeSRandy Dunlap  *	    %-1 otherwise.
142628d82dc1SJason Baron  */
reverse_path_check(void)142728d82dc1SJason Baron static int reverse_path_check(void)
142828d82dc1SJason Baron {
1429319c1517SAl Viro 	struct epitems_head *p;
143028d82dc1SJason Baron 
1431319c1517SAl Viro 	for (p = tfile_check_list; p != EP_UNACTIVE_PTR; p = p->next) {
1432319c1517SAl Viro 		int error;
143328d82dc1SJason Baron 		path_count_init();
1434b62d2706SAl Viro 		rcu_read_lock();
1435319c1517SAl Viro 		error = reverse_path_check_proc(&p->epitems, 0);
1436b62d2706SAl Viro 		rcu_read_unlock();
143728d82dc1SJason Baron 		if (error)
143828d82dc1SJason Baron 			return error;
143928d82dc1SJason Baron 	}
1440319c1517SAl Viro 	return 0;
1441319c1517SAl Viro }
144228d82dc1SJason Baron 
ep_create_wakeup_source(struct epitem * epi)14434d7e30d9SArve Hjønnevåg static int ep_create_wakeup_source(struct epitem *epi)
14444d7e30d9SArve Hjønnevåg {
14453701cb59SAl Viro 	struct name_snapshot n;
1446eea1d585SEric Wong 	struct wakeup_source *ws;
14474d7e30d9SArve Hjønnevåg 
14484d7e30d9SArve Hjønnevåg 	if (!epi->ep->ws) {
1449c8377adfSTri Vo 		epi->ep->ws = wakeup_source_register(NULL, "eventpoll");
14504d7e30d9SArve Hjønnevåg 		if (!epi->ep->ws)
14514d7e30d9SArve Hjønnevåg 			return -ENOMEM;
14524d7e30d9SArve Hjønnevåg 	}
14534d7e30d9SArve Hjønnevåg 
14543701cb59SAl Viro 	take_dentry_name_snapshot(&n, epi->ffd.file->f_path.dentry);
14553701cb59SAl Viro 	ws = wakeup_source_register(NULL, n.name.name);
14563701cb59SAl Viro 	release_dentry_name_snapshot(&n);
1457eea1d585SEric Wong 
1458eea1d585SEric Wong 	if (!ws)
14594d7e30d9SArve Hjønnevåg 		return -ENOMEM;
1460eea1d585SEric Wong 	rcu_assign_pointer(epi->ws, ws);
14614d7e30d9SArve Hjønnevåg 
14624d7e30d9SArve Hjønnevåg 	return 0;
14634d7e30d9SArve Hjønnevåg }
14644d7e30d9SArve Hjønnevåg 
1465eea1d585SEric Wong /* rare code path, only used when EPOLL_CTL_MOD removes a wakeup source */
ep_destroy_wakeup_source(struct epitem * epi)1466eea1d585SEric Wong static noinline void ep_destroy_wakeup_source(struct epitem *epi)
14674d7e30d9SArve Hjønnevåg {
1468eea1d585SEric Wong 	struct wakeup_source *ws = ep_wakeup_source(epi);
1469eea1d585SEric Wong 
1470d6d67e72SEric Wong 	RCU_INIT_POINTER(epi->ws, NULL);
1471eea1d585SEric Wong 
1472eea1d585SEric Wong 	/*
1473eea1d585SEric Wong 	 * wait for ep_pm_stay_awake_rcu to finish, synchronize_rcu is
1474eea1d585SEric Wong 	 * used internally by wakeup_source_remove, too (called by
1475eea1d585SEric Wong 	 * wakeup_source_unregister), so we cannot use call_rcu
1476eea1d585SEric Wong 	 */
1477eea1d585SEric Wong 	synchronize_rcu();
1478eea1d585SEric Wong 	wakeup_source_unregister(ws);
14794d7e30d9SArve Hjønnevåg }
14804d7e30d9SArve Hjønnevåg 
attach_epitem(struct file * file,struct epitem * epi)1481319c1517SAl Viro static int attach_epitem(struct file *file, struct epitem *epi)
1482319c1517SAl Viro {
1483319c1517SAl Viro 	struct epitems_head *to_free = NULL;
1484319c1517SAl Viro 	struct hlist_head *head = NULL;
1485319c1517SAl Viro 	struct eventpoll *ep = NULL;
1486319c1517SAl Viro 
1487319c1517SAl Viro 	if (is_file_epoll(file))
1488319c1517SAl Viro 		ep = file->private_data;
1489319c1517SAl Viro 
1490319c1517SAl Viro 	if (ep) {
1491319c1517SAl Viro 		head = &ep->refs;
1492319c1517SAl Viro 	} else if (!READ_ONCE(file->f_ep)) {
1493319c1517SAl Viro allocate:
1494319c1517SAl Viro 		to_free = kmem_cache_zalloc(ephead_cache, GFP_KERNEL);
1495319c1517SAl Viro 		if (!to_free)
1496319c1517SAl Viro 			return -ENOMEM;
1497319c1517SAl Viro 		head = &to_free->epitems;
1498319c1517SAl Viro 	}
1499319c1517SAl Viro 	spin_lock(&file->f_lock);
1500319c1517SAl Viro 	if (!file->f_ep) {
1501319c1517SAl Viro 		if (unlikely(!head)) {
1502319c1517SAl Viro 			spin_unlock(&file->f_lock);
1503319c1517SAl Viro 			goto allocate;
1504319c1517SAl Viro 		}
150561005057SChristian Brauner 		/* See eventpoll_release() for details. */
150661005057SChristian Brauner 		WRITE_ONCE(file->f_ep, head);
1507319c1517SAl Viro 		to_free = NULL;
1508319c1517SAl Viro 	}
1509319c1517SAl Viro 	hlist_add_head_rcu(&epi->fllink, file->f_ep);
1510319c1517SAl Viro 	spin_unlock(&file->f_lock);
1511319c1517SAl Viro 	free_ephead(to_free);
1512319c1517SAl Viro 	return 0;
1513319c1517SAl Viro }
1514319c1517SAl Viro 
1515c7ea7630SDavide Libenzi /*
1516c7ea7630SDavide Libenzi  * Must be called with "mtx" held.
1517c7ea7630SDavide Libenzi  */
ep_insert(struct eventpoll * ep,const struct epoll_event * event,struct file * tfile,int fd,int full_check)1518bec1a502SAl Viro static int ep_insert(struct eventpoll *ep, const struct epoll_event *event,
151967347fe4SJason Baron 		     struct file *tfile, int fd, int full_check)
15201da177e4SLinus Torvalds {
1521d85e2aa2SAl Viro 	int error, pwake = 0;
1522d85e2aa2SAl Viro 	__poll_t revents;
15231da177e4SLinus Torvalds 	struct epitem *epi;
15241da177e4SLinus Torvalds 	struct ep_pqueue epq;
152585353e91SAl Viro 	struct eventpoll *tep = NULL;
152685353e91SAl Viro 
152785353e91SAl Viro 	if (is_file_epoll(tfile))
152885353e91SAl Viro 		tep = tfile->private_data;
15291da177e4SLinus Torvalds 
153092e64178SDavidlohr Bueso 	lockdep_assert_irqs_enabled();
153192e64178SDavidlohr Bueso 
15321e1c1583SNicholas Piggin 	if (unlikely(percpu_counter_compare(&ep->user->epoll_watches,
15331e1c1583SNicholas Piggin 					    max_user_watches) >= 0))
15347ef9964eSDavide Libenzi 		return -ENOSPC;
15351e1c1583SNicholas Piggin 	percpu_counter_inc(&ep->user->epoll_watches);
15361e1c1583SNicholas Piggin 
15371e1c1583SNicholas Piggin 	if (!(epi = kmem_cache_zalloc(epi_cache, GFP_KERNEL))) {
15381e1c1583SNicholas Piggin 		percpu_counter_dec(&ep->user->epoll_watches);
15397ef9964eSDavide Libenzi 		return -ENOMEM;
15401e1c1583SNicholas Piggin 	}
15411da177e4SLinus Torvalds 
15421da177e4SLinus Torvalds 	/* Item initialization follow here ... */
15431da177e4SLinus Torvalds 	INIT_LIST_HEAD(&epi->rdllink);
15441da177e4SLinus Torvalds 	epi->ep = ep;
1545b030a4ddSPekka Enberg 	ep_set_ffd(&epi->ffd, tfile, fd);
15461da177e4SLinus Torvalds 	epi->event = *event;
1547d47de16cSDavide Libenzi 	epi->next = EP_UNACTIVE_PTR;
15481da177e4SLinus Torvalds 
154985353e91SAl Viro 	if (tep)
155085353e91SAl Viro 		mutex_lock_nested(&tep->mtx, 1);
1551f8d4f44dSAl Viro 	/* Add the current item to the list of active epoll hook for this file */
1552319c1517SAl Viro 	if (unlikely(attach_epitem(tfile, epi) < 0)) {
1553319c1517SAl Viro 		if (tep)
1554319c1517SAl Viro 			mutex_unlock(&tep->mtx);
15551e1c1583SNicholas Piggin 		kmem_cache_free(epi_cache, epi);
15561e1c1583SNicholas Piggin 		percpu_counter_dec(&ep->user->epoll_watches);
1557319c1517SAl Viro 		return -ENOMEM;
15581da177e4SLinus Torvalds 	}
15591da177e4SLinus Torvalds 
1560319c1517SAl Viro 	if (full_check && !tep)
1561319c1517SAl Viro 		list_file(tfile);
1562319c1517SAl Viro 
1563f8d4f44dSAl Viro 	/*
1564f8d4f44dSAl Viro 	 * Add the current item to the RB tree. All RB tree operations are
1565f8d4f44dSAl Viro 	 * protected by "mtx", and ep_insert() is called with "mtx" held.
1566f8d4f44dSAl Viro 	 */
1567f8d4f44dSAl Viro 	ep_rbtree_insert(ep, epi);
156885353e91SAl Viro 	if (tep)
156985353e91SAl Viro 		mutex_unlock(&tep->mtx);
1570f8d4f44dSAl Viro 
157158c9b016SPaolo Abeni 	/*
157258c9b016SPaolo Abeni 	 * ep_remove_safe() calls in the later error paths can't lead to
157358c9b016SPaolo Abeni 	 * ep_free() as the ep file itself still holds an ep reference.
157458c9b016SPaolo Abeni 	 */
157558c9b016SPaolo Abeni 	ep_get(ep);
157658c9b016SPaolo Abeni 
1577f8d4f44dSAl Viro 	/* now check if we've created too many backpaths */
1578e3e096e7SAl Viro 	if (unlikely(full_check && reverse_path_check())) {
157958c9b016SPaolo Abeni 		ep_remove_safe(ep, epi);
1580e3e096e7SAl Viro 		return -EINVAL;
1581e3e096e7SAl Viro 	}
1582f8d4f44dSAl Viro 
1583d1ec50adSAl Viro 	if (epi->event.events & EPOLLWAKEUP) {
1584d1ec50adSAl Viro 		error = ep_create_wakeup_source(epi);
1585d1ec50adSAl Viro 		if (error) {
158658c9b016SPaolo Abeni 			ep_remove_safe(ep, epi);
1587d1ec50adSAl Viro 			return error;
1588d1ec50adSAl Viro 		}
1589d1ec50adSAl Viro 	}
15901da177e4SLinus Torvalds 
15911da177e4SLinus Torvalds 	/* Initialize the poll table using the queue callback */
15921da177e4SLinus Torvalds 	epq.epi = epi;
15931da177e4SLinus Torvalds 	init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
15941da177e4SLinus Torvalds 
15951da177e4SLinus Torvalds 	/*
15961da177e4SLinus Torvalds 	 * Attach the item to the poll hooks and get current event bits.
15971da177e4SLinus Torvalds 	 * We can safely use the file* here because its usage count has
1598c7ea7630SDavide Libenzi 	 * been increased by the caller of this function. Note that after
1599c7ea7630SDavide Libenzi 	 * this operation completes, the poll callback can start hitting
1600c7ea7630SDavide Libenzi 	 * the new item.
16011da177e4SLinus Torvalds 	 */
160237b5e521SJason Baron 	revents = ep_item_poll(epi, &epq.pt, 1);
16031da177e4SLinus Torvalds 
16041da177e4SLinus Torvalds 	/*
16051da177e4SLinus Torvalds 	 * We have to check if something went wrong during the poll wait queue
16061da177e4SLinus Torvalds 	 * install process. Namely an allocation for a wait queue failed due
16071da177e4SLinus Torvalds 	 * high memory pressure.
16081da177e4SLinus Torvalds 	 */
1609e3e096e7SAl Viro 	if (unlikely(!epq.epi)) {
161058c9b016SPaolo Abeni 		ep_remove_safe(ep, epi);
1611e3e096e7SAl Viro 		return -ENOMEM;
1612e3e096e7SAl Viro 	}
16131da177e4SLinus Torvalds 
1614c7ea7630SDavide Libenzi 	/* We have to drop the new item inside our item list to keep track of it */
1615a218cc49SRoman Penyaev 	write_lock_irq(&ep->lock);
1616c7ea7630SDavide Libenzi 
1617bf3b9f63SSridhar Samudrala 	/* record NAPI ID of new item if present */
1618bf3b9f63SSridhar Samudrala 	ep_set_busy_poll_napi_id(epi);
1619bf3b9f63SSridhar Samudrala 
16201da177e4SLinus Torvalds 	/* If the file is already "ready" we drop it inside the ready list */
1621992991c0SDavidlohr Bueso 	if (revents && !ep_is_linked(epi)) {
16221da177e4SLinus Torvalds 		list_add_tail(&epi->rdllink, &ep->rdllist);
1623eea1d585SEric Wong 		ep_pm_stay_awake(epi);
16241da177e4SLinus Torvalds 
16251da177e4SLinus Torvalds 		/* Notify waiting tasks that events are available */
16261da177e4SLinus Torvalds 		if (waitqueue_active(&ep->wq))
1627a218cc49SRoman Penyaev 			wake_up(&ep->wq);
16281da177e4SLinus Torvalds 		if (waitqueue_active(&ep->poll_wait))
16291da177e4SLinus Torvalds 			pwake++;
16301da177e4SLinus Torvalds 	}
16311da177e4SLinus Torvalds 
1632a218cc49SRoman Penyaev 	write_unlock_irq(&ep->lock);
16331da177e4SLinus Torvalds 
16341da177e4SLinus Torvalds 	/* We have to call this outside the lock */
16351da177e4SLinus Torvalds 	if (pwake)
1636caf1aeafSJens Axboe 		ep_poll_safewake(ep, NULL, 0);
16371da177e4SLinus Torvalds 
16381da177e4SLinus Torvalds 	return 0;
16391da177e4SLinus Torvalds }
16401da177e4SLinus Torvalds 
16411da177e4SLinus Torvalds /*
16421da177e4SLinus Torvalds  * Modify the interest event mask by dropping an event if the new mask
1643c7ea7630SDavide Libenzi  * has a match in the current file status. Must be called with "mtx" held.
16441da177e4SLinus Torvalds  */
ep_modify(struct eventpoll * ep,struct epitem * epi,const struct epoll_event * event)1645bec1a502SAl Viro static int ep_modify(struct eventpoll *ep, struct epitem *epi,
1646bec1a502SAl Viro 		     const struct epoll_event *event)
16471da177e4SLinus Torvalds {
16481da177e4SLinus Torvalds 	int pwake = 0;
1649626cf236SHans Verkuil 	poll_table pt;
1650626cf236SHans Verkuil 
165192e64178SDavidlohr Bueso 	lockdep_assert_irqs_enabled();
165292e64178SDavidlohr Bueso 
1653626cf236SHans Verkuil 	init_poll_funcptr(&pt, NULL);
16541da177e4SLinus Torvalds 
16551da177e4SLinus Torvalds 	/*
1656e057e15fSTony Battersby 	 * Set the new event interest mask before calling f_op->poll();
1657e057e15fSTony Battersby 	 * otherwise we might miss an event that happens between the
1658e057e15fSTony Battersby 	 * f_op->poll() call and the new event set registering.
16591da177e4SLinus Torvalds 	 */
1660128dd175SEric Wong 	epi->event.events = event->events; /* need barrier below */
1661e057e15fSTony Battersby 	epi->event.data = event->data; /* protected by mtx */
16624d7e30d9SArve Hjønnevåg 	if (epi->event.events & EPOLLWAKEUP) {
1663eea1d585SEric Wong 		if (!ep_has_wakeup_source(epi))
16644d7e30d9SArve Hjønnevåg 			ep_create_wakeup_source(epi);
1665eea1d585SEric Wong 	} else if (ep_has_wakeup_source(epi)) {
16664d7e30d9SArve Hjønnevåg 		ep_destroy_wakeup_source(epi);
16674d7e30d9SArve Hjønnevåg 	}
16681da177e4SLinus Torvalds 
16691da177e4SLinus Torvalds 	/*
1670128dd175SEric Wong 	 * The following barrier has two effects:
1671128dd175SEric Wong 	 *
1672128dd175SEric Wong 	 * 1) Flush epi changes above to other CPUs.  This ensures
1673128dd175SEric Wong 	 *    we do not miss events from ep_poll_callback if an
1674128dd175SEric Wong 	 *    event occurs immediately after we call f_op->poll().
1675a218cc49SRoman Penyaev 	 *    We need this because we did not take ep->lock while
1676128dd175SEric Wong 	 *    changing epi above (but ep_poll_callback does take
1677a218cc49SRoman Penyaev 	 *    ep->lock).
1678128dd175SEric Wong 	 *
1679128dd175SEric Wong 	 * 2) We also need to ensure we do not miss _past_ events
1680128dd175SEric Wong 	 *    when calling f_op->poll().  This barrier also
1681128dd175SEric Wong 	 *    pairs with the barrier in wq_has_sleeper (see
1682128dd175SEric Wong 	 *    comments for wq_has_sleeper).
1683128dd175SEric Wong 	 *
1684128dd175SEric Wong 	 * This barrier will now guarantee ep_poll_callback or f_op->poll
1685128dd175SEric Wong 	 * (or both) will notice the readiness of an item.
1686128dd175SEric Wong 	 */
1687128dd175SEric Wong 	smp_mb();
1688128dd175SEric Wong 
1689128dd175SEric Wong 	/*
16901da177e4SLinus Torvalds 	 * Get current event bits. We can safely use the file* here because
16911da177e4SLinus Torvalds 	 * its usage count has been increased by the caller of this function.
16921da177e4SLinus Torvalds 	 * If the item is "hot" and it is not registered inside the ready
169367647d0fSDavide Libenzi 	 * list, push it inside.
16941da177e4SLinus Torvalds 	 */
169569112736SAl Viro 	if (ep_item_poll(epi, &pt, 1)) {
1696a218cc49SRoman Penyaev 		write_lock_irq(&ep->lock);
1697992991c0SDavidlohr Bueso 		if (!ep_is_linked(epi)) {
16981da177e4SLinus Torvalds 			list_add_tail(&epi->rdllink, &ep->rdllist);
1699eea1d585SEric Wong 			ep_pm_stay_awake(epi);
17001da177e4SLinus Torvalds 
17011da177e4SLinus Torvalds 			/* Notify waiting tasks that events are available */
17021da177e4SLinus Torvalds 			if (waitqueue_active(&ep->wq))
1703a218cc49SRoman Penyaev 				wake_up(&ep->wq);
17041da177e4SLinus Torvalds 			if (waitqueue_active(&ep->poll_wait))
17051da177e4SLinus Torvalds 				pwake++;
17061da177e4SLinus Torvalds 		}
1707a218cc49SRoman Penyaev 		write_unlock_irq(&ep->lock);
17081da177e4SLinus Torvalds 	}
17091da177e4SLinus Torvalds 
17101da177e4SLinus Torvalds 	/* We have to call this outside the lock */
17111da177e4SLinus Torvalds 	if (pwake)
1712caf1aeafSJens Axboe 		ep_poll_safewake(ep, NULL, 0);
17131da177e4SLinus Torvalds 
17141da177e4SLinus Torvalds 	return 0;
17151da177e4SLinus Torvalds }
17161da177e4SLinus Torvalds 
ep_send_events(struct eventpoll * ep,struct epoll_event __user * events,int maxevents)1717ff07952aSAl Viro static int ep_send_events(struct eventpoll *ep,
1718ff07952aSAl Viro 			  struct epoll_event __user *events, int maxevents)
17195071f97eSDavide Libenzi {
17204e0982a0SDavidlohr Bueso 	struct epitem *epi, *tmp;
1721ff07952aSAl Viro 	LIST_HEAD(txlist);
1722626cf236SHans Verkuil 	poll_table pt;
1723ff07952aSAl Viro 	int res = 0;
1724626cf236SHans Verkuil 
1725cccd29bfSSoheil Hassas Yeganeh 	/*
1726cccd29bfSSoheil Hassas Yeganeh 	 * Always short-circuit for fatal signals to allow threads to make a
1727cccd29bfSSoheil Hassas Yeganeh 	 * timely exit without the chance of finding more events available and
1728cccd29bfSSoheil Hassas Yeganeh 	 * fetching repeatedly.
1729cccd29bfSSoheil Hassas Yeganeh 	 */
1730cccd29bfSSoheil Hassas Yeganeh 	if (fatal_signal_pending(current))
1731cccd29bfSSoheil Hassas Yeganeh 		return -EINTR;
1732cccd29bfSSoheil Hassas Yeganeh 
1733626cf236SHans Verkuil 	init_poll_funcptr(&pt, NULL);
1734ff07952aSAl Viro 
173557804b1cSAl Viro 	mutex_lock(&ep->mtx);
173657804b1cSAl Viro 	ep_start_scan(ep, &txlist);
17375071f97eSDavide Libenzi 
17385071f97eSDavide Libenzi 	/*
17395071f97eSDavide Libenzi 	 * We can loop without lock because we are passed a task private list.
174057804b1cSAl Viro 	 * Items cannot vanish during the loop we are holding ep->mtx.
17415071f97eSDavide Libenzi 	 */
1742ff07952aSAl Viro 	list_for_each_entry_safe(epi, tmp, &txlist, rdllink) {
1743ff07952aSAl Viro 		struct wakeup_source *ws;
1744ff07952aSAl Viro 		__poll_t revents;
174521877e1aSDavidlohr Bueso 
1746ff07952aSAl Viro 		if (res >= maxevents)
17474e0982a0SDavidlohr Bueso 			break;
17485071f97eSDavide Libenzi 
17494d7e30d9SArve Hjønnevåg 		/*
17504d7e30d9SArve Hjønnevåg 		 * Activate ep->ws before deactivating epi->ws to prevent
17514d7e30d9SArve Hjønnevåg 		 * triggering auto-suspend here (in case we reactive epi->ws
17524d7e30d9SArve Hjønnevåg 		 * below).
17534d7e30d9SArve Hjønnevåg 		 *
17544d7e30d9SArve Hjønnevåg 		 * This could be rearranged to delay the deactivation of epi->ws
17554d7e30d9SArve Hjønnevåg 		 * instead, but then epi->ws would temporarily be out of sync
17564d7e30d9SArve Hjønnevåg 		 * with ep_is_linked().
17574d7e30d9SArve Hjønnevåg 		 */
1758eea1d585SEric Wong 		ws = ep_wakeup_source(epi);
1759eea1d585SEric Wong 		if (ws) {
1760eea1d585SEric Wong 			if (ws->active)
17614d7e30d9SArve Hjønnevåg 				__pm_stay_awake(ep->ws);
1762eea1d585SEric Wong 			__pm_relax(ws);
1763eea1d585SEric Wong 		}
1764eea1d585SEric Wong 
17655071f97eSDavide Libenzi 		list_del_init(&epi->rdllink);
17665071f97eSDavide Libenzi 
17675071f97eSDavide Libenzi 		/*
17685071f97eSDavide Libenzi 		 * If the event mask intersect the caller-requested one,
176957804b1cSAl Viro 		 * deliver the event to userspace. Again, we are holding ep->mtx,
177057804b1cSAl Viro 		 * so no operations coming from userspace can change the item.
17715071f97eSDavide Libenzi 		 */
17724e0982a0SDavidlohr Bueso 		revents = ep_item_poll(epi, &pt, 1);
17734e0982a0SDavidlohr Bueso 		if (!revents)
17744e0982a0SDavidlohr Bueso 			continue;
17754e0982a0SDavidlohr Bueso 
1776249dbe74SArnd Bergmann 		events = epoll_put_uevent(revents, epi->event.data, events);
1777249dbe74SArnd Bergmann 		if (!events) {
1778ff07952aSAl Viro 			list_add(&epi->rdllink, &txlist);
1779eea1d585SEric Wong 			ep_pm_stay_awake(epi);
1780ff07952aSAl Viro 			if (!res)
1781ff07952aSAl Viro 				res = -EFAULT;
1782ff07952aSAl Viro 			break;
1783d0305882STony Battersby 		}
1784ff07952aSAl Viro 		res++;
17855071f97eSDavide Libenzi 		if (epi->event.events & EPOLLONESHOT)
17865071f97eSDavide Libenzi 			epi->event.events &= EP_PRIVATE_BITS;
1787296e236eSDavide Libenzi 		else if (!(epi->event.events & EPOLLET)) {
17885071f97eSDavide Libenzi 			/*
1789296e236eSDavide Libenzi 			 * If this file has been added with Level
1790296e236eSDavide Libenzi 			 * Trigger mode, we need to insert back inside
1791296e236eSDavide Libenzi 			 * the ready list, so that the next call to
1792296e236eSDavide Libenzi 			 * epoll_wait() will check again the events
1793296e236eSDavide Libenzi 			 * availability. At this point, no one can insert
1794296e236eSDavide Libenzi 			 * into ep->rdllist besides us. The epoll_ctl()
1795296e236eSDavide Libenzi 			 * callers are locked out by
1796296e236eSDavide Libenzi 			 * ep_scan_ready_list() holding "mtx" and the
1797296e236eSDavide Libenzi 			 * poll callback will queue them in ep->ovflist.
17985071f97eSDavide Libenzi 			 */
17995071f97eSDavide Libenzi 			list_add_tail(&epi->rdllink, &ep->rdllist);
1800eea1d585SEric Wong 			ep_pm_stay_awake(epi);
18015071f97eSDavide Libenzi 		}
18025071f97eSDavide Libenzi 	}
180357804b1cSAl Viro 	ep_done_scan(ep, &txlist);
180457804b1cSAl Viro 	mutex_unlock(&ep->mtx);
18055071f97eSDavide Libenzi 
1806ff07952aSAl Viro 	return res;
18071da177e4SLinus Torvalds }
18081da177e4SLinus Torvalds 
ep_timeout_to_timespec(struct timespec64 * to,long ms)18097cdf7c20SWillem de Bruijn static struct timespec64 *ep_timeout_to_timespec(struct timespec64 *to, long ms)
18100781b909SEric Dumazet {
18117cdf7c20SWillem de Bruijn 	struct timespec64 now;
18127cdf7c20SWillem de Bruijn 
18137cdf7c20SWillem de Bruijn 	if (ms < 0)
18147cdf7c20SWillem de Bruijn 		return NULL;
18157cdf7c20SWillem de Bruijn 
18167cdf7c20SWillem de Bruijn 	if (!ms) {
18177cdf7c20SWillem de Bruijn 		to->tv_sec = 0;
18187cdf7c20SWillem de Bruijn 		to->tv_nsec = 0;
18197cdf7c20SWillem de Bruijn 		return to;
18207cdf7c20SWillem de Bruijn 	}
18217cdf7c20SWillem de Bruijn 
18227cdf7c20SWillem de Bruijn 	to->tv_sec = ms / MSEC_PER_SEC;
18237cdf7c20SWillem de Bruijn 	to->tv_nsec = NSEC_PER_MSEC * (ms % MSEC_PER_SEC);
18240781b909SEric Dumazet 
1825766b9f92SDeepa Dinamani 	ktime_get_ts64(&now);
18267cdf7c20SWillem de Bruijn 	*to = timespec64_add_safe(now, *to);
18277cdf7c20SWillem de Bruijn 	return to;
18280781b909SEric Dumazet }
18290781b909SEric Dumazet 
1830a16ceb13SBenjamin Segall /*
1831a16ceb13SBenjamin Segall  * autoremove_wake_function, but remove even on failure to wake up, because we
1832a16ceb13SBenjamin Segall  * know that default_wake_function/ttwu will only fail if the thread is already
1833a16ceb13SBenjamin Segall  * woken, and in that case the ep_poll loop will remove the entry anyways, not
1834a16ceb13SBenjamin Segall  * try to reuse it.
1835a16ceb13SBenjamin Segall  */
ep_autoremove_wake_function(struct wait_queue_entry * wq_entry,unsigned int mode,int sync,void * key)1836a16ceb13SBenjamin Segall static int ep_autoremove_wake_function(struct wait_queue_entry *wq_entry,
1837a16ceb13SBenjamin Segall 				       unsigned int mode, int sync, void *key)
1838a16ceb13SBenjamin Segall {
1839a16ceb13SBenjamin Segall 	int ret = default_wake_function(wq_entry, mode, sync, key);
1840a16ceb13SBenjamin Segall 
18412192bba0SBenjamin Segall 	/*
18422192bba0SBenjamin Segall 	 * Pairs with list_empty_careful in ep_poll, and ensures future loop
18432192bba0SBenjamin Segall 	 * iterations see the cause of this wakeup.
18442192bba0SBenjamin Segall 	 */
18452192bba0SBenjamin Segall 	list_del_init_careful(&wq_entry->entry);
1846a16ceb13SBenjamin Segall 	return ret;
1847a16ceb13SBenjamin Segall }
1848a16ceb13SBenjamin Segall 
1849f4d93ad7SShawn Bohrer /**
1850a6c67feeSRandy Dunlap  * ep_poll - Retrieves ready events, and delivers them to the caller-supplied
1851f4d93ad7SShawn Bohrer  *           event buffer.
1852f4d93ad7SShawn Bohrer  *
1853f4d93ad7SShawn Bohrer  * @ep: Pointer to the eventpoll context.
1854f4d93ad7SShawn Bohrer  * @events: Pointer to the userspace buffer where the ready events should be
1855f4d93ad7SShawn Bohrer  *          stored.
1856f4d93ad7SShawn Bohrer  * @maxevents: Size (in terms of number of events) of the caller event buffer.
1857f4d93ad7SShawn Bohrer  * @timeout: Maximum timeout for the ready events fetch operation, in
18587cdf7c20SWillem de Bruijn  *           timespec. If the timeout is zero, the function will not block,
18597cdf7c20SWillem de Bruijn  *           while if the @timeout ptr is NULL, the function will block
1860f4d93ad7SShawn Bohrer  *           until at least one event has been retrieved (or an error
1861f4d93ad7SShawn Bohrer  *           occurred).
1862f4d93ad7SShawn Bohrer  *
1863a6c67feeSRandy Dunlap  * Return: the number of ready events which have been fetched, or an
1864f4d93ad7SShawn Bohrer  *          error code, in case of error.
1865f4d93ad7SShawn Bohrer  */
ep_poll(struct eventpoll * ep,struct epoll_event __user * events,int maxevents,struct timespec64 * timeout)18661da177e4SLinus Torvalds static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
18677cdf7c20SWillem de Bruijn 		   int maxevents, struct timespec64 *timeout)
18681da177e4SLinus Torvalds {
1869e59d3c64SSoheil Hassas Yeganeh 	int res, eavail, timed_out = 0;
1870da8b44d5SJohn Stultz 	u64 slack = 0;
1871ac6424b9SIngo Molnar 	wait_queue_entry_t wait;
187295aac7b1SShawn Bohrer 	ktime_t expires, *to = NULL;
18731da177e4SLinus Torvalds 
1874679abf38SDavidlohr Bueso 	lockdep_assert_irqs_enabled();
1875679abf38SDavidlohr Bueso 
18767cdf7c20SWillem de Bruijn 	if (timeout && (timeout->tv_sec | timeout->tv_nsec)) {
18777cdf7c20SWillem de Bruijn 		slack = select_estimate_accuracy(timeout);
187895aac7b1SShawn Bohrer 		to = &expires;
18797cdf7c20SWillem de Bruijn 		*to = timespec64_to_ktime(*timeout);
18807cdf7c20SWillem de Bruijn 	} else if (timeout) {
1881f4d93ad7SShawn Bohrer 		/*
1882f4d93ad7SShawn Bohrer 		 * Avoid the unnecessary trip to the wait queue loop, if the
1883e59d3c64SSoheil Hassas Yeganeh 		 * caller specified a non blocking operation.
1884f4d93ad7SShawn Bohrer 		 */
188595aac7b1SShawn Bohrer 		timed_out = 1;
188695aac7b1SShawn Bohrer 	}
18871da177e4SLinus Torvalds 
1888e59d3c64SSoheil Hassas Yeganeh 	/*
1889e59d3c64SSoheil Hassas Yeganeh 	 * This call is racy: We may or may not see events that are being added
1890a6c67feeSRandy Dunlap 	 * to the ready list under the lock (e.g., in IRQ callbacks). For cases
1891e59d3c64SSoheil Hassas Yeganeh 	 * with a non-zero timeout, this thread will check the ready list under
1892a6c67feeSRandy Dunlap 	 * lock and will add to the wait queue.  For cases with a zero
1893e59d3c64SSoheil Hassas Yeganeh 	 * timeout, the user by definition should not care and will have to
1894e59d3c64SSoheil Hassas Yeganeh 	 * recheck again.
1895e59d3c64SSoheil Hassas Yeganeh 	 */
1896e59d3c64SSoheil Hassas Yeganeh 	eavail = ep_events_available(ep);
1897e59d3c64SSoheil Hassas Yeganeh 
189800b27634SSoheil Hassas Yeganeh 	while (1) {
189900b27634SSoheil Hassas Yeganeh 		if (eavail) {
190000b27634SSoheil Hassas Yeganeh 			/*
190100b27634SSoheil Hassas Yeganeh 			 * Try to transfer events to user space. In case we get
190200b27634SSoheil Hassas Yeganeh 			 * 0 events and there's still timeout left over, we go
190300b27634SSoheil Hassas Yeganeh 			 * trying again in search of more luck.
190400b27634SSoheil Hassas Yeganeh 			 */
190500b27634SSoheil Hassas Yeganeh 			res = ep_send_events(ep, events, maxevents);
190600b27634SSoheil Hassas Yeganeh 			if (res)
190700b27634SSoheil Hassas Yeganeh 				return res;
190800b27634SSoheil Hassas Yeganeh 		}
19091493c47fSSoheil Hassas Yeganeh 
191000b27634SSoheil Hassas Yeganeh 		if (timed_out)
191100b27634SSoheil Hassas Yeganeh 			return 0;
191200b27634SSoheil Hassas Yeganeh 
191300b27634SSoheil Hassas Yeganeh 		eavail = ep_busy_loop(ep, timed_out);
191400b27634SSoheil Hassas Yeganeh 		if (eavail)
191500b27634SSoheil Hassas Yeganeh 			continue;
19161da177e4SLinus Torvalds 
19172efdaf76SSoheil Hassas Yeganeh 		if (signal_pending(current))
19182efdaf76SSoheil Hassas Yeganeh 			return -EINTR;
19192efdaf76SSoheil Hassas Yeganeh 
1920bf3b9f63SSridhar Samudrala 		/*
1921412895f0SRoman Penyaev 		 * Internally init_wait() uses autoremove_wake_function(),
1922412895f0SRoman Penyaev 		 * thus wait entry is removed from the wait queue on each
1923412895f0SRoman Penyaev 		 * wakeup. Why it is important? In case of several waiters
1924412895f0SRoman Penyaev 		 * each new wakeup will hit the next waiter, giving it the
1925412895f0SRoman Penyaev 		 * chance to harvest new event. Otherwise wakeup can be
1926412895f0SRoman Penyaev 		 * lost. This is also good performance-wise, because on
1927412895f0SRoman Penyaev 		 * normal wakeup path no need to call __remove_wait_queue()
1928412895f0SRoman Penyaev 		 * explicitly, thus ep->lock is not taken, which halts the
1929412895f0SRoman Penyaev 		 * event delivery.
1930a16ceb13SBenjamin Segall 		 *
1931a16ceb13SBenjamin Segall 		 * In fact, we now use an even more aggressive function that
1932a16ceb13SBenjamin Segall 		 * unconditionally removes, because we don't reuse the wait
1933a16ceb13SBenjamin Segall 		 * entry between loop iterations. This lets us also avoid the
1934a16ceb13SBenjamin Segall 		 * performance issue if a process is killed, causing all of its
1935a16ceb13SBenjamin Segall 		 * threads to wake up without being removed normally.
19361da177e4SLinus Torvalds 		 */
1937412895f0SRoman Penyaev 		init_wait(&wait);
1938a16ceb13SBenjamin Segall 		wait.func = ep_autoremove_wake_function;
193965759097SRoman Penyaev 
19401b53734bSRoman Penyaev 		write_lock_irq(&ep->lock);
194165759097SRoman Penyaev 		/*
194265759097SRoman Penyaev 		 * Barrierless variant, waitqueue_active() is called under
194365759097SRoman Penyaev 		 * the same lock on wakeup ep_poll_callback() side, so it
194465759097SRoman Penyaev 		 * is safe to avoid an explicit barrier.
194565759097SRoman Penyaev 		 */
194665759097SRoman Penyaev 		__set_current_state(TASK_INTERRUPTIBLE);
194765759097SRoman Penyaev 
194865759097SRoman Penyaev 		/*
194965759097SRoman Penyaev 		 * Do the final check under the lock. ep_scan_ready_list()
195065759097SRoman Penyaev 		 * plays with two lists (->rdllist and ->ovflist) and there
195165759097SRoman Penyaev 		 * is always a race when both lists are empty for short
195265759097SRoman Penyaev 		 * period of time although events are pending, so lock is
195365759097SRoman Penyaev 		 * important.
195465759097SRoman Penyaev 		 */
195565759097SRoman Penyaev 		eavail = ep_events_available(ep);
19562efdaf76SSoheil Hassas Yeganeh 		if (!eavail)
1957a93d2f17SChangli Gao 			__add_wait_queue_exclusive(&ep->wq, &wait);
19582efdaf76SSoheil Hassas Yeganeh 
19591b53734bSRoman Penyaev 		write_unlock_irq(&ep->lock);
19601da177e4SLinus Torvalds 
19612efdaf76SSoheil Hassas Yeganeh 		if (!eavail)
1962289caf5dSSoheil Hassas Yeganeh 			timed_out = !schedule_hrtimeout_range(to, slack,
1963289caf5dSSoheil Hassas Yeganeh 							      HRTIMER_MODE_ABS);
1964e411596dSSoheil Hassas Yeganeh 		__set_current_state(TASK_RUNNING);
19651da177e4SLinus Torvalds 
1966289caf5dSSoheil Hassas Yeganeh 		/*
1967289caf5dSSoheil Hassas Yeganeh 		 * We were woken up, thus go and try to harvest some events.
1968289caf5dSSoheil Hassas Yeganeh 		 * If timed out and still on the wait queue, recheck eavail
1969289caf5dSSoheil Hassas Yeganeh 		 * carefully under lock, below.
1970289caf5dSSoheil Hassas Yeganeh 		 */
1971412895f0SRoman Penyaev 		eavail = 1;
19721da177e4SLinus Torvalds 
1973412895f0SRoman Penyaev 		if (!list_empty_careful(&wait.entry)) {
1974412895f0SRoman Penyaev 			write_lock_irq(&ep->lock);
1975289caf5dSSoheil Hassas Yeganeh 			/*
1976e8c85328SSoheil Hassas Yeganeh 			 * If the thread timed out and is not on the wait queue,
1977e8c85328SSoheil Hassas Yeganeh 			 * it means that the thread was woken up after its
1978e8c85328SSoheil Hassas Yeganeh 			 * timeout expired before it could reacquire the lock.
1979e8c85328SSoheil Hassas Yeganeh 			 * Thus, when wait.entry is empty, it needs to harvest
1980e8c85328SSoheil Hassas Yeganeh 			 * events.
1981289caf5dSSoheil Hassas Yeganeh 			 */
1982289caf5dSSoheil Hassas Yeganeh 			if (timed_out)
1983289caf5dSSoheil Hassas Yeganeh 				eavail = list_empty(&wait.entry);
1984412895f0SRoman Penyaev 			__remove_wait_queue(&ep->wq, &wait);
1985412895f0SRoman Penyaev 			write_unlock_irq(&ep->lock);
1986412895f0SRoman Penyaev 		}
198700b27634SSoheil Hassas Yeganeh 	}
19881da177e4SLinus Torvalds }
19891da177e4SLinus Torvalds 
199022bacca4SDavide Libenzi /**
1991773318edSAl Viro  * ep_loop_check_proc - verify that adding an epoll file inside another
1992a6c67feeSRandy Dunlap  *                      epoll structure does not violate the constraints, in
199322bacca4SDavide Libenzi  *                      terms of closed loops, or too deep chains (which can
199422bacca4SDavide Libenzi  *                      result in excessive stack usage).
199522bacca4SDavide Libenzi  *
1996a6c67feeSRandy Dunlap  * @ep: the &struct eventpoll to be currently checked.
1997bde03c4cSAl Viro  * @depth: Current depth of the path being checked.
199822bacca4SDavide Libenzi  *
1999a6c67feeSRandy Dunlap  * Return: %zero if adding the epoll @file inside current epoll
2000a6c67feeSRandy Dunlap  *          structure @ep does not violate the constraints, or %-1 otherwise.
200122bacca4SDavide Libenzi  */
ep_loop_check_proc(struct eventpoll * ep,int depth)2002bde03c4cSAl Viro static int ep_loop_check_proc(struct eventpoll *ep, int depth)
200322bacca4SDavide Libenzi {
200422bacca4SDavide Libenzi 	int error = 0;
200522bacca4SDavide Libenzi 	struct rb_node *rbp;
200622bacca4SDavide Libenzi 	struct epitem *epi;
200722bacca4SDavide Libenzi 
2008773318edSAl Viro 	mutex_lock_nested(&ep->mtx, depth + 1);
200918306c40SAl Viro 	ep->gen = loop_check_gen;
2010b2ac2ea6SDavidlohr Bueso 	for (rbp = rb_first_cached(&ep->rbr); rbp; rbp = rb_next(rbp)) {
201122bacca4SDavide Libenzi 		epi = rb_entry(rbp, struct epitem, rbn);
201222bacca4SDavide Libenzi 		if (unlikely(is_file_epoll(epi->ffd.file))) {
2013bde03c4cSAl Viro 			struct eventpoll *ep_tovisit;
201428d82dc1SJason Baron 			ep_tovisit = epi->ffd.file->private_data;
201518306c40SAl Viro 			if (ep_tovisit->gen == loop_check_gen)
201628d82dc1SJason Baron 				continue;
2017bde03c4cSAl Viro 			if (ep_tovisit == inserting_into || depth > EP_MAX_NESTS)
201856c428caSAl Viro 				error = -1;
2019bde03c4cSAl Viro 			else
2020bde03c4cSAl Viro 				error = ep_loop_check_proc(ep_tovisit, depth + 1);
202122bacca4SDavide Libenzi 			if (error != 0)
202222bacca4SDavide Libenzi 				break;
202328d82dc1SJason Baron 		} else {
202428d82dc1SJason Baron 			/*
202528d82dc1SJason Baron 			 * If we've reached a file that is not associated with
202628d82dc1SJason Baron 			 * an ep, then we need to check if the newly added
202728d82dc1SJason Baron 			 * links are going to add too many wakeup paths. We do
202828d82dc1SJason Baron 			 * this by adding it to the tfile_check_list, if it's
202928d82dc1SJason Baron 			 * not already there, and calling reverse_path_check()
203028d82dc1SJason Baron 			 * during ep_insert().
203128d82dc1SJason Baron 			 */
2032319c1517SAl Viro 			list_file(epi->ffd.file);
203322bacca4SDavide Libenzi 		}
2034a9ed4a65SMarc Zyngier 	}
203522bacca4SDavide Libenzi 	mutex_unlock(&ep->mtx);
203622bacca4SDavide Libenzi 
203722bacca4SDavide Libenzi 	return error;
203822bacca4SDavide Libenzi }
203922bacca4SDavide Libenzi 
204022bacca4SDavide Libenzi /**
2041bde03c4cSAl Viro  * ep_loop_check - Performs a check to verify that adding an epoll file (@to)
2042a6c67feeSRandy Dunlap  *                 into another epoll file (represented by @ep) does not create
204322bacca4SDavide Libenzi  *                 closed loops or too deep chains.
204422bacca4SDavide Libenzi  *
2045a6c67feeSRandy Dunlap  * @ep: Pointer to the epoll we are inserting into.
2046bde03c4cSAl Viro  * @to: Pointer to the epoll to be inserted.
204722bacca4SDavide Libenzi  *
2048a6c67feeSRandy Dunlap  * Return: %zero if adding the epoll @to inside the epoll @from
2049a6c67feeSRandy Dunlap  * does not violate the constraints, or %-1 otherwise.
205022bacca4SDavide Libenzi  */
ep_loop_check(struct eventpoll * ep,struct eventpoll * to)2051bde03c4cSAl Viro static int ep_loop_check(struct eventpoll *ep, struct eventpoll *to)
205222bacca4SDavide Libenzi {
20536a3890c4SAl Viro 	inserting_into = ep;
2054bde03c4cSAl Viro 	return ep_loop_check_proc(to, 0);
205528d82dc1SJason Baron }
205628d82dc1SJason Baron 
clear_tfile_check_list(void)205728d82dc1SJason Baron static void clear_tfile_check_list(void)
205828d82dc1SJason Baron {
2059319c1517SAl Viro 	rcu_read_lock();
2060319c1517SAl Viro 	while (tfile_check_list != EP_UNACTIVE_PTR) {
2061319c1517SAl Viro 		struct epitems_head *head = tfile_check_list;
2062319c1517SAl Viro 		tfile_check_list = head->next;
2063319c1517SAl Viro 		unlist_file(head);
206428d82dc1SJason Baron 	}
2065319c1517SAl Viro 	rcu_read_unlock();
206622bacca4SDavide Libenzi }
206722bacca4SDavide Libenzi 
20687699acd1SDavide Libenzi /*
2069523723bbSAndrew Morton  * Open an eventpoll file descriptor.
20707699acd1SDavide Libenzi  */
do_epoll_create(int flags)2071791eb22eSDominik Brodowski static int do_epoll_create(int flags)
20727699acd1SDavide Libenzi {
207328d82dc1SJason Baron 	int error, fd;
2074bb57c3edSDavide Libenzi 	struct eventpoll *ep = NULL;
207528d82dc1SJason Baron 	struct file *file;
20767699acd1SDavide Libenzi 
2077e38b36f3SUlrich Drepper 	/* Check the EPOLL_* constant for consistency.  */
2078e38b36f3SUlrich Drepper 	BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC);
2079e38b36f3SUlrich Drepper 
2080296e236eSDavide Libenzi 	if (flags & ~EPOLL_CLOEXEC)
2081296e236eSDavide Libenzi 		return -EINVAL;
20827699acd1SDavide Libenzi 	/*
20839fe5ad9cSUlrich Drepper 	 * Create the internal data structure ("struct eventpoll").
20847699acd1SDavide Libenzi 	 */
20859fe5ad9cSUlrich Drepper 	error = ep_alloc(&ep);
2086bb57c3edSDavide Libenzi 	if (error < 0)
2087bb57c3edSDavide Libenzi 		return error;
20887699acd1SDavide Libenzi 	/*
20897699acd1SDavide Libenzi 	 * Creates all the items needed to setup an eventpoll file. That is,
20902030a42cSAl Viro 	 * a file structure and a free file descriptor.
20917699acd1SDavide Libenzi 	 */
209228d82dc1SJason Baron 	fd = get_unused_fd_flags(O_RDWR | (flags & O_CLOEXEC));
209328d82dc1SJason Baron 	if (fd < 0) {
209428d82dc1SJason Baron 		error = fd;
209528d82dc1SJason Baron 		goto out_free_ep;
209628d82dc1SJason Baron 	}
209728d82dc1SJason Baron 	file = anon_inode_getfile("[eventpoll]", &eventpoll_fops, ep,
2098628ff7c1SRoland Dreier 				 O_RDWR | (flags & O_CLOEXEC));
209928d82dc1SJason Baron 	if (IS_ERR(file)) {
210028d82dc1SJason Baron 		error = PTR_ERR(file);
210128d82dc1SJason Baron 		goto out_free_fd;
210228d82dc1SJason Baron 	}
210328d82dc1SJason Baron 	ep->file = file;
210498022748SAl Viro 	fd_install(fd, file);
210528d82dc1SJason Baron 	return fd;
21067699acd1SDavide Libenzi 
210728d82dc1SJason Baron out_free_fd:
210828d82dc1SJason Baron 	put_unused_fd(fd);
210928d82dc1SJason Baron out_free_ep:
211058c9b016SPaolo Abeni 	ep_clear_and_put(ep);
2111bb57c3edSDavide Libenzi 	return error;
21127699acd1SDavide Libenzi }
21137699acd1SDavide Libenzi 
SYSCALL_DEFINE1(epoll_create1,int,flags)2114791eb22eSDominik Brodowski SYSCALL_DEFINE1(epoll_create1, int, flags)
2115791eb22eSDominik Brodowski {
2116791eb22eSDominik Brodowski 	return do_epoll_create(flags);
2117791eb22eSDominik Brodowski }
2118791eb22eSDominik Brodowski 
SYSCALL_DEFINE1(epoll_create,int,size)21195a8a82b1SHeiko Carstens SYSCALL_DEFINE1(epoll_create, int, size)
2120a0998b50SUlrich Drepper {
2121bfe3891aSDavide Libenzi 	if (size <= 0)
21229fe5ad9cSUlrich Drepper 		return -EINVAL;
21239fe5ad9cSUlrich Drepper 
2124791eb22eSDominik Brodowski 	return do_epoll_create(0);
2125a0998b50SUlrich Drepper }
2126a0998b50SUlrich Drepper 
2127063f3ed9SPalmer Dabbelt #ifdef CONFIG_PM_SLEEP
ep_take_care_of_epollwakeup(struct epoll_event * epev)2128063f3ed9SPalmer Dabbelt static inline void ep_take_care_of_epollwakeup(struct epoll_event *epev)
2129063f3ed9SPalmer Dabbelt {
2130063f3ed9SPalmer Dabbelt 	if ((epev->events & EPOLLWAKEUP) && !capable(CAP_BLOCK_SUSPEND))
2131063f3ed9SPalmer Dabbelt 		epev->events &= ~EPOLLWAKEUP;
2132063f3ed9SPalmer Dabbelt }
2133063f3ed9SPalmer Dabbelt #else
ep_take_care_of_epollwakeup(struct epoll_event * epev)2134063f3ed9SPalmer Dabbelt static inline void ep_take_care_of_epollwakeup(struct epoll_event *epev)
2135063f3ed9SPalmer Dabbelt {
2136063f3ed9SPalmer Dabbelt 	epev->events &= ~EPOLLWAKEUP;
2137063f3ed9SPalmer Dabbelt }
2138063f3ed9SPalmer Dabbelt #endif
2139063f3ed9SPalmer Dabbelt 
epoll_mutex_lock(struct mutex * mutex,int depth,bool nonblock)214039220e8dSJens Axboe static inline int epoll_mutex_lock(struct mutex *mutex, int depth,
214139220e8dSJens Axboe 				   bool nonblock)
214239220e8dSJens Axboe {
214339220e8dSJens Axboe 	if (!nonblock) {
214439220e8dSJens Axboe 		mutex_lock_nested(mutex, depth);
214539220e8dSJens Axboe 		return 0;
214639220e8dSJens Axboe 	}
214739220e8dSJens Axboe 	if (mutex_trylock(mutex))
214839220e8dSJens Axboe 		return 0;
214939220e8dSJens Axboe 	return -EAGAIN;
215039220e8dSJens Axboe }
215139220e8dSJens Axboe 
do_epoll_ctl(int epfd,int op,int fd,struct epoll_event * epds,bool nonblock)215239220e8dSJens Axboe int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds,
215339220e8dSJens Axboe 		 bool nonblock)
21547699acd1SDavide Libenzi {
21557699acd1SDavide Libenzi 	int error;
215667347fe4SJason Baron 	int full_check = 0;
21577e3fb584SAl Viro 	struct fd f, tf;
21587699acd1SDavide Libenzi 	struct eventpoll *ep;
21597699acd1SDavide Libenzi 	struct epitem *epi;
216067347fe4SJason Baron 	struct eventpoll *tep = NULL;
21617699acd1SDavide Libenzi 
21627699acd1SDavide Libenzi 	error = -EBADF;
21637e3fb584SAl Viro 	f = fdget(epfd);
21647e3fb584SAl Viro 	if (!f.file)
21657699acd1SDavide Libenzi 		goto error_return;
21667699acd1SDavide Libenzi 
21677699acd1SDavide Libenzi 	/* Get the "struct file *" for the target file */
21687e3fb584SAl Viro 	tf = fdget(fd);
21697e3fb584SAl Viro 	if (!tf.file)
21707699acd1SDavide Libenzi 		goto error_fput;
21717699acd1SDavide Libenzi 
21727699acd1SDavide Libenzi 	/* The target file descriptor must support poll */
21737699acd1SDavide Libenzi 	error = -EPERM;
21749965ed17SChristoph Hellwig 	if (!file_can_poll(tf.file))
21757699acd1SDavide Libenzi 		goto error_tgt_fput;
21767699acd1SDavide Libenzi 
21774d7e30d9SArve Hjønnevåg 	/* Check if EPOLLWAKEUP is allowed */
2178c680e41bSNicolas Iooss 	if (ep_op_has_event(op))
217958e41a44SJens Axboe 		ep_take_care_of_epollwakeup(epds);
21804d7e30d9SArve Hjønnevåg 
21817699acd1SDavide Libenzi 	/*
21827699acd1SDavide Libenzi 	 * We have to check that the file structure underneath the file descriptor
21837699acd1SDavide Libenzi 	 * the user passed to us _is_ an eventpoll file. And also we do not permit
21847699acd1SDavide Libenzi 	 * adding an epoll file descriptor inside itself.
21857699acd1SDavide Libenzi 	 */
21867699acd1SDavide Libenzi 	error = -EINVAL;
21877e3fb584SAl Viro 	if (f.file == tf.file || !is_file_epoll(f.file))
21887699acd1SDavide Libenzi 		goto error_tgt_fput;
21897699acd1SDavide Libenzi 
21907699acd1SDavide Libenzi 	/*
2191df0108c5SJason Baron 	 * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only,
2192df0108c5SJason Baron 	 * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation.
2193df0108c5SJason Baron 	 * Also, we do not currently supported nested exclusive wakeups.
2194df0108c5SJason Baron 	 */
219558e41a44SJens Axboe 	if (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) {
2196b6a515c8SJason Baron 		if (op == EPOLL_CTL_MOD)
2197df0108c5SJason Baron 			goto error_tgt_fput;
2198b6a515c8SJason Baron 		if (op == EPOLL_CTL_ADD && (is_file_epoll(tf.file) ||
219958e41a44SJens Axboe 				(epds->events & ~EPOLLEXCLUSIVE_OK_BITS)))
2200b6a515c8SJason Baron 			goto error_tgt_fput;
2201b6a515c8SJason Baron 	}
2202df0108c5SJason Baron 
2203df0108c5SJason Baron 	/*
22047699acd1SDavide Libenzi 	 * At this point it is safe to assume that the "private_data" contains
22057699acd1SDavide Libenzi 	 * our own data structure.
22067699acd1SDavide Libenzi 	 */
22077e3fb584SAl Viro 	ep = f.file->private_data;
22087699acd1SDavide Libenzi 
220922bacca4SDavide Libenzi 	/*
2210a6c67feeSRandy Dunlap 	 * When we insert an epoll file descriptor inside another epoll file
2211a6c67feeSRandy Dunlap 	 * descriptor, there is the chance of creating closed loops, which are
221228d82dc1SJason Baron 	 * better be handled here, than in more critical paths. While we are
221328d82dc1SJason Baron 	 * checking for loops we also determine the list of files reachable
221428d82dc1SJason Baron 	 * and hang them on the tfile_check_list, so we can check that we
221528d82dc1SJason Baron 	 * haven't created too many possible wakeup paths.
221622bacca4SDavide Libenzi 	 *
221767347fe4SJason Baron 	 * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when
221867347fe4SJason Baron 	 * the epoll file descriptor is attaching directly to a wakeup source,
221967347fe4SJason Baron 	 * unless the epoll file descriptor is nested. The purpose of taking the
2220d4cb626dSDavidlohr Bueso 	 * 'epnested_mutex' on add is to prevent complex toplogies such as loops and
222167347fe4SJason Baron 	 * deep wakeup paths from forming in parallel through multiple
222267347fe4SJason Baron 	 * EPOLL_CTL_ADD operations.
222322bacca4SDavide Libenzi 	 */
222439220e8dSJens Axboe 	error = epoll_mutex_lock(&ep->mtx, 0, nonblock);
222539220e8dSJens Axboe 	if (error)
222639220e8dSJens Axboe 		goto error_tgt_fput;
222728d82dc1SJason Baron 	if (op == EPOLL_CTL_ADD) {
2228319c1517SAl Viro 		if (READ_ONCE(f.file->f_ep) || ep->gen == loop_check_gen ||
222967347fe4SJason Baron 		    is_file_epoll(tf.file)) {
223067347fe4SJason Baron 			mutex_unlock(&ep->mtx);
2231d4cb626dSDavidlohr Bueso 			error = epoll_mutex_lock(&epnested_mutex, 0, nonblock);
223239220e8dSJens Axboe 			if (error)
223339220e8dSJens Axboe 				goto error_tgt_fput;
223418306c40SAl Viro 			loop_check_gen++;
223539220e8dSJens Axboe 			full_check = 1;
22367e3fb584SAl Viro 			if (is_file_epoll(tf.file)) {
2237bde03c4cSAl Viro 				tep = tf.file->private_data;
223822bacca4SDavide Libenzi 				error = -ELOOP;
2239bde03c4cSAl Viro 				if (ep_loop_check(ep, tep) != 0)
224022bacca4SDavide Libenzi 					goto error_tgt_fput;
2241a9ed4a65SMarc Zyngier 			}
224239220e8dSJens Axboe 			error = epoll_mutex_lock(&ep->mtx, 0, nonblock);
224352c47969SAl Viro 			if (error)
224439220e8dSJens Axboe 				goto error_tgt_fput;
224567347fe4SJason Baron 		}
224667347fe4SJason Baron 	}
22477699acd1SDavide Libenzi 
224867647d0fSDavide Libenzi 	/*
2249a6c67feeSRandy Dunlap 	 * Try to lookup the file inside our RB tree. Since we grabbed "mtx"
225067647d0fSDavide Libenzi 	 * above, we can be sure to be able to use the item looked up by
225167647d0fSDavide Libenzi 	 * ep_find() till we release the mutex.
225267647d0fSDavide Libenzi 	 */
22537e3fb584SAl Viro 	epi = ep_find(ep, tf.file, fd);
22547699acd1SDavide Libenzi 
22557699acd1SDavide Libenzi 	error = -EINVAL;
22567699acd1SDavide Libenzi 	switch (op) {
22577699acd1SDavide Libenzi 	case EPOLL_CTL_ADD:
22587699acd1SDavide Libenzi 		if (!epi) {
225958e41a44SJens Axboe 			epds->events |= EPOLLERR | EPOLLHUP;
226058e41a44SJens Axboe 			error = ep_insert(ep, epds, tf.file, fd, full_check);
22617699acd1SDavide Libenzi 		} else
22627699acd1SDavide Libenzi 			error = -EEXIST;
22637699acd1SDavide Libenzi 		break;
22647699acd1SDavide Libenzi 	case EPOLL_CTL_DEL:
226558c9b016SPaolo Abeni 		if (epi) {
226658c9b016SPaolo Abeni 			/*
226758c9b016SPaolo Abeni 			 * The eventpoll itself is still alive: the refcount
226858c9b016SPaolo Abeni 			 * can't go to zero here.
226958c9b016SPaolo Abeni 			 */
227058c9b016SPaolo Abeni 			ep_remove_safe(ep, epi);
227158c9b016SPaolo Abeni 			error = 0;
227258c9b016SPaolo Abeni 		} else {
22737699acd1SDavide Libenzi 			error = -ENOENT;
227458c9b016SPaolo Abeni 		}
22757699acd1SDavide Libenzi 		break;
22767699acd1SDavide Libenzi 	case EPOLL_CTL_MOD:
22777699acd1SDavide Libenzi 		if (epi) {
2278b6a515c8SJason Baron 			if (!(epi->event.events & EPOLLEXCLUSIVE)) {
227958e41a44SJens Axboe 				epds->events |= EPOLLERR | EPOLLHUP;
228058e41a44SJens Axboe 				error = ep_modify(ep, epi, epds);
2281b6a515c8SJason Baron 			}
22827699acd1SDavide Libenzi 		} else
22837699acd1SDavide Libenzi 			error = -ENOENT;
22847699acd1SDavide Libenzi 		break;
22857699acd1SDavide Libenzi 	}
2286d47de16cSDavide Libenzi 	mutex_unlock(&ep->mtx);
22877699acd1SDavide Libenzi 
22887699acd1SDavide Libenzi error_tgt_fput:
228952c47969SAl Viro 	if (full_check) {
229052c47969SAl Viro 		clear_tfile_check_list();
229118306c40SAl Viro 		loop_check_gen++;
2292d4cb626dSDavidlohr Bueso 		mutex_unlock(&epnested_mutex);
229352c47969SAl Viro 	}
229422bacca4SDavide Libenzi 
22957e3fb584SAl Viro 	fdput(tf);
22967699acd1SDavide Libenzi error_fput:
22977e3fb584SAl Viro 	fdput(f);
22987699acd1SDavide Libenzi error_return:
22997699acd1SDavide Libenzi 
23007699acd1SDavide Libenzi 	return error;
23017699acd1SDavide Libenzi }
23027699acd1SDavide Libenzi 
23037699acd1SDavide Libenzi /*
230458e41a44SJens Axboe  * The following function implements the controller interface for
230558e41a44SJens Axboe  * the eventpoll file that enables the insertion/removal/change of
230658e41a44SJens Axboe  * file descriptors inside the interest set.
230758e41a44SJens Axboe  */
SYSCALL_DEFINE4(epoll_ctl,int,epfd,int,op,int,fd,struct epoll_event __user *,event)230858e41a44SJens Axboe SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
230958e41a44SJens Axboe 		struct epoll_event __user *, event)
231058e41a44SJens Axboe {
231158e41a44SJens Axboe 	struct epoll_event epds;
231258e41a44SJens Axboe 
231358e41a44SJens Axboe 	if (ep_op_has_event(op) &&
231458e41a44SJens Axboe 	    copy_from_user(&epds, event, sizeof(struct epoll_event)))
231558e41a44SJens Axboe 		return -EFAULT;
231658e41a44SJens Axboe 
231739220e8dSJens Axboe 	return do_epoll_ctl(epfd, op, fd, &epds, false);
231858e41a44SJens Axboe }
231958e41a44SJens Axboe 
232058e41a44SJens Axboe /*
23217699acd1SDavide Libenzi  * Implement the event wait interface for the eventpoll file. It is the kernel
23227699acd1SDavide Libenzi  * part of the user space epoll_wait(2).
23237699acd1SDavide Libenzi  */
do_epoll_wait(int epfd,struct epoll_event __user * events,int maxevents,struct timespec64 * to)2324791eb22eSDominik Brodowski static int do_epoll_wait(int epfd, struct epoll_event __user *events,
23257cdf7c20SWillem de Bruijn 			 int maxevents, struct timespec64 *to)
23267699acd1SDavide Libenzi {
23272903ff01SAl Viro 	int error;
23282903ff01SAl Viro 	struct fd f;
23297699acd1SDavide Libenzi 	struct eventpoll *ep;
23307699acd1SDavide Libenzi 
23317699acd1SDavide Libenzi 	/* The maximum number of event must be greater than zero */
23327699acd1SDavide Libenzi 	if (maxevents <= 0 || maxevents > EP_MAX_EVENTS)
23337699acd1SDavide Libenzi 		return -EINVAL;
23347699acd1SDavide Libenzi 
23357699acd1SDavide Libenzi 	/* Verify that the area passed by the user is writeable */
233696d4f267SLinus Torvalds 	if (!access_ok(events, maxevents * sizeof(struct epoll_event)))
23372903ff01SAl Viro 		return -EFAULT;
23387699acd1SDavide Libenzi 
23397699acd1SDavide Libenzi 	/* Get the "struct file *" for the eventpoll file */
23402903ff01SAl Viro 	f = fdget(epfd);
23412903ff01SAl Viro 	if (!f.file)
23422903ff01SAl Viro 		return -EBADF;
23437699acd1SDavide Libenzi 
23447699acd1SDavide Libenzi 	/*
23457699acd1SDavide Libenzi 	 * We have to check that the file structure underneath the fd
23467699acd1SDavide Libenzi 	 * the user passed to us _is_ an eventpoll file.
23477699acd1SDavide Libenzi 	 */
23487699acd1SDavide Libenzi 	error = -EINVAL;
23492903ff01SAl Viro 	if (!is_file_epoll(f.file))
23507699acd1SDavide Libenzi 		goto error_fput;
23517699acd1SDavide Libenzi 
23527699acd1SDavide Libenzi 	/*
23537699acd1SDavide Libenzi 	 * At this point it is safe to assume that the "private_data" contains
23547699acd1SDavide Libenzi 	 * our own data structure.
23557699acd1SDavide Libenzi 	 */
23562903ff01SAl Viro 	ep = f.file->private_data;
23577699acd1SDavide Libenzi 
23587699acd1SDavide Libenzi 	/* Time to fish for events ... */
23597cdf7c20SWillem de Bruijn 	error = ep_poll(ep, events, maxevents, to);
23607699acd1SDavide Libenzi 
23617699acd1SDavide Libenzi error_fput:
23622903ff01SAl Viro 	fdput(f);
23637699acd1SDavide Libenzi 	return error;
23647699acd1SDavide Libenzi }
23657699acd1SDavide Libenzi 
SYSCALL_DEFINE4(epoll_wait,int,epfd,struct epoll_event __user *,events,int,maxevents,int,timeout)2366791eb22eSDominik Brodowski SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events,
2367791eb22eSDominik Brodowski 		int, maxevents, int, timeout)
2368791eb22eSDominik Brodowski {
23697cdf7c20SWillem de Bruijn 	struct timespec64 to;
23707cdf7c20SWillem de Bruijn 
23717cdf7c20SWillem de Bruijn 	return do_epoll_wait(epfd, events, maxevents,
23727cdf7c20SWillem de Bruijn 			     ep_timeout_to_timespec(&to, timeout));
2373791eb22eSDominik Brodowski }
2374791eb22eSDominik Brodowski 
23757699acd1SDavide Libenzi /*
23767699acd1SDavide Libenzi  * Implement the event wait interface for the eventpoll file. It is the kernel
23777699acd1SDavide Libenzi  * part of the user space epoll_pwait(2).
23787699acd1SDavide Libenzi  */
do_epoll_pwait(int epfd,struct epoll_event __user * events,int maxevents,struct timespec64 * to,const sigset_t __user * sigmask,size_t sigsetsize)237958169a52SWillem de Bruijn static int do_epoll_pwait(int epfd, struct epoll_event __user *events,
238058169a52SWillem de Bruijn 			  int maxevents, struct timespec64 *to,
238158169a52SWillem de Bruijn 			  const sigset_t __user *sigmask, size_t sigsetsize)
23827699acd1SDavide Libenzi {
23837699acd1SDavide Libenzi 	int error;
23847699acd1SDavide Libenzi 
23857699acd1SDavide Libenzi 	/*
23867699acd1SDavide Libenzi 	 * If the caller wants a certain signal mask to be set during the wait,
23877699acd1SDavide Libenzi 	 * we apply it here.
23887699acd1SDavide Libenzi 	 */
2389b772434bSOleg Nesterov 	error = set_user_sigmask(sigmask, sigsetsize);
2390ded653ccSDeepa Dinamani 	if (error)
2391ded653ccSDeepa Dinamani 		return error;
23927699acd1SDavide Libenzi 
239358169a52SWillem de Bruijn 	error = do_epoll_wait(epfd, events, maxevents, to);
23947cdf7c20SWillem de Bruijn 
2395b772434bSOleg Nesterov 	restore_saved_sigmask_unless(error == -EINTR);
23967699acd1SDavide Libenzi 
23977699acd1SDavide Libenzi 	return error;
23987699acd1SDavide Libenzi }
23997699acd1SDavide Libenzi 
SYSCALL_DEFINE6(epoll_pwait,int,epfd,struct epoll_event __user *,events,int,maxevents,int,timeout,const sigset_t __user *,sigmask,size_t,sigsetsize)240058169a52SWillem de Bruijn SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
240158169a52SWillem de Bruijn 		int, maxevents, int, timeout, const sigset_t __user *, sigmask,
240258169a52SWillem de Bruijn 		size_t, sigsetsize)
240335280bd4SAl Viro {
24047cdf7c20SWillem de Bruijn 	struct timespec64 to;
240558169a52SWillem de Bruijn 
240658169a52SWillem de Bruijn 	return do_epoll_pwait(epfd, events, maxevents,
240758169a52SWillem de Bruijn 			      ep_timeout_to_timespec(&to, timeout),
240858169a52SWillem de Bruijn 			      sigmask, sigsetsize);
240958169a52SWillem de Bruijn }
241058169a52SWillem de Bruijn 
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)241158169a52SWillem de Bruijn SYSCALL_DEFINE6(epoll_pwait2, int, epfd, struct epoll_event __user *, events,
241258169a52SWillem de Bruijn 		int, maxevents, const struct __kernel_timespec __user *, timeout,
241358169a52SWillem de Bruijn 		const sigset_t __user *, sigmask, size_t, sigsetsize)
241458169a52SWillem de Bruijn {
241558169a52SWillem de Bruijn 	struct timespec64 ts, *to = NULL;
241658169a52SWillem de Bruijn 
241758169a52SWillem de Bruijn 	if (timeout) {
241858169a52SWillem de Bruijn 		if (get_timespec64(&ts, timeout))
241958169a52SWillem de Bruijn 			return -EFAULT;
242058169a52SWillem de Bruijn 		to = &ts;
242158169a52SWillem de Bruijn 		if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
242258169a52SWillem de Bruijn 			return -EINVAL;
242358169a52SWillem de Bruijn 	}
242458169a52SWillem de Bruijn 
242558169a52SWillem de Bruijn 	return do_epoll_pwait(epfd, events, maxevents, to,
242658169a52SWillem de Bruijn 			      sigmask, sigsetsize);
242758169a52SWillem de Bruijn }
242858169a52SWillem de Bruijn 
242958169a52SWillem de Bruijn #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)243058169a52SWillem de Bruijn static int do_compat_epoll_pwait(int epfd, struct epoll_event __user *events,
243158169a52SWillem de Bruijn 				 int maxevents, struct timespec64 *timeout,
243258169a52SWillem de Bruijn 				 const compat_sigset_t __user *sigmask,
243358169a52SWillem de Bruijn 				 compat_size_t sigsetsize)
243458169a52SWillem de Bruijn {
243535280bd4SAl Viro 	long err;
243635280bd4SAl Viro 
243735280bd4SAl Viro 	/*
243835280bd4SAl Viro 	 * If the caller wants a certain signal mask to be set during the wait,
243935280bd4SAl Viro 	 * we apply it here.
244035280bd4SAl Viro 	 */
2441b772434bSOleg Nesterov 	err = set_compat_user_sigmask(sigmask, sigsetsize);
2442ded653ccSDeepa Dinamani 	if (err)
2443ded653ccSDeepa Dinamani 		return err;
244435280bd4SAl Viro 
244558169a52SWillem de Bruijn 	err = do_epoll_wait(epfd, events, maxevents, timeout);
24467cdf7c20SWillem de Bruijn 
2447b772434bSOleg Nesterov 	restore_saved_sigmask_unless(err == -EINTR);
244835280bd4SAl Viro 
244935280bd4SAl Viro 	return err;
245035280bd4SAl Viro }
245158169a52SWillem de Bruijn 
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)245258169a52SWillem de Bruijn COMPAT_SYSCALL_DEFINE6(epoll_pwait, int, epfd,
245358169a52SWillem de Bruijn 		       struct epoll_event __user *, events,
245458169a52SWillem de Bruijn 		       int, maxevents, int, timeout,
245558169a52SWillem de Bruijn 		       const compat_sigset_t __user *, sigmask,
245658169a52SWillem de Bruijn 		       compat_size_t, sigsetsize)
245758169a52SWillem de Bruijn {
245858169a52SWillem de Bruijn 	struct timespec64 to;
245958169a52SWillem de Bruijn 
246058169a52SWillem de Bruijn 	return do_compat_epoll_pwait(epfd, events, maxevents,
246158169a52SWillem de Bruijn 				     ep_timeout_to_timespec(&to, timeout),
246258169a52SWillem de Bruijn 				     sigmask, sigsetsize);
246358169a52SWillem de Bruijn }
246458169a52SWillem de Bruijn 
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)246558169a52SWillem de Bruijn COMPAT_SYSCALL_DEFINE6(epoll_pwait2, int, epfd,
246658169a52SWillem de Bruijn 		       struct epoll_event __user *, events,
246758169a52SWillem de Bruijn 		       int, maxevents,
246858169a52SWillem de Bruijn 		       const struct __kernel_timespec __user *, timeout,
246958169a52SWillem de Bruijn 		       const compat_sigset_t __user *, sigmask,
247058169a52SWillem de Bruijn 		       compat_size_t, sigsetsize)
247158169a52SWillem de Bruijn {
247258169a52SWillem de Bruijn 	struct timespec64 ts, *to = NULL;
247358169a52SWillem de Bruijn 
247458169a52SWillem de Bruijn 	if (timeout) {
247558169a52SWillem de Bruijn 		if (get_timespec64(&ts, timeout))
247658169a52SWillem de Bruijn 			return -EFAULT;
247758169a52SWillem de Bruijn 		to = &ts;
247858169a52SWillem de Bruijn 		if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
247958169a52SWillem de Bruijn 			return -EINVAL;
248058169a52SWillem de Bruijn 	}
248158169a52SWillem de Bruijn 
248258169a52SWillem de Bruijn 	return do_compat_epoll_pwait(epfd, events, maxevents, to,
248358169a52SWillem de Bruijn 				     sigmask, sigsetsize);
248458169a52SWillem de Bruijn }
248558169a52SWillem de Bruijn 
248635280bd4SAl Viro #endif
248735280bd4SAl Viro 
eventpoll_init(void)24881da177e4SLinus Torvalds static int __init eventpoll_init(void)
24891da177e4SLinus Torvalds {
24907ef9964eSDavide Libenzi 	struct sysinfo si;
24917ef9964eSDavide Libenzi 
24927ef9964eSDavide Libenzi 	si_meminfo(&si);
24939df04e1fSDavide Libenzi 	/*
24949df04e1fSDavide Libenzi 	 * Allows top 4% of lomem to be allocated for epoll watches (per user).
24959df04e1fSDavide Libenzi 	 */
24969df04e1fSDavide Libenzi 	max_user_watches = (((si.totalram - si.totalhigh) / 25) << PAGE_SHIFT) /
24977ef9964eSDavide Libenzi 		EP_ITEM_COST;
249852bd19f7SRobin Holt 	BUG_ON(max_user_watches < 0);
24991da177e4SLinus Torvalds 
250022bacca4SDavide Libenzi 	/*
250139732ca5SEric Wong 	 * We can have many thousands of epitems, so prevent this from
250239732ca5SEric Wong 	 * using an extra cache line on 64-bit (and smaller) CPUs
250339732ca5SEric Wong 	 */
250439732ca5SEric Wong 	BUILD_BUG_ON(sizeof(void *) <= 8 && sizeof(struct epitem) > 128);
250539732ca5SEric Wong 
25061da177e4SLinus Torvalds 	/* Allocates slab cache used to allocate "struct epitem" items */
25071da177e4SLinus Torvalds 	epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
25082ae928a9SShakeel Butt 			0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, NULL);
25091da177e4SLinus Torvalds 
25101da177e4SLinus Torvalds 	/* Allocates slab cache used to allocate "struct eppoll_entry" */
25111da177e4SLinus Torvalds 	pwq_cache = kmem_cache_create("eventpoll_pwq",
25122ae928a9SShakeel Butt 		sizeof(struct eppoll_entry), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL);
2513a8f5de89SXiaoming Ni 	epoll_sysctls_init();
25141da177e4SLinus Torvalds 
2515319c1517SAl Viro 	ephead_cache = kmem_cache_create("ep_head",
2516319c1517SAl Viro 		sizeof(struct epitems_head), 0, SLAB_PANIC|SLAB_ACCOUNT, NULL);
2517319c1517SAl Viro 
25181da177e4SLinus Torvalds 	return 0;
25191da177e4SLinus Torvalds }
2520cea69241SDavide Libenzi fs_initcall(eventpoll_init);
2521