2 * fs/eventpoll.c ( Efficent event polling implementation )
3 * Copyright (C) 2001,...,2006 Davide Libenzi
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * Davide Libenzi <davidel@xmailserver.org>
14 #include <linux/init.h>
15 #include <linux/kernel.h>
16 #include <linux/sched.h>
18 #include <linux/file.h>
19 #include <linux/signal.h>
20 #include <linux/errno.h>
22 #include <linux/slab.h>
23 #include <linux/poll.h>
24 #include <linux/string.h>
25 #include <linux/list.h>
26 #include <linux/hash.h>
27 #include <linux/spinlock.h>
28 #include <linux/syscalls.h>
29 #include <linux/rwsem.h>
30 #include <linux/rbtree.h>
31 #include <linux/wait.h>
32 #include <linux/eventpoll.h>
33 #include <linux/mount.h>
34 #include <linux/bitops.h>
35 #include <linux/mutex.h>
36 #include <linux/anon_inodes.h>
37 #include <asm/uaccess.h>
38 #include <asm/system.h>
41 #include <asm/atomic.h>
42 #include <asm/semaphore.h>
46 * There are three level of locking required by epoll :
49 * 2) ep->sem (rw_semaphore)
50 * 3) ep->lock (rw_lock)
52 * The acquire order is the one listed above, from 1 to 3.
53 * We need a spinlock (ep->lock) because we manipulate objects
54 * from inside the poll callback, that might be triggered from
55 * a wake_up() that in turn might be called from IRQ context.
56 * So we can't sleep inside the poll callback and hence we need
57 * a spinlock. During the event transfer loop (from kernel to
58 * user space) we could end up sleeping due a copy_to_user(), so
59 * we need a lock that will allow us to sleep. This lock is a
60 * read-write semaphore (ep->sem). It is acquired on read during
61 * the event transfer loop and in write during epoll_ctl(EPOLL_CTL_DEL)
62 * and during eventpoll_release_file(). Then we also need a global
63 * semaphore to serialize eventpoll_release_file() and ep_free().
64 * This semaphore is acquired by ep_free() during the epoll file
65 * cleanup path and it is also acquired by eventpoll_release_file()
66 * if a file has been pushed inside an epoll set and it is then
67 * close()d without a previous call toepoll_ctl(EPOLL_CTL_DEL).
68 * It is possible to drop the "ep->sem" and to use the global
69 * semaphore "epmutex" (together with "ep->lock") to have it working,
70 * but having "ep->sem" will make the interface more scalable.
71 * Events that require holding "epmutex" are very rare, while for
72 * normal operations the epoll private "ep->sem" will guarantee
73 * a greater scalability.
79 #define DPRINTK(x) printk x
80 #define DNPRINTK(n, x) do { if ((n) <= DEBUG_EPOLL) printk x; } while (0)
81 #else /* #if DEBUG_EPOLL > 0 */
82 #define DPRINTK(x) (void) 0
83 #define DNPRINTK(n, x) (void) 0
84 #endif /* #if DEBUG_EPOLL > 0 */
89 #define EPI_SLAB_DEBUG (SLAB_DEBUG_FREE | SLAB_RED_ZONE /* | SLAB_POISON */)
90 #else /* #if DEBUG_EPI != 0 */
91 #define EPI_SLAB_DEBUG 0
92 #endif /* #if DEBUG_EPI != 0 */
94 /* Epoll private bits inside the event mask */
95 #define EP_PRIVATE_BITS (EPOLLONESHOT | EPOLLET)
97 /* Maximum number of poll wake up nests we are allowing */
98 #define EP_MAX_POLLWAKE_NESTS 4
100 /* Maximum msec timeout value storeable in a long int */
101 #define EP_MAX_MSTIMEO min(1000ULL * MAX_SCHEDULE_TIMEOUT / HZ, (LONG_MAX - 999ULL) / HZ)
103 #define EP_MAX_EVENTS (INT_MAX / sizeof(struct epoll_event))
105 struct epoll_filefd {
111 * Node that is linked into the "wake_task_list" member of the "struct poll_safewake".
112 * It is used to keep track on all tasks that are currently inside the wake_up() code
113 * to 1) short-circuit the one coming from the same task and same wait queue head
114 * ( loop ) 2) allow a maximum number of epoll descriptors inclusion nesting
115 * 3) let go the ones coming from other tasks.
117 struct wake_task_node {
118 struct list_head llink;
119 struct task_struct *task;
120 wait_queue_head_t *wq;
124 * This is used to implement the safe poll wake up avoiding to reenter
125 * the poll callback from inside wake_up().
127 struct poll_safewake {
128 struct list_head wake_task_list;
133 * This structure is stored inside the "private_data" member of the file
134 * structure and rapresent the main data sructure for the eventpoll
138 /* Protect the this structure access */
142 * This semaphore is used to ensure that files are not removed
143 * while epoll is using them. This is read-held during the event
144 * collection loop and it is write-held during the file cleanup
145 * path, the epoll file exit code and the ctl operations.
147 struct rw_semaphore sem;
149 /* Wait queue used by sys_epoll_wait() */
150 wait_queue_head_t wq;
152 /* Wait queue used by file->poll() */
153 wait_queue_head_t poll_wait;
155 /* List of ready file descriptors */
156 struct list_head rdllist;
158 /* RB-Tree root used to store monitored fd structs */
162 /* Wait structure used by the poll hooks */
163 struct eppoll_entry {
164 /* List header used to link this structure to the "struct epitem" */
165 struct list_head llink;
167 /* The "base" pointer is set to the container "struct epitem" */
171 * Wait queue item that will be linked to the target file wait
176 /* The wait queue head that linked the "wait" wait queue item */
177 wait_queue_head_t *whead;
181 * Each file descriptor added to the eventpoll interface will
182 * have an entry of this type linked to the "rbr" RB tree.
185 /* RB-Tree node used to link this structure to the eventpoll rb-tree */
188 /* List header used to link this structure to the eventpoll ready list */
189 struct list_head rdllink;
191 /* The file descriptor information this item refers to */
192 struct epoll_filefd ffd;
194 /* Number of active wait queue attached to poll operations */
197 /* List containing poll wait queues */
198 struct list_head pwqlist;
200 /* The "container" of this item */
201 struct eventpoll *ep;
203 /* The structure that describe the interested events and the source fd */
204 struct epoll_event event;
207 * Used to keep track of the usage count of the structure. This avoids
208 * that the structure will desappear from underneath our processing.
212 /* List header used to link this item to the "struct file" items list */
213 struct list_head fllink;
216 /* Wrapper struct used by poll queueing */
223 * This semaphore is used to serialize ep_free() and eventpoll_release_file().
225 static struct mutex epmutex;
227 /* Safe wake up implementation */
228 static struct poll_safewake psw;
230 /* Slab cache used to allocate "struct epitem" */
231 static struct kmem_cache *epi_cache __read_mostly;
233 /* Slab cache used to allocate "struct eppoll_entry" */
234 static struct kmem_cache *pwq_cache __read_mostly;
237 /* Setup the structure that is used as key for the rb-tree */
238 static inline void ep_set_ffd(struct epoll_filefd *ffd,
239 struct file *file, int fd)
245 /* Compare rb-tree keys */
246 static inline int ep_cmp_ffd(struct epoll_filefd *p1,
247 struct epoll_filefd *p2)
249 return (p1->file > p2->file ? +1:
250 (p1->file < p2->file ? -1 : p1->fd - p2->fd));
253 /* Special initialization for the rb-tree node to detect linkage */
254 static inline void ep_rb_initnode(struct rb_node *n)
259 /* Removes a node from the rb-tree and marks it for a fast is-linked check */
260 static inline void ep_rb_erase(struct rb_node *n, struct rb_root *r)
266 /* Fast check to verify that the item is linked to the main rb-tree */
267 static inline int ep_rb_linked(struct rb_node *n)
269 return rb_parent(n) != n;
272 /* Tells us if the item is currently linked */
273 static inline int ep_is_linked(struct list_head *p)
275 return !list_empty(p);
278 /* Get the "struct epitem" from a wait queue pointer */
279 static inline struct epitem * ep_item_from_wait(wait_queue_t *p)
281 return container_of(p, struct eppoll_entry, wait)->base;
284 /* Get the "struct epitem" from an epoll queue wrapper */
285 static inline struct epitem * ep_item_from_epqueue(poll_table *p)
287 return container_of(p, struct ep_pqueue, pt)->epi;
290 /* Tells if the epoll_ctl(2) operation needs an event copy from userspace */
291 static inline int ep_op_has_event(int op)
293 return op != EPOLL_CTL_DEL;
296 /* Initialize the poll safe wake up structure */
297 static void ep_poll_safewake_init(struct poll_safewake *psw)
300 INIT_LIST_HEAD(&psw->wake_task_list);
301 spin_lock_init(&psw->lock);
305 * Perform a safe wake up of the poll wait list. The problem is that
306 * with the new callback'd wake up system, it is possible that the
307 * poll callback is reentered from inside the call to wake_up() done
308 * on the poll wait queue head. The rule is that we cannot reenter the
309 * wake up code from the same task more than EP_MAX_POLLWAKE_NESTS times,
310 * and we cannot reenter the same wait queue head at all. This will
311 * enable to have a hierarchy of epoll file descriptor of no more than
312 * EP_MAX_POLLWAKE_NESTS deep. We need the irq version of the spin lock
313 * because this one gets called by the poll callback, that in turn is called
314 * from inside a wake_up(), that might be called from irq context.
316 static void ep_poll_safewake(struct poll_safewake *psw, wait_queue_head_t *wq)
320 struct task_struct *this_task = current;
321 struct list_head *lsthead = &psw->wake_task_list, *lnk;
322 struct wake_task_node *tncur;
323 struct wake_task_node tnode;
325 spin_lock_irqsave(&psw->lock, flags);
327 /* Try to see if the current task is already inside this wakeup call */
328 list_for_each(lnk, lsthead) {
329 tncur = list_entry(lnk, struct wake_task_node, llink);
331 if (tncur->wq == wq ||
332 (tncur->task == this_task && ++wake_nests > EP_MAX_POLLWAKE_NESTS)) {
334 * Ops ... loop detected or maximum nest level reached.
335 * We abort this wake by breaking the cycle itself.
337 spin_unlock_irqrestore(&psw->lock, flags);
342 /* Add the current task to the list */
343 tnode.task = this_task;
345 list_add(&tnode.llink, lsthead);
347 spin_unlock_irqrestore(&psw->lock, flags);
349 /* Do really wake up now */
352 /* Remove the current task from the list */
353 spin_lock_irqsave(&psw->lock, flags);
354 list_del(&tnode.llink);
355 spin_unlock_irqrestore(&psw->lock, flags);
359 * This function unregister poll callbacks from the associated file descriptor.
360 * Since this must be called without holding "ep->lock" the atomic exchange trick
361 * will protect us from multiple unregister.
363 static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi)
366 struct list_head *lsthead = &epi->pwqlist;
367 struct eppoll_entry *pwq;
369 /* This is called without locks, so we need the atomic exchange */
370 nwait = xchg(&epi->nwait, 0);
373 while (!list_empty(lsthead)) {
374 pwq = list_first_entry(lsthead, struct eppoll_entry, llink);
376 list_del_init(&pwq->llink);
377 remove_wait_queue(pwq->whead, &pwq->wait);
378 kmem_cache_free(pwq_cache, pwq);
384 * Unlink the "struct epitem" from all places it might have been hooked up.
385 * This function must be called with write IRQ lock on "ep->lock".
387 static int ep_unlink(struct eventpoll *ep, struct epitem *epi)
392 * It can happen that this one is called for an item already unlinked.
393 * The check protect us from doing a double unlink ( crash ).
396 if (!ep_rb_linked(&epi->rbn))
400 * Clear the event mask for the unlinked item. This will avoid item
401 * notifications to be sent after the unlink operation from inside
402 * the kernel->userspace event transfer loop.
404 epi->event.events = 0;
407 * At this point is safe to do the job, unlink the item from our rb-tree.
408 * This operation togheter with the above check closes the door to
411 ep_rb_erase(&epi->rbn, &ep->rbr);
414 * If the item we are going to remove is inside the ready file descriptors
415 * we want to remove it from this list to avoid stale events.
417 if (ep_is_linked(&epi->rdllink))
418 list_del_init(&epi->rdllink);
423 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_unlink(%p, %p) = %d\n",
424 current, ep, epi->ffd.file, error));
430 * Increment the usage count of the "struct epitem" making it sure
431 * that the user will have a valid pointer to reference.
433 static void ep_use_epitem(struct epitem *epi)
435 atomic_inc(&epi->usecnt);
439 * Decrement ( release ) the usage count by signaling that the user
440 * has finished using the structure. It might lead to freeing the
441 * structure itself if the count goes to zero.
443 static void ep_release_epitem(struct epitem *epi)
445 if (atomic_dec_and_test(&epi->usecnt))
446 kmem_cache_free(epi_cache, epi);
450 * Removes a "struct epitem" from the eventpoll RB tree and deallocates
451 * all the associated resources.
453 static int ep_remove(struct eventpoll *ep, struct epitem *epi)
457 struct file *file = epi->ffd.file;
460 * Removes poll wait queue hooks. We _have_ to do this without holding
461 * the "ep->lock" otherwise a deadlock might occur. This because of the
462 * sequence of the lock acquisition. Here we do "ep->lock" then the wait
463 * queue head lock when unregistering the wait queue. The wakeup callback
464 * will run by holding the wait queue head lock and will call our callback
465 * that will try to get "ep->lock".
467 ep_unregister_pollwait(ep, epi);
469 /* Remove the current item from the list of epoll hooks */
470 spin_lock(&file->f_ep_lock);
471 if (ep_is_linked(&epi->fllink))
472 list_del_init(&epi->fllink);
473 spin_unlock(&file->f_ep_lock);
475 /* We need to acquire the write IRQ lock before calling ep_unlink() */
476 write_lock_irqsave(&ep->lock, flags);
478 /* Really unlink the item from the RB tree */
479 error = ep_unlink(ep, epi);
481 write_unlock_irqrestore(&ep->lock, flags);
486 /* At this point it is safe to free the eventpoll item */
487 ep_release_epitem(epi);
491 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_remove(%p, %p) = %d\n",
492 current, ep, file, error));
497 static void ep_free(struct eventpoll *ep)
502 /* We need to release all tasks waiting for these file */
503 if (waitqueue_active(&ep->poll_wait))
504 ep_poll_safewake(&psw, &ep->poll_wait);
507 * We need to lock this because we could be hit by
508 * eventpoll_release_file() while we're freeing the "struct eventpoll".
509 * We do not need to hold "ep->sem" here because the epoll file
510 * is on the way to be removed and no one has references to it
511 * anymore. The only hit might come from eventpoll_release_file() but
512 * holding "epmutex" is sufficent here.
514 mutex_lock(&epmutex);
517 * Walks through the whole tree by unregistering poll callbacks.
519 for (rbp = rb_first(&ep->rbr); rbp; rbp = rb_next(rbp)) {
520 epi = rb_entry(rbp, struct epitem, rbn);
522 ep_unregister_pollwait(ep, epi);
526 * Walks through the whole tree by freeing each "struct epitem". At this
527 * point we are sure no poll callbacks will be lingering around, and also by
528 * write-holding "sem" we can be sure that no file cleanup code will hit
529 * us during this operation. So we can avoid the lock on "ep->lock".
531 while ((rbp = rb_first(&ep->rbr)) != 0) {
532 epi = rb_entry(rbp, struct epitem, rbn);
536 mutex_unlock(&epmutex);
539 static int ep_eventpoll_release(struct inode *inode, struct file *file)
541 struct eventpoll *ep = file->private_data;
548 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: close() ep=%p\n", current, ep));
552 static unsigned int ep_eventpoll_poll(struct file *file, poll_table *wait)
554 unsigned int pollflags = 0;
556 struct eventpoll *ep = file->private_data;
558 /* Insert inside our poll wait queue */
559 poll_wait(file, &ep->poll_wait, wait);
561 /* Check our condition */
562 read_lock_irqsave(&ep->lock, flags);
563 if (!list_empty(&ep->rdllist))
564 pollflags = POLLIN | POLLRDNORM;
565 read_unlock_irqrestore(&ep->lock, flags);
570 /* File callbacks that implement the eventpoll file behaviour */
571 static const struct file_operations eventpoll_fops = {
572 .release = ep_eventpoll_release,
573 .poll = ep_eventpoll_poll
576 /* Fast test to see if the file is an evenpoll file */
577 static inline int is_file_epoll(struct file *f)
579 return f->f_op == &eventpoll_fops;
583 * This is called from eventpoll_release() to unlink files from the eventpoll
584 * interface. We need to have this facility to cleanup correctly files that are
585 * closed without being removed from the eventpoll interface.
587 void eventpoll_release_file(struct file *file)
589 struct list_head *lsthead = &file->f_ep_links;
590 struct eventpoll *ep;
594 * We don't want to get "file->f_ep_lock" because it is not
595 * necessary. It is not necessary because we're in the "struct file"
596 * cleanup path, and this means that noone is using this file anymore.
597 * The only hit might come from ep_free() but by holding the semaphore
598 * will correctly serialize the operation. We do need to acquire
599 * "ep->sem" after "epmutex" because ep_remove() requires it when called
600 * from anywhere but ep_free().
602 mutex_lock(&epmutex);
604 while (!list_empty(lsthead)) {
605 epi = list_first_entry(lsthead, struct epitem, fllink);
608 list_del_init(&epi->fllink);
609 down_write(&ep->sem);
614 mutex_unlock(&epmutex);
617 static int ep_alloc(struct eventpoll **pep)
619 struct eventpoll *ep = kzalloc(sizeof(*ep), GFP_KERNEL);
624 rwlock_init(&ep->lock);
625 init_rwsem(&ep->sem);
626 init_waitqueue_head(&ep->wq);
627 init_waitqueue_head(&ep->poll_wait);
628 INIT_LIST_HEAD(&ep->rdllist);
633 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_alloc() ep=%p\n",
639 * Search the file inside the eventpoll tree. It add usage count to
640 * the returned item, so the caller must call ep_release_epitem()
641 * after finished using the "struct epitem".
643 static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
648 struct epitem *epi, *epir = NULL;
649 struct epoll_filefd ffd;
651 ep_set_ffd(&ffd, file, fd);
652 read_lock_irqsave(&ep->lock, flags);
653 for (rbp = ep->rbr.rb_node; rbp; ) {
654 epi = rb_entry(rbp, struct epitem, rbn);
655 kcmp = ep_cmp_ffd(&ffd, &epi->ffd);
666 read_unlock_irqrestore(&ep->lock, flags);
668 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_find(%p) -> %p\n",
669 current, file, epir));
675 * This is the callback that is passed to the wait queue wakeup
676 * machanism. It is called by the stored file descriptors when they
677 * have events to report.
679 static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *key)
683 struct epitem *epi = ep_item_from_wait(wait);
684 struct eventpoll *ep = epi->ep;
686 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: poll_callback(%p) epi=%p ep=%p\n",
687 current, epi->ffd.file, epi, ep));
689 write_lock_irqsave(&ep->lock, flags);
692 * If the event mask does not contain any poll(2) event, we consider the
693 * descriptor to be disabled. This condition is likely the effect of the
694 * EPOLLONESHOT bit that disables the descriptor when an event is received,
695 * until the next EPOLL_CTL_MOD will be issued.
697 if (!(epi->event.events & ~EP_PRIVATE_BITS))
700 /* If this file is already in the ready list we exit soon */
701 if (ep_is_linked(&epi->rdllink))
704 list_add_tail(&epi->rdllink, &ep->rdllist);
708 * Wake up ( if active ) both the eventpoll wait list and the ->poll()
711 if (waitqueue_active(&ep->wq))
712 __wake_up_locked(&ep->wq, TASK_UNINTERRUPTIBLE |
714 if (waitqueue_active(&ep->poll_wait))
718 write_unlock_irqrestore(&ep->lock, flags);
720 /* We have to call this outside the lock */
722 ep_poll_safewake(&psw, &ep->poll_wait);
728 * This is the callback that is used to add our wait queue to the
729 * target file wakeup lists.
731 static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
734 struct epitem *epi = ep_item_from_epqueue(pt);
735 struct eppoll_entry *pwq;
737 if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) {
738 init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
741 add_wait_queue(whead, &pwq->wait);
742 list_add_tail(&pwq->llink, &epi->pwqlist);
745 /* We have to signal that an error occurred */
750 static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)
753 struct rb_node **p = &ep->rbr.rb_node, *parent = NULL;
758 epic = rb_entry(parent, struct epitem, rbn);
759 kcmp = ep_cmp_ffd(&epi->ffd, &epic->ffd);
761 p = &parent->rb_right;
763 p = &parent->rb_left;
765 rb_link_node(&epi->rbn, parent, p);
766 rb_insert_color(&epi->rbn, &ep->rbr);
769 static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
770 struct file *tfile, int fd)
772 int error, revents, pwake = 0;
775 struct ep_pqueue epq;
778 if (!(epi = kmem_cache_alloc(epi_cache, GFP_KERNEL)))
781 /* Item initialization follow here ... */
782 ep_rb_initnode(&epi->rbn);
783 INIT_LIST_HEAD(&epi->rdllink);
784 INIT_LIST_HEAD(&epi->fllink);
785 INIT_LIST_HEAD(&epi->pwqlist);
787 ep_set_ffd(&epi->ffd, tfile, fd);
789 atomic_set(&epi->usecnt, 1);
792 /* Initialize the poll table using the queue callback */
794 init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
797 * Attach the item to the poll hooks and get current event bits.
798 * We can safely use the file* here because its usage count has
799 * been increased by the caller of this function.
801 revents = tfile->f_op->poll(tfile, &epq.pt);
804 * We have to check if something went wrong during the poll wait queue
805 * install process. Namely an allocation for a wait queue failed due
806 * high memory pressure.
809 goto error_unregister;
811 /* Add the current item to the list of active epoll hook for this file */
812 spin_lock(&tfile->f_ep_lock);
813 list_add_tail(&epi->fllink, &tfile->f_ep_links);
814 spin_unlock(&tfile->f_ep_lock);
816 /* We have to drop the new item inside our item list to keep track of it */
817 write_lock_irqsave(&ep->lock, flags);
819 /* Add the current item to the rb-tree */
820 ep_rbtree_insert(ep, epi);
822 /* If the file is already "ready" we drop it inside the ready list */
823 if ((revents & event->events) && !ep_is_linked(&epi->rdllink)) {
824 list_add_tail(&epi->rdllink, &ep->rdllist);
826 /* Notify waiting tasks that events are available */
827 if (waitqueue_active(&ep->wq))
828 __wake_up_locked(&ep->wq, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE);
829 if (waitqueue_active(&ep->poll_wait))
833 write_unlock_irqrestore(&ep->lock, flags);
835 /* We have to call this outside the lock */
837 ep_poll_safewake(&psw, &ep->poll_wait);
839 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_insert(%p, %p, %d)\n",
840 current, ep, tfile, fd));
845 ep_unregister_pollwait(ep, epi);
848 * We need to do this because an event could have been arrived on some
849 * allocated wait queue.
851 write_lock_irqsave(&ep->lock, flags);
852 if (ep_is_linked(&epi->rdllink))
853 list_del_init(&epi->rdllink);
854 write_unlock_irqrestore(&ep->lock, flags);
856 kmem_cache_free(epi_cache, epi);
862 * Modify the interest event mask by dropping an event if the new mask
863 * has a match in the current file status.
865 static int ep_modify(struct eventpoll *ep, struct epitem *epi, struct epoll_event *event)
868 unsigned int revents;
872 * Set the new event interest mask before calling f_op->poll(), otherwise
873 * a potential race might occur. In fact if we do this operation inside
874 * the lock, an event might happen between the f_op->poll() call and the
875 * new event set registering.
877 epi->event.events = event->events;
880 * Get current event bits. We can safely use the file* here because
881 * its usage count has been increased by the caller of this function.
883 revents = epi->ffd.file->f_op->poll(epi->ffd.file, NULL);
885 write_lock_irqsave(&ep->lock, flags);
887 /* Copy the data member from inside the lock */
888 epi->event.data = event->data;
891 * If the item is not linked to the RB tree it means that it's on its
892 * way toward the removal. Do nothing in this case.
894 if (ep_rb_linked(&epi->rbn)) {
896 * If the item is "hot" and it is not registered inside the ready
897 * list, push it inside. If the item is not "hot" and it is currently
898 * registered inside the ready list, unlink it.
900 if (revents & event->events) {
901 if (!ep_is_linked(&epi->rdllink)) {
902 list_add_tail(&epi->rdllink, &ep->rdllist);
904 /* Notify waiting tasks that events are available */
905 if (waitqueue_active(&ep->wq))
906 __wake_up_locked(&ep->wq, TASK_UNINTERRUPTIBLE |
908 if (waitqueue_active(&ep->poll_wait))
914 write_unlock_irqrestore(&ep->lock, flags);
916 /* We have to call this outside the lock */
918 ep_poll_safewake(&psw, &ep->poll_wait);
924 * This function is called without holding the "ep->lock" since the call to
925 * __copy_to_user() might sleep, and also f_op->poll() might reenable the IRQ
926 * because of the way poll() is traditionally implemented in Linux.
928 static int ep_send_events(struct eventpoll *ep, struct list_head *txlist,
929 struct epoll_event __user *events, int maxevents)
931 int eventcnt, error = -EFAULT, pwake = 0;
932 unsigned int revents;
935 struct list_head injlist;
937 INIT_LIST_HEAD(&injlist);
940 * We can loop without lock because this is a task private list.
941 * We just splice'd out the ep->rdllist in ep_collect_ready_items().
942 * Items cannot vanish during the loop because we are holding "sem" in
945 for (eventcnt = 0; !list_empty(txlist) && eventcnt < maxevents;) {
946 epi = list_first_entry(txlist, struct epitem, rdllink);
947 prefetch(epi->rdllink.next);
950 * Get the ready file event set. We can safely use the file
951 * because we are holding the "sem" in read and this will
952 * guarantee that both the file and the item will not vanish.
954 revents = epi->ffd.file->f_op->poll(epi->ffd.file, NULL);
955 revents &= epi->event.events;
958 * Is the event mask intersect the caller-requested one,
959 * deliver the event to userspace. Again, we are holding
960 * "sem" in read, so no operations coming from userspace
961 * can change the item.
964 if (__put_user(revents,
965 &events[eventcnt].events) ||
966 __put_user(epi->event.data,
967 &events[eventcnt].data))
969 if (epi->event.events & EPOLLONESHOT)
970 epi->event.events &= EP_PRIVATE_BITS;
975 * This is tricky. We are holding the "sem" in read, and this
976 * means that the operations that can change the "linked" status
977 * of the epoll item (epi->rbn and epi->rdllink), cannot touch
978 * them. Also, since we are "linked" from a epi->rdllink POV
979 * (the item is linked to our transmission list we just
980 * spliced), the ep_poll_callback() cannot touch us either,
981 * because of the check present in there. Another parallel
982 * epoll_wait() will not get the same result set, since we
983 * spliced the ready list before. Note that list_del() still
984 * shows the item as linked to the test in ep_poll_callback().
986 list_del(&epi->rdllink);
987 if (!(epi->event.events & EPOLLET) &&
988 (revents & epi->event.events))
989 list_add_tail(&epi->rdllink, &injlist);
992 * Be sure the item is totally detached before re-init
993 * the list_head. After INIT_LIST_HEAD() is committed,
994 * the ep_poll_callback() can requeue the item again,
995 * but we don't care since we are already past it.
998 INIT_LIST_HEAD(&epi->rdllink);
1006 * If the re-injection list or the txlist are not empty, re-splice
1007 * them to the ready list and do proper wakeups.
1009 if (!list_empty(&injlist) || !list_empty(txlist)) {
1010 write_lock_irqsave(&ep->lock, flags);
1012 list_splice(txlist, &ep->rdllist);
1013 list_splice(&injlist, &ep->rdllist);
1015 * Wake up ( if active ) both the eventpoll wait list and the ->poll()
1018 if (waitqueue_active(&ep->wq))
1019 __wake_up_locked(&ep->wq, TASK_UNINTERRUPTIBLE |
1020 TASK_INTERRUPTIBLE);
1021 if (waitqueue_active(&ep->poll_wait))
1024 write_unlock_irqrestore(&ep->lock, flags);
1027 /* We have to call this outside the lock */
1029 ep_poll_safewake(&psw, &ep->poll_wait);
1031 return eventcnt == 0 ? error: eventcnt;
1035 * Perform the transfer of events to user space.
1037 static int ep_events_transfer(struct eventpoll *ep,
1038 struct epoll_event __user *events, int maxevents)
1041 unsigned long flags;
1042 struct list_head txlist;
1044 INIT_LIST_HEAD(&txlist);
1047 * We need to lock this because we could be hit by
1048 * eventpoll_release_file() and epoll_ctl(EPOLL_CTL_DEL).
1050 down_read(&ep->sem);
1053 * Steal the ready list, and re-init the original one to the
1056 write_lock_irqsave(&ep->lock, flags);
1057 list_splice(&ep->rdllist, &txlist);
1058 INIT_LIST_HEAD(&ep->rdllist);
1059 write_unlock_irqrestore(&ep->lock, flags);
1061 /* Build result set in userspace */
1062 eventcnt = ep_send_events(ep, &txlist, events, maxevents);
1069 static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
1070 int maxevents, long timeout)
1073 unsigned long flags;
1078 * Calculate the timeout by checking for the "infinite" value ( -1 )
1079 * and the overflow condition. The passed timeout is in milliseconds,
1080 * that why (t * HZ) / 1000.
1082 jtimeout = (timeout < 0 || timeout >= EP_MAX_MSTIMEO) ?
1083 MAX_SCHEDULE_TIMEOUT : (timeout * HZ + 999) / 1000;
1086 write_lock_irqsave(&ep->lock, flags);
1089 if (list_empty(&ep->rdllist)) {
1091 * We don't have any available event to return to the caller.
1092 * We need to sleep here, and we will be wake up by
1093 * ep_poll_callback() when events will become available.
1095 init_waitqueue_entry(&wait, current);
1096 __add_wait_queue(&ep->wq, &wait);
1100 * We don't want to sleep if the ep_poll_callback() sends us
1101 * a wakeup in between. That's why we set the task state
1102 * to TASK_INTERRUPTIBLE before doing the checks.
1104 set_current_state(TASK_INTERRUPTIBLE);
1105 if (!list_empty(&ep->rdllist) || !jtimeout)
1107 if (signal_pending(current)) {
1112 write_unlock_irqrestore(&ep->lock, flags);
1113 jtimeout = schedule_timeout(jtimeout);
1114 write_lock_irqsave(&ep->lock, flags);
1116 __remove_wait_queue(&ep->wq, &wait);
1118 set_current_state(TASK_RUNNING);
1121 /* Is it worth to try to dig for events ? */
1122 eavail = !list_empty(&ep->rdllist);
1124 write_unlock_irqrestore(&ep->lock, flags);
1127 * Try to transfer events to user space. In case we get 0 events and
1128 * there's still timeout left over, we go trying again in search of
1131 if (!res && eavail &&
1132 !(res = ep_events_transfer(ep, events, maxevents)) && jtimeout)
1139 * It opens an eventpoll file descriptor by suggesting a storage of "size"
1140 * file descriptors. The size parameter is just an hint about how to size
1141 * data structures. It won't prevent the user to store more than "size"
1142 * file descriptors inside the epoll interface. It is the kernel part of
1143 * the userspace epoll_create(2).
1145 asmlinkage long sys_epoll_create(int size)
1148 struct eventpoll *ep;
1149 struct inode *inode;
1152 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d)\n",
1156 * Sanity check on the size parameter, and create the internal data
1157 * structure ( "struct eventpoll" ).
1160 if (size <= 0 || (error = ep_alloc(&ep)) != 0)
1164 * Creates all the items needed to setup an eventpoll file. That is,
1165 * a file structure, and inode and a free file descriptor.
1167 error = anon_inode_getfd(&fd, &inode, &file, "[eventpoll]",
1168 &eventpoll_fops, ep);
1172 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d) = %d\n",
1173 current, size, fd));
1181 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d) = %d\n",
1182 current, size, error));
1187 * The following function implements the controller interface for
1188 * the eventpoll file that enables the insertion/removal/change of
1189 * file descriptors inside the interest set. It represents
1190 * the kernel part of the user space epoll_ctl(2).
1192 asmlinkage long sys_epoll_ctl(int epfd, int op, int fd,
1193 struct epoll_event __user *event)
1196 struct file *file, *tfile;
1197 struct eventpoll *ep;
1199 struct epoll_event epds;
1201 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_ctl(%d, %d, %d, %p)\n",
1202 current, epfd, op, fd, event));
1205 if (ep_op_has_event(op) &&
1206 copy_from_user(&epds, event, sizeof(struct epoll_event)))
1209 /* Get the "struct file *" for the eventpoll file */
1215 /* Get the "struct file *" for the target file */
1220 /* The target file descriptor must support poll */
1222 if (!tfile->f_op || !tfile->f_op->poll)
1223 goto error_tgt_fput;
1226 * We have to check that the file structure underneath the file descriptor
1227 * the user passed to us _is_ an eventpoll file. And also we do not permit
1228 * adding an epoll file descriptor inside itself.
1231 if (file == tfile || !is_file_epoll(file))
1232 goto error_tgt_fput;
1235 * At this point it is safe to assume that the "private_data" contains
1236 * our own data structure.
1238 ep = file->private_data;
1240 down_write(&ep->sem);
1242 /* Try to lookup the file inside our RB tree */
1243 epi = ep_find(ep, tfile, fd);
1249 epds.events |= POLLERR | POLLHUP;
1251 error = ep_insert(ep, &epds, tfile, fd);
1257 error = ep_remove(ep, epi);
1263 epds.events |= POLLERR | POLLHUP;
1264 error = ep_modify(ep, epi, &epds);
1270 * The function ep_find() increments the usage count of the structure
1271 * so, if this is not NULL, we need to release it.
1274 ep_release_epitem(epi);
1282 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_ctl(%d, %d, %d, %p) = %d\n",
1283 current, epfd, op, fd, event, error));
1289 * Implement the event wait interface for the eventpoll file. It is the kernel
1290 * part of the user space epoll_wait(2).
1292 asmlinkage long sys_epoll_wait(int epfd, struct epoll_event __user *events,
1293 int maxevents, int timeout)
1297 struct eventpoll *ep;
1299 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_wait(%d, %p, %d, %d)\n",
1300 current, epfd, events, maxevents, timeout));
1302 /* The maximum number of event must be greater than zero */
1303 if (maxevents <= 0 || maxevents > EP_MAX_EVENTS)
1306 /* Verify that the area passed by the user is writeable */
1307 if (!access_ok(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event))) {
1312 /* Get the "struct file *" for the eventpoll file */
1319 * We have to check that the file structure underneath the fd
1320 * the user passed to us _is_ an eventpoll file.
1323 if (!is_file_epoll(file))
1327 * At this point it is safe to assume that the "private_data" contains
1328 * our own data structure.
1330 ep = file->private_data;
1332 /* Time to fish for events ... */
1333 error = ep_poll(ep, events, maxevents, timeout);
1338 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_wait(%d, %p, %d, %d) = %d\n",
1339 current, epfd, events, maxevents, timeout, error));
1344 #ifdef TIF_RESTORE_SIGMASK
1347 * Implement the event wait interface for the eventpoll file. It is the kernel
1348 * part of the user space epoll_pwait(2).
1350 asmlinkage long sys_epoll_pwait(int epfd, struct epoll_event __user *events,
1351 int maxevents, int timeout, const sigset_t __user *sigmask,
1355 sigset_t ksigmask, sigsaved;
1358 * If the caller wants a certain signal mask to be set during the wait,
1362 if (sigsetsize != sizeof(sigset_t))
1364 if (copy_from_user(&ksigmask, sigmask, sizeof(ksigmask)))
1366 sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
1367 sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
1370 error = sys_epoll_wait(epfd, events, maxevents, timeout);
1373 * If we changed the signal mask, we need to restore the original one.
1374 * In case we've got a signal while waiting, we do not restore the
1375 * signal mask yet, and we allow do_signal() to deliver the signal on
1376 * the way back to userspace, before the signal mask is restored.
1379 if (error == -EINTR) {
1380 memcpy(¤t->saved_sigmask, &sigsaved,
1382 set_thread_flag(TIF_RESTORE_SIGMASK);
1384 sigprocmask(SIG_SETMASK, &sigsaved, NULL);
1390 #endif /* #ifdef TIF_RESTORE_SIGMASK */
1392 static int __init eventpoll_init(void)
1394 mutex_init(&epmutex);
1396 /* Initialize the structure used to perform safe poll wait head wake ups */
1397 ep_poll_safewake_init(&psw);
1399 /* Allocates slab cache used to allocate "struct epitem" items */
1400 epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
1401 0, SLAB_HWCACHE_ALIGN|EPI_SLAB_DEBUG|SLAB_PANIC,
1404 /* Allocates slab cache used to allocate "struct eppoll_entry" */
1405 pwq_cache = kmem_cache_create("eventpoll_pwq",
1406 sizeof(struct eppoll_entry), 0,
1407 EPI_SLAB_DEBUG|SLAB_PANIC, NULL, NULL);
1411 fs_initcall(eventpoll_init);