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