2 * fs/eventpoll.c ( Efficent event polling implementation )
3 * Copyright (C) 2001,...,2003 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/module.h>
15 #include <linux/init.h>
16 #include <linux/kernel.h>
17 #include <linux/sched.h>
19 #include <linux/file.h>
20 #include <linux/signal.h>
21 #include <linux/errno.h>
23 #include <linux/slab.h>
24 #include <linux/poll.h>
25 #include <linux/smp_lock.h>
26 #include <linux/string.h>
27 #include <linux/list.h>
28 #include <linux/hash.h>
29 #include <linux/spinlock.h>
30 #include <linux/syscalls.h>
31 #include <linux/rwsem.h>
32 #include <linux/wait.h>
33 #include <linux/eventpoll.h>
34 #include <linux/mount.h>
35 #include <asm/bitops.h>
36 #include <asm/uaccess.h>
37 #include <asm/system.h>
40 #include <asm/atomic.h>
41 #include <asm/semaphore.h>
46 * There are three level of locking required by epoll :
48 * 1) epsem (semaphore)
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 "epsem" (together with "ep->lock") to have it working,
70 * but having "ep->sem" will make the interface more scalable.
71 * Events that require holding "epsem" are very rare, while for
72 * normal operations the epoll private "ep->sem" will guarantee
73 * a greater scalability.
77 #define EVENTPOLLFS_MAGIC 0x03111965 /* My birthday should work for this :) */
82 #define DPRINTK(x) printk x
83 #define DNPRINTK(n, x) do { if ((n) <= DEBUG_EPOLL) printk x; } while (0)
84 #else /* #if DEBUG_EPOLL > 0 */
85 #define DPRINTK(x) (void) 0
86 #define DNPRINTK(n, x) (void) 0
87 #endif /* #if DEBUG_EPOLL > 0 */
92 #define EPI_SLAB_DEBUG (SLAB_DEBUG_FREE | SLAB_RED_ZONE /* | SLAB_POISON */)
93 #else /* #if DEBUG_EPI != 0 */
94 #define EPI_SLAB_DEBUG 0
95 #endif /* #if DEBUG_EPI != 0 */
97 /* Epoll private bits inside the event mask */
98 #define EP_PRIVATE_BITS (EPOLLONESHOT | EPOLLET)
100 /* Maximum number of poll wake up nests we are allowing */
101 #define EP_MAX_POLLWAKE_NESTS 4
103 /* Maximum size of the hash in bits ( 2^N ) */
104 #define EP_MAX_HASH_BITS 17
106 /* Minimum size of the hash in bits ( 2^N ) */
107 #define EP_MIN_HASH_BITS 9
109 /* Number of hash entries ( "struct list_head" ) inside a page */
110 #define EP_HENTRY_X_PAGE (PAGE_SIZE / sizeof(struct list_head))
112 /* Maximum size of the hash in pages */
113 #define EP_MAX_HPAGES ((1 << EP_MAX_HASH_BITS) / EP_HENTRY_X_PAGE + 1)
115 /* Number of pages allocated for an "hbits" sized hash table */
116 #define EP_HASH_PAGES(hbits) ((int) ((1 << (hbits)) / EP_HENTRY_X_PAGE + \
117 ((1 << (hbits)) % EP_HENTRY_X_PAGE ? 1: 0)))
119 /* Macro to allocate a "struct epitem" from the slab cache */
120 #define EPI_MEM_ALLOC() (struct epitem *) kmem_cache_alloc(epi_cache, SLAB_KERNEL)
122 /* Macro to free a "struct epitem" to the slab cache */
123 #define EPI_MEM_FREE(p) kmem_cache_free(epi_cache, p)
125 /* Macro to allocate a "struct eppoll_entry" from the slab cache */
126 #define PWQ_MEM_ALLOC() (struct eppoll_entry *) kmem_cache_alloc(pwq_cache, SLAB_KERNEL)
128 /* Macro to free a "struct eppoll_entry" to the slab cache */
129 #define PWQ_MEM_FREE(p) kmem_cache_free(pwq_cache, p)
131 /* Fast test to see if the file is an evenpoll file */
132 #define IS_FILE_EPOLL(f) ((f)->f_op == &eventpoll_fops)
135 * Remove the item from the list and perform its initialization.
136 * This is useful for us because we can test if the item is linked
137 * using "EP_IS_LINKED(p)".
139 #define EP_LIST_DEL(p) do { list_del(p); INIT_LIST_HEAD(p); } while (0)
141 /* Tells us if the item is currently linked */
142 #define EP_IS_LINKED(p) (!list_empty(p))
144 /* Get the "struct epitem" from a wait queue pointer */
145 #define EP_ITEM_FROM_WAIT(p) ((struct epitem *) container_of(p, struct eppoll_entry, wait)->base)
147 /* Get the "struct epitem" from an epoll queue wrapper */
148 #define EP_ITEM_FROM_EPQUEUE(p) (container_of(p, struct ep_pqueue, pt)->epi)
151 * Node that is linked into the "wake_task_list" member of the "struct poll_safewake".
152 * It is used to keep track on all tasks that are currently inside the wake_up() code
153 * to 1) short-circuit the one coming from the same task and same wait queue head
154 * ( loop ) 2) allow a maximum number of epoll descriptors inclusion nesting
155 * 3) let go the ones coming from other tasks.
157 struct wake_task_node {
158 struct list_head llink;
160 wait_queue_head_t *wq;
164 * This is used to implement the safe poll wake up avoiding to reenter
165 * the poll callback from inside wake_up().
167 struct poll_safewake {
168 struct list_head wake_task_list;
173 * This structure is stored inside the "private_data" member of the file
174 * structure and rapresent the main data sructure for the eventpoll
178 /* Protect the this structure access */
182 * This semaphore is used to ensure that files are not removed
183 * while epoll is using them. This is read-held during the event
184 * collection loop and it is write-held during the file cleanup
185 * path, the epoll file exit code and the ctl operations.
187 struct rw_semaphore sem;
189 /* Wait queue used by sys_epoll_wait() */
190 wait_queue_head_t wq;
192 /* Wait queue used by file->poll() */
193 wait_queue_head_t poll_wait;
195 /* List of ready file descriptors */
196 struct list_head rdllist;
198 /* Size of the hash */
199 unsigned int hashbits;
201 /* Pages for the "struct epitem" hash */
202 char *hpages[EP_MAX_HPAGES];
205 /* Wait structure used by the poll hooks */
206 struct eppoll_entry {
207 /* List header used to link this structure to the "struct epitem" */
208 struct list_head llink;
210 /* The "base" pointer is set to the container "struct epitem" */
214 * Wait queue item that will be linked to the target file wait
219 /* The wait queue head that linked the "wait" wait queue item */
220 wait_queue_head_t *whead;
224 * Each file descriptor added to the eventpoll interface will
225 * have an entry of this type linked to the hash.
228 /* List header used to link this structure to the eventpoll hash */
229 struct list_head llink;
231 /* List header used to link this structure to the eventpoll ready list */
232 struct list_head rdllink;
234 /* The file descriptor this item refers to */
237 /* Number of active wait queue attached to poll operations */
240 /* List containing poll wait queues */
241 struct list_head pwqlist;
243 /* The "container" of this item */
244 struct eventpoll *ep;
246 /* The file this item refers to */
249 /* The structure that describe the interested events and the source fd */
250 struct epoll_event event;
253 * Used to keep track of the usage count of the structure. This avoids
254 * that the structure will desappear from underneath our processing.
258 /* List header used to link this item to the "struct file" items list */
259 struct list_head fllink;
261 /* List header used to link the item to the transfer list */
262 struct list_head txlink;
265 * This is used during the collection/transfer of events to userspace
266 * to pin items empty events set.
268 unsigned int revents;
271 /* Wrapper struct used by poll queueing */
279 static void ep_poll_safewake_init(struct poll_safewake *psw);
280 static void ep_poll_safewake(struct poll_safewake *psw, wait_queue_head_t *wq);
281 static unsigned int ep_get_hash_bits(unsigned int hintsize);
282 static int ep_getfd(int *efd, struct inode **einode, struct file **efile);
283 static int ep_alloc_pages(char **pages, int numpages);
284 static int ep_free_pages(char **pages, int numpages);
285 static int ep_file_init(struct file *file, unsigned int hashbits);
286 static unsigned int ep_hash_index(struct eventpoll *ep, struct file *file,
288 static struct list_head *ep_hash_entry(struct eventpoll *ep,
290 static int ep_init(struct eventpoll *ep, unsigned int hashbits);
291 static void ep_free(struct eventpoll *ep);
292 static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd);
293 static void ep_use_epitem(struct epitem *epi);
294 static void ep_release_epitem(struct epitem *epi);
295 static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
297 static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
298 struct file *tfile, int fd);
299 static int ep_modify(struct eventpoll *ep, struct epitem *epi,
300 struct epoll_event *event);
301 static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi);
302 static int ep_unlink(struct eventpoll *ep, struct epitem *epi);
303 static int ep_remove(struct eventpoll *ep, struct epitem *epi);
304 static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *key);
305 static int ep_eventpoll_close(struct inode *inode, struct file *file);
306 static unsigned int ep_eventpoll_poll(struct file *file, poll_table *wait);
307 static int ep_collect_ready_items(struct eventpoll *ep,
308 struct list_head *txlist, int maxevents);
309 static int ep_send_events(struct eventpoll *ep, struct list_head *txlist,
310 struct epoll_event __user *events);
311 static void ep_reinject_items(struct eventpoll *ep, struct list_head *txlist);
312 static int ep_events_transfer(struct eventpoll *ep,
313 struct epoll_event __user *events,
315 static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
316 int maxevents, long timeout);
317 static int eventpollfs_delete_dentry(struct dentry *dentry);
318 static struct inode *ep_eventpoll_inode(void);
319 static struct super_block *eventpollfs_get_sb(struct file_system_type *fs_type,
320 int flags, const char *dev_name,
324 * This semaphore is used to serialize ep_free() and eventpoll_release_file().
326 struct semaphore epsem;
328 /* Safe wake up implementation */
329 static struct poll_safewake psw;
331 /* Slab cache used to allocate "struct epitem" */
332 static kmem_cache_t *epi_cache;
334 /* Slab cache used to allocate "struct eppoll_entry" */
335 static kmem_cache_t *pwq_cache;
337 /* Virtual fs used to allocate inodes for eventpoll files */
338 static struct vfsmount *eventpoll_mnt;
340 /* File callbacks that implement the eventpoll file behaviour */
341 static struct file_operations eventpoll_fops = {
342 .release = ep_eventpoll_close,
343 .poll = ep_eventpoll_poll
347 * This is used to register the virtual file system from where
348 * eventpoll inodes are allocated.
350 static struct file_system_type eventpoll_fs_type = {
351 .name = "eventpollfs",
352 .get_sb = eventpollfs_get_sb,
353 .kill_sb = kill_anon_super,
356 /* Very basic directory entry operations for the eventpoll virtual file system */
357 static struct dentry_operations eventpollfs_dentry_operations = {
358 .d_delete = eventpollfs_delete_dentry,
363 /* Initialize the poll safe wake up structure */
364 static void ep_poll_safewake_init(struct poll_safewake *psw)
367 INIT_LIST_HEAD(&psw->wake_task_list);
368 spin_lock_init(&psw->lock);
373 * Perform a safe wake up of the poll wait list. The problem is that
374 * with the new callback'd wake up system, it is possible that the
375 * poll callback is reentered from inside the call to wake_up() done
376 * on the poll wait queue head. The rule is that we cannot reenter the
377 * wake up code from the same task more than EP_MAX_POLLWAKE_NESTS times,
378 * and we cannot reenter the same wait queue head at all. This will
379 * enable to have a hierarchy of epoll file descriptor of no more than
380 * EP_MAX_POLLWAKE_NESTS deep. We need the irq version of the spin lock
381 * because this one gets called by the poll callback, that in turn is called
382 * from inside a wake_up(), that might be called from irq context.
384 static void ep_poll_safewake(struct poll_safewake *psw, wait_queue_head_t *wq)
388 task_t *this_task = current;
389 struct list_head *lsthead = &psw->wake_task_list, *lnk;
390 struct wake_task_node *tncur;
391 struct wake_task_node tnode;
393 spin_lock_irqsave(&psw->lock, flags);
395 /* Try to see if the current task is already inside this wakeup call */
396 list_for_each(lnk, lsthead) {
397 tncur = list_entry(lnk, struct wake_task_node, llink);
399 if (tncur->wq == wq ||
400 (tncur->task == this_task && ++wake_nests > EP_MAX_POLLWAKE_NESTS)) {
402 * Ops ... loop detected or maximum nest level reached.
403 * We abort this wake by breaking the cycle itself.
405 spin_unlock_irqrestore(&psw->lock, flags);
410 /* Add the current task to the list */
411 tnode.task = this_task;
413 list_add(&tnode.llink, lsthead);
415 spin_unlock_irqrestore(&psw->lock, flags);
417 /* Do really wake up now */
420 /* Remove the current task from the list */
421 spin_lock_irqsave(&psw->lock, flags);
422 list_del(&tnode.llink);
423 spin_unlock_irqrestore(&psw->lock, flags);
428 * Calculate the size of the hash in bits. The returned size will be
429 * bounded between EP_MIN_HASH_BITS and EP_MAX_HASH_BITS.
431 static unsigned int ep_get_hash_bits(unsigned int hintsize)
435 for (i = 0, val = 1; val < hintsize && i < EP_MAX_HASH_BITS; i++, val <<= 1);
436 return i < EP_MIN_HASH_BITS ? EP_MIN_HASH_BITS: i;
440 /* Used to initialize the epoll bits inside the "struct file" */
441 void eventpoll_init_file(struct file *file)
444 INIT_LIST_HEAD(&file->f_ep_links);
445 spin_lock_init(&file->f_ep_lock);
450 * This is called from eventpoll_release() to unlink files from the eventpoll
451 * interface. We need to have this facility to cleanup correctly files that are
452 * closed without being removed from the eventpoll interface.
454 void eventpoll_release_file(struct file *file)
456 struct list_head *lsthead = &file->f_ep_links;
457 struct eventpoll *ep;
461 * We don't want to get "file->f_ep_lock" because it is not
462 * necessary. It is not necessary because we're in the "struct file"
463 * cleanup path, and this means that noone is using this file anymore.
464 * The only hit might come from ep_free() but by holding the semaphore
465 * will correctly serialize the operation. We do need to acquire
466 * "ep->sem" after "epsem" because ep_remove() requires it when called
467 * from anywhere but ep_free().
471 while (!list_empty(lsthead)) {
472 epi = list_entry(lsthead->next, struct epitem, fllink);
475 EP_LIST_DEL(&epi->fllink);
476 down_write(&ep->sem);
486 * It opens an eventpoll file descriptor by suggesting a storage of "size"
487 * file descriptors. The size parameter is just an hint about how to size
488 * data structures. It won't prevent the user to store more than "size"
489 * file descriptors inside the epoll interface. It is the kernel part of
490 * the userspace epoll_create(2).
492 asmlinkage long sys_epoll_create(int size)
495 unsigned int hashbits;
499 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d)\n",
502 /* Sanity check on the size parameter */
507 /* Correctly size the hash */
508 hashbits = ep_get_hash_bits((unsigned int) size);
511 * Creates all the items needed to setup an eventpoll file. That is,
512 * a file structure, and inode and a free file descriptor.
514 error = ep_getfd(&fd, &inode, &file);
518 /* Setup the file internal data structure ( "struct eventpoll" ) */
519 error = ep_file_init(file, hashbits);
524 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d) = %d\n",
532 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d) = %d\n",
533 current, size, error));
539 * The following function implements the controller interface for
540 * the eventpoll file that enables the insertion/removal/change of
541 * file descriptors inside the interest set. It represents
542 * the kernel part of the user space epoll_ctl(2).
545 sys_epoll_ctl(int epfd, int op, int fd, struct epoll_event __user *event)
548 struct file *file, *tfile;
549 struct eventpoll *ep;
551 struct epoll_event epds;
553 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_ctl(%d, %d, %d, %p)\n",
554 current, epfd, op, fd, event));
557 if (copy_from_user(&epds, event, sizeof(struct epoll_event)))
560 /* Get the "struct file *" for the eventpoll file */
566 /* Get the "struct file *" for the target file */
571 /* The target file descriptor must support poll */
573 if (!tfile->f_op || !tfile->f_op->poll)
577 * We have to check that the file structure underneath the file descriptor
578 * the user passed to us _is_ an eventpoll file. And also we do not permit
579 * adding an epoll file descriptor inside itself.
582 if (file == tfile || !IS_FILE_EPOLL(file))
586 * At this point it is safe to assume that the "private_data" contains
587 * our own data structure.
589 ep = file->private_data;
591 down_write(&ep->sem);
593 /* Try to lookup the file inside our hash table */
594 epi = ep_find(ep, tfile, fd);
600 epds.events |= POLLERR | POLLHUP;
602 error = ep_insert(ep, &epds, tfile, fd);
608 error = ep_remove(ep, epi);
614 epds.events |= POLLERR | POLLHUP;
615 error = ep_modify(ep, epi, &epds);
622 * The function ep_find() increments the usage count of the structure
623 * so, if this is not NULL, we need to release it.
626 ep_release_epitem(epi);
635 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_ctl(%d, %d, %d, %p) = %d\n",
636 current, epfd, op, fd, event, error));
643 * Implement the event wait interface for the eventpoll file. It is the kernel
644 * part of the user space epoll_wait(2).
646 asmlinkage long sys_epoll_wait(int epfd, struct epoll_event __user *events,
647 int maxevents, int timeout)
651 struct eventpoll *ep;
653 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_wait(%d, %p, %d, %d)\n",
654 current, epfd, events, maxevents, timeout));
656 /* The maximum number of event must be greater than zero */
660 /* Verify that the area passed by the user is writeable */
661 if ((error = verify_area(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event))))
664 /* Get the "struct file *" for the eventpoll file */
671 * We have to check that the file structure underneath the fd
672 * the user passed to us _is_ an eventpoll file.
675 if (!IS_FILE_EPOLL(file))
679 * At this point it is safe to assume that the "private_data" contains
680 * our own data structure.
682 ep = file->private_data;
684 /* Time to fish for events ... */
685 error = ep_poll(ep, events, maxevents, timeout);
690 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_wait(%d, %p, %d, %d) = %d\n",
691 current, epfd, events, maxevents, timeout, error));
698 * Creates the file descriptor to be used by the epoll interface.
700 static int ep_getfd(int *efd, struct inode **einode, struct file **efile)
704 struct dentry *dentry;
709 /* Get an ready to use file */
711 file = get_empty_filp();
715 /* Allocates an inode from the eventpoll file system */
716 inode = ep_eventpoll_inode();
717 error = PTR_ERR(inode);
721 /* Allocates a free descriptor to plug the file onto */
722 error = get_unused_fd();
728 * Link the inode to a directory entry by creating a unique name
729 * using the inode number.
732 sprintf(name, "[%lu]", inode->i_ino);
734 this.len = strlen(name);
735 this.hash = inode->i_ino;
736 dentry = d_alloc(eventpoll_mnt->mnt_sb->s_root, &this);
739 dentry->d_op = &eventpollfs_dentry_operations;
740 d_add(dentry, inode);
741 file->f_vfsmnt = mntget(eventpoll_mnt);
742 file->f_dentry = dget(dentry);
743 file->f_mapping = inode->i_mapping;
746 file->f_flags = O_RDONLY;
747 file->f_op = &eventpoll_fops;
748 file->f_mode = FMODE_READ;
750 file->private_data = NULL;
752 /* Install the new setup file into the allocated fd. */
753 fd_install(fd, file);
771 static int ep_alloc_pages(char **pages, int numpages)
775 for (i = 0; i < numpages; i++) {
776 pages[i] = (char *) __get_free_pages(GFP_KERNEL, 0);
778 for (--i; i >= 0; i--) {
779 ClearPageReserved(virt_to_page(pages[i]));
780 free_pages((unsigned long) pages[i], 0);
784 SetPageReserved(virt_to_page(pages[i]));
790 static int ep_free_pages(char **pages, int numpages)
794 for (i = 0; i < numpages; i++) {
795 ClearPageReserved(virt_to_page(pages[i]));
796 free_pages((unsigned long) pages[i], 0);
802 static int ep_file_init(struct file *file, unsigned int hashbits)
805 struct eventpoll *ep;
807 if (!(ep = kmalloc(sizeof(struct eventpoll), GFP_KERNEL)))
810 memset(ep, 0, sizeof(*ep));
812 error = ep_init(ep, hashbits);
818 file->private_data = ep;
820 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_file_init() ep=%p\n",
827 * Calculate the index of the hash relative to "file".
829 static unsigned int ep_hash_index(struct eventpoll *ep, struct file *file, int fd)
831 unsigned long ptr = (unsigned long) file ^ (fd << ep->hashbits);
833 return (unsigned int) hash_ptr((void *) ptr, ep->hashbits);
838 * Returns the hash entry ( struct list_head * ) of the passed index.
840 static struct list_head *ep_hash_entry(struct eventpoll *ep, unsigned int index)
843 return (struct list_head *) (ep->hpages[index / EP_HENTRY_X_PAGE] +
844 (index % EP_HENTRY_X_PAGE) * sizeof(struct list_head));
848 static int ep_init(struct eventpoll *ep, unsigned int hashbits)
851 unsigned int i, hsize;
853 rwlock_init(&ep->lock);
854 init_rwsem(&ep->sem);
855 init_waitqueue_head(&ep->wq);
856 init_waitqueue_head(&ep->poll_wait);
857 INIT_LIST_HEAD(&ep->rdllist);
859 /* Hash allocation and setup */
860 ep->hashbits = hashbits;
861 error = ep_alloc_pages(ep->hpages, EP_HASH_PAGES(ep->hashbits));
865 /* Initialize hash buckets */
866 for (i = 0, hsize = 1 << hashbits; i < hsize; i++)
867 INIT_LIST_HEAD(ep_hash_entry(ep, i));
875 static void ep_free(struct eventpoll *ep)
877 unsigned int i, hsize;
878 struct list_head *lsthead, *lnk;
881 /* We need to release all tasks waiting for these file */
882 if (waitqueue_active(&ep->poll_wait))
883 ep_poll_safewake(&psw, &ep->poll_wait);
886 * We need to lock this because we could be hit by
887 * eventpoll_release_file() while we're freeing the "struct eventpoll".
888 * We do not need to hold "ep->sem" here because the epoll file
889 * is on the way to be removed and no one has references to it
890 * anymore. The only hit might come from eventpoll_release_file() but
891 * holding "epsem" is sufficent here.
896 * Walks through the whole hash by unregistering poll callbacks.
898 for (i = 0, hsize = 1 << ep->hashbits; i < hsize; i++) {
899 lsthead = ep_hash_entry(ep, i);
901 list_for_each(lnk, lsthead) {
902 epi = list_entry(lnk, struct epitem, llink);
904 ep_unregister_pollwait(ep, epi);
909 * Walks through the whole hash by freeing each "struct epitem". At this
910 * point we are sure no poll callbacks will be lingering around, and also by
911 * write-holding "sem" we can be sure that no file cleanup code will hit
912 * us during this operation. So we can avoid the lock on "ep->lock".
914 for (i = 0, hsize = 1 << ep->hashbits; i < hsize; i++) {
915 lsthead = ep_hash_entry(ep, i);
917 while (!list_empty(lsthead)) {
918 epi = list_entry(lsthead->next, struct epitem, llink);
926 /* Free hash pages */
927 ep_free_pages(ep->hpages, EP_HASH_PAGES(ep->hashbits));
932 * Search the file inside the eventpoll hash. It add usage count to
933 * the returned item, so the caller must call ep_release_epitem()
934 * after finished using the "struct epitem".
936 static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
939 struct list_head *lsthead, *lnk;
940 struct epitem *epi = NULL;
942 read_lock_irqsave(&ep->lock, flags);
944 lsthead = ep_hash_entry(ep, ep_hash_index(ep, file, fd));
945 list_for_each(lnk, lsthead) {
946 epi = list_entry(lnk, struct epitem, llink);
948 if (epi->file == file && epi->fd == fd) {
955 read_unlock_irqrestore(&ep->lock, flags);
957 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_find(%p) -> %p\n",
958 current, file, epi));
965 * Increment the usage count of the "struct epitem" making it sure
966 * that the user will have a valid pointer to reference.
968 static void ep_use_epitem(struct epitem *epi)
971 atomic_inc(&epi->usecnt);
976 * Decrement ( release ) the usage count by signaling that the user
977 * has finished using the structure. It might lead to freeing the
978 * structure itself if the count goes to zero.
980 static void ep_release_epitem(struct epitem *epi)
983 if (atomic_dec_and_test(&epi->usecnt))
989 * This is the callback that is used to add our wait queue to the
990 * target file wakeup lists.
992 static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
995 struct epitem *epi = EP_ITEM_FROM_EPQUEUE(pt);
996 struct eppoll_entry *pwq;
998 if (epi->nwait >= 0 && (pwq = PWQ_MEM_ALLOC())) {
999 init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
1002 add_wait_queue(whead, &pwq->wait);
1003 list_add_tail(&pwq->llink, &epi->pwqlist);
1006 /* We have to signal that an error occurred */
1012 static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
1013 struct file *tfile, int fd)
1015 int error, revents, pwake = 0;
1016 unsigned long flags;
1018 struct ep_pqueue epq;
1021 if (!(epi = EPI_MEM_ALLOC()))
1024 /* Item initialization follow here ... */
1025 INIT_LIST_HEAD(&epi->llink);
1026 INIT_LIST_HEAD(&epi->rdllink);
1027 INIT_LIST_HEAD(&epi->fllink);
1028 INIT_LIST_HEAD(&epi->txlink);
1029 INIT_LIST_HEAD(&epi->pwqlist);
1033 epi->event = *event;
1034 atomic_set(&epi->usecnt, 1);
1037 /* Initialize the poll table using the queue callback */
1039 init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
1042 * Attach the item to the poll hooks and get current event bits.
1043 * We can safely use the file* here because its usage count has
1044 * been increased by the caller of this function.
1046 revents = tfile->f_op->poll(tfile, &epq.pt);
1049 * We have to check if something went wrong during the poll wait queue
1050 * install process. Namely an allocation for a wait queue failed due
1051 * high memory pressure.
1056 /* Add the current item to the list of active epoll hook for this file */
1057 spin_lock(&tfile->f_ep_lock);
1058 list_add_tail(&epi->fllink, &tfile->f_ep_links);
1059 spin_unlock(&tfile->f_ep_lock);
1061 /* We have to drop the new item inside our item list to keep track of it */
1062 write_lock_irqsave(&ep->lock, flags);
1064 /* Add the current item to the hash table */
1065 list_add(&epi->llink, ep_hash_entry(ep, ep_hash_index(ep, tfile, fd)));
1067 /* If the file is already "ready" we drop it inside the ready list */
1068 if ((revents & event->events) && !EP_IS_LINKED(&epi->rdllink)) {
1069 list_add_tail(&epi->rdllink, &ep->rdllist);
1071 /* Notify waiting tasks that events are available */
1072 if (waitqueue_active(&ep->wq))
1074 if (waitqueue_active(&ep->poll_wait))
1078 write_unlock_irqrestore(&ep->lock, flags);
1080 /* We have to call this outside the lock */
1082 ep_poll_safewake(&psw, &ep->poll_wait);
1084 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_insert(%p, %p, %d)\n",
1085 current, ep, tfile, fd));
1090 ep_unregister_pollwait(ep, epi);
1093 * We need to do this because an event could have been arrived on some
1094 * allocated wait queue.
1096 write_lock_irqsave(&ep->lock, flags);
1097 if (EP_IS_LINKED(&epi->rdllink))
1098 EP_LIST_DEL(&epi->rdllink);
1099 write_unlock_irqrestore(&ep->lock, flags);
1108 * Modify the interest event mask by dropping an event if the new mask
1109 * has a match in the current file status.
1111 static int ep_modify(struct eventpoll *ep, struct epitem *epi, struct epoll_event *event)
1114 unsigned int revents;
1115 unsigned long flags;
1118 * Set the new event interest mask before calling f_op->poll(), otherwise
1119 * a potential race might occur. In fact if we do this operation inside
1120 * the lock, an event might happen between the f_op->poll() call and the
1121 * new event set registering.
1123 epi->event.events = event->events;
1126 * Get current event bits. We can safely use the file* here because
1127 * its usage count has been increased by the caller of this function.
1129 revents = epi->file->f_op->poll(epi->file, NULL);
1131 write_lock_irqsave(&ep->lock, flags);
1133 /* Copy the data member from inside the lock */
1134 epi->event.data = event->data;
1137 * If the item is not linked to the hash it means that it's on its
1138 * way toward the removal. Do nothing in this case.
1140 if (EP_IS_LINKED(&epi->llink)) {
1142 * If the item is "hot" and it is not registered inside the ready
1143 * list, push it inside. If the item is not "hot" and it is currently
1144 * registered inside the ready list, unlink it.
1146 if (revents & event->events) {
1147 if (!EP_IS_LINKED(&epi->rdllink)) {
1148 list_add_tail(&epi->rdllink, &ep->rdllist);
1150 /* Notify waiting tasks that events are available */
1151 if (waitqueue_active(&ep->wq))
1153 if (waitqueue_active(&ep->poll_wait))
1159 write_unlock_irqrestore(&ep->lock, flags);
1161 /* We have to call this outside the lock */
1163 ep_poll_safewake(&psw, &ep->poll_wait);
1170 * This function unregister poll callbacks from the associated file descriptor.
1171 * Since this must be called without holding "ep->lock" the atomic exchange trick
1172 * will protect us from multiple unregister.
1174 static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi)
1177 struct list_head *lsthead = &epi->pwqlist;
1178 struct eppoll_entry *pwq;
1180 /* This is called without locks, so we need the atomic exchange */
1181 nwait = xchg(&epi->nwait, 0);
1184 while (!list_empty(lsthead)) {
1185 pwq = list_entry(lsthead->next, struct eppoll_entry, llink);
1187 EP_LIST_DEL(&pwq->llink);
1188 remove_wait_queue(pwq->whead, &pwq->wait);
1196 * Unlink the "struct epitem" from all places it might have been hooked up.
1197 * This function must be called with write IRQ lock on "ep->lock".
1199 static int ep_unlink(struct eventpoll *ep, struct epitem *epi)
1204 * It can happen that this one is called for an item already unlinked.
1205 * The check protect us from doing a double unlink ( crash ).
1208 if (!EP_IS_LINKED(&epi->llink))
1212 * Clear the event mask for the unlinked item. This will avoid item
1213 * notifications to be sent after the unlink operation from inside
1214 * the kernel->userspace event transfer loop.
1216 epi->event.events = 0;
1219 * At this point is safe to do the job, unlink the item from our list.
1220 * This operation togheter with the above check closes the door to
1223 EP_LIST_DEL(&epi->llink);
1226 * If the item we are going to remove is inside the ready file descriptors
1227 * we want to remove it from this list to avoid stale events.
1229 if (EP_IS_LINKED(&epi->rdllink))
1230 EP_LIST_DEL(&epi->rdllink);
1235 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_unlink(%p, %p) = %d\n",
1236 current, ep, epi->file, error));
1243 * Removes a "struct epitem" from the eventpoll hash and deallocates
1244 * all the associated resources.
1246 static int ep_remove(struct eventpoll *ep, struct epitem *epi)
1249 unsigned long flags;
1250 struct file *file = epi->file;
1253 * Removes poll wait queue hooks. We _have_ to do this without holding
1254 * the "ep->lock" otherwise a deadlock might occur. This because of the
1255 * sequence of the lock acquisition. Here we do "ep->lock" then the wait
1256 * queue head lock when unregistering the wait queue. The wakeup callback
1257 * will run by holding the wait queue head lock and will call our callback
1258 * that will try to get "ep->lock".
1260 ep_unregister_pollwait(ep, epi);
1262 /* Remove the current item from the list of epoll hooks */
1263 spin_lock(&file->f_ep_lock);
1264 if (EP_IS_LINKED(&epi->fllink))
1265 EP_LIST_DEL(&epi->fllink);
1266 spin_unlock(&file->f_ep_lock);
1268 /* We need to acquire the write IRQ lock before calling ep_unlink() */
1269 write_lock_irqsave(&ep->lock, flags);
1271 /* Really unlink the item from the hash */
1272 error = ep_unlink(ep, epi);
1274 write_unlock_irqrestore(&ep->lock, flags);
1279 /* At this point it is safe to free the eventpoll item */
1280 ep_release_epitem(epi);
1284 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_remove(%p, %p) = %d\n",
1285 current, ep, file, error));
1292 * This is the callback that is passed to the wait queue wakeup
1293 * machanism. It is called by the stored file descriptors when they
1294 * have events to report.
1296 static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *key)
1299 unsigned long flags;
1300 struct epitem *epi = EP_ITEM_FROM_WAIT(wait);
1301 struct eventpoll *ep = epi->ep;
1303 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: poll_callback(%p) epi=%p ep=%p\n",
1304 current, epi->file, epi, ep));
1306 write_lock_irqsave(&ep->lock, flags);
1309 * If the event mask does not contain any poll(2) event, we consider the
1310 * descriptor to be disabled. This condition is likely the effect of the
1311 * EPOLLONESHOT bit that disables the descriptor when an event is received,
1312 * until the next EPOLL_CTL_MOD will be issued.
1314 if (!(epi->event.events & ~EP_PRIVATE_BITS))
1317 /* If this file is already in the ready list we exit soon */
1318 if (EP_IS_LINKED(&epi->rdllink))
1321 list_add_tail(&epi->rdllink, &ep->rdllist);
1325 * Wake up ( if active ) both the eventpoll wait list and the ->poll()
1328 if (waitqueue_active(&ep->wq))
1330 if (waitqueue_active(&ep->poll_wait))
1334 write_unlock_irqrestore(&ep->lock, flags);
1336 /* We have to call this outside the lock */
1338 ep_poll_safewake(&psw, &ep->poll_wait);
1344 static int ep_eventpoll_close(struct inode *inode, struct file *file)
1346 struct eventpoll *ep = file->private_data;
1353 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: close() ep=%p\n", current, ep));
1358 static unsigned int ep_eventpoll_poll(struct file *file, poll_table *wait)
1360 unsigned int pollflags = 0;
1361 unsigned long flags;
1362 struct eventpoll *ep = file->private_data;
1364 /* Insert inside our poll wait queue */
1365 poll_wait(file, &ep->poll_wait, wait);
1367 /* Check our condition */
1368 read_lock_irqsave(&ep->lock, flags);
1369 if (!list_empty(&ep->rdllist))
1370 pollflags = POLLIN | POLLRDNORM;
1371 read_unlock_irqrestore(&ep->lock, flags);
1378 * Since we have to release the lock during the __copy_to_user() operation and
1379 * during the f_op->poll() call, we try to collect the maximum number of items
1380 * by reducing the irqlock/irqunlock switching rate.
1382 static int ep_collect_ready_items(struct eventpoll *ep, struct list_head *txlist, int maxevents)
1385 unsigned long flags;
1386 struct list_head *lsthead = &ep->rdllist, *lnk;
1389 write_lock_irqsave(&ep->lock, flags);
1391 for (nepi = 0, lnk = lsthead->next; lnk != lsthead && nepi < maxevents;) {
1392 epi = list_entry(lnk, struct epitem, rdllink);
1396 /* If this file is already in the ready list we exit soon */
1397 if (!EP_IS_LINKED(&epi->txlink)) {
1399 * This is initialized in this way so that the default
1400 * behaviour of the reinjecting code will be to push back
1401 * the item inside the ready list.
1403 epi->revents = epi->event.events;
1405 /* Link the ready item into the transfer list */
1406 list_add(&epi->txlink, txlist);
1410 * Unlink the item from the ready list.
1412 EP_LIST_DEL(&epi->rdllink);
1416 write_unlock_irqrestore(&ep->lock, flags);
1423 * This function is called without holding the "ep->lock" since the call to
1424 * __copy_to_user() might sleep, and also f_op->poll() might reenable the IRQ
1425 * because of the way poll() is traditionally implemented in Linux.
1427 static int ep_send_events(struct eventpoll *ep, struct list_head *txlist,
1428 struct epoll_event __user *events)
1431 unsigned int revents;
1432 struct list_head *lnk;
1436 * We can loop without lock because this is a task private list.
1437 * The test done during the collection loop will guarantee us that
1438 * another task will not try to collect this file. Also, items
1439 * cannot vanish during the loop because we are holding "sem".
1441 list_for_each(lnk, txlist) {
1442 epi = list_entry(lnk, struct epitem, txlink);
1445 * Get the ready file event set. We can safely use the file
1446 * because we are holding the "sem" in read and this will
1447 * guarantee that both the file and the item will not vanish.
1449 revents = epi->file->f_op->poll(epi->file, NULL);
1452 * Set the return event set for the current file descriptor.
1453 * Note that only the task task was successfully able to link
1454 * the item to its "txlist" will write this field.
1456 epi->revents = revents & epi->event.events;
1459 if (__put_user(epi->revents,
1460 &events[eventcnt].events) ||
1461 __put_user(epi->event.data,
1462 &events[eventcnt].data))
1464 if (epi->event.events & EPOLLONESHOT)
1465 epi->event.events &= EP_PRIVATE_BITS;
1474 * Walk through the transfer list we collected with ep_collect_ready_items()
1475 * and, if 1) the item is still "alive" 2) its event set is not empty 3) it's
1476 * not already linked, links it to the ready list. Same as above, we are holding
1477 * "sem" so items cannot vanish underneath our nose.
1479 static void ep_reinject_items(struct eventpoll *ep, struct list_head *txlist)
1481 int ricnt = 0, pwake = 0;
1482 unsigned long flags;
1485 write_lock_irqsave(&ep->lock, flags);
1487 while (!list_empty(txlist)) {
1488 epi = list_entry(txlist->next, struct epitem, txlink);
1490 /* Unlink the current item from the transfer list */
1491 EP_LIST_DEL(&epi->txlink);
1494 * If the item is no more linked to the interest set, we don't
1495 * have to push it inside the ready list because the following
1496 * ep_release_epitem() is going to drop it. Also, if the current
1497 * item is set to have an Edge Triggered behaviour, we don't have
1498 * to push it back either.
1500 if (EP_IS_LINKED(&epi->llink) && !(epi->event.events & EPOLLET) &&
1501 (epi->revents & epi->event.events) && !EP_IS_LINKED(&epi->rdllink)) {
1502 list_add_tail(&epi->rdllink, &ep->rdllist);
1509 * Wake up ( if active ) both the eventpoll wait list and the ->poll()
1512 if (waitqueue_active(&ep->wq))
1514 if (waitqueue_active(&ep->poll_wait))
1518 write_unlock_irqrestore(&ep->lock, flags);
1520 /* We have to call this outside the lock */
1522 ep_poll_safewake(&psw, &ep->poll_wait);
1527 * Perform the transfer of events to user space.
1529 static int ep_events_transfer(struct eventpoll *ep,
1530 struct epoll_event __user *events, int maxevents)
1533 struct list_head txlist;
1535 INIT_LIST_HEAD(&txlist);
1538 * We need to lock this because we could be hit by
1539 * eventpoll_release_file() and epoll_ctl(EPOLL_CTL_DEL).
1541 down_read(&ep->sem);
1543 /* Collect/extract ready items */
1544 if (ep_collect_ready_items(ep, &txlist, maxevents) > 0) {
1545 /* Build result set in userspace */
1546 eventcnt = ep_send_events(ep, &txlist, events);
1548 /* Reinject ready items into the ready list */
1549 ep_reinject_items(ep, &txlist);
1558 static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
1559 int maxevents, long timeout)
1562 unsigned long flags;
1567 * Calculate the timeout by checking for the "infinite" value ( -1 )
1568 * and the overflow condition. The passed timeout is in milliseconds,
1569 * that why (t * HZ) / 1000.
1571 jtimeout = timeout == -1 || timeout > (MAX_SCHEDULE_TIMEOUT - 1000) / HZ ?
1572 MAX_SCHEDULE_TIMEOUT: (timeout * HZ + 999) / 1000;
1575 write_lock_irqsave(&ep->lock, flags);
1578 if (list_empty(&ep->rdllist)) {
1580 * We don't have any available event to return to the caller.
1581 * We need to sleep here, and we will be wake up by
1582 * ep_poll_callback() when events will become available.
1584 init_waitqueue_entry(&wait, current);
1585 add_wait_queue(&ep->wq, &wait);
1589 * We don't want to sleep if the ep_poll_callback() sends us
1590 * a wakeup in between. That's why we set the task state
1591 * to TASK_INTERRUPTIBLE before doing the checks.
1593 set_current_state(TASK_INTERRUPTIBLE);
1594 if (!list_empty(&ep->rdllist) || !jtimeout)
1596 if (signal_pending(current)) {
1601 write_unlock_irqrestore(&ep->lock, flags);
1602 jtimeout = schedule_timeout(jtimeout);
1603 write_lock_irqsave(&ep->lock, flags);
1605 remove_wait_queue(&ep->wq, &wait);
1607 set_current_state(TASK_RUNNING);
1610 /* Is it worth to try to dig for events ? */
1611 eavail = !list_empty(&ep->rdllist);
1613 write_unlock_irqrestore(&ep->lock, flags);
1616 * Try to transfer events to user space. In case we get 0 events and
1617 * there's still timeout left over, we go trying again in search of
1620 if (!res && eavail &&
1621 !(res = ep_events_transfer(ep, events, maxevents)) && jtimeout)
1628 static int eventpollfs_delete_dentry(struct dentry *dentry)
1635 static struct inode *ep_eventpoll_inode(void)
1637 int error = -ENOMEM;
1638 struct inode *inode = new_inode(eventpoll_mnt->mnt_sb);
1643 inode->i_fop = &eventpoll_fops;
1646 * Mark the inode dirty from the very beginning,
1647 * that way it will never be moved to the dirty
1648 * list because mark_inode_dirty() will think
1649 * that it already _is_ on the dirty list.
1651 inode->i_state = I_DIRTY;
1652 inode->i_mode = S_IRUSR | S_IWUSR;
1653 inode->i_uid = current->fsuid;
1654 inode->i_gid = current->fsgid;
1655 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1656 inode->i_blksize = PAGE_SIZE;
1660 return ERR_PTR(error);
1664 static struct super_block *
1665 eventpollfs_get_sb(struct file_system_type *fs_type, int flags,
1666 const char *dev_name, void *data)
1668 return get_sb_pseudo(fs_type, "eventpoll:", NULL, EVENTPOLLFS_MAGIC);
1672 static int __init eventpoll_init(void)
1678 /* Initialize the structure used to perform safe poll wait head wake ups */
1679 ep_poll_safewake_init(&psw);
1681 /* Allocates slab cache used to allocate "struct epitem" items */
1682 epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
1683 0, SLAB_HWCACHE_ALIGN|EPI_SLAB_DEBUG|SLAB_PANIC,
1686 /* Allocates slab cache used to allocate "struct eppoll_entry" */
1687 pwq_cache = kmem_cache_create("eventpoll_pwq",
1688 sizeof(struct eppoll_entry), 0,
1689 EPI_SLAB_DEBUG|SLAB_PANIC, NULL, NULL);
1692 * Register the virtual file system that will be the source of inodes
1693 * for the eventpoll files
1695 error = register_filesystem(&eventpoll_fs_type);
1699 /* Mount the above commented virtual file system */
1700 eventpoll_mnt = kern_mount(&eventpoll_fs_type);
1701 error = PTR_ERR(eventpoll_mnt);
1702 if (IS_ERR(eventpoll_mnt))
1705 DNPRINTK(3, (KERN_INFO "[%p] eventpoll: successfully initialized.\n",
1710 panic("eventpoll_init() failed\n");
1714 static void __exit eventpoll_exit(void)
1716 /* Undo all operations done inside eventpoll_init() */
1717 unregister_filesystem(&eventpoll_fs_type);
1718 mntput(eventpoll_mnt);
1719 kmem_cache_destroy(pwq_cache);
1720 kmem_cache_destroy(epi_cache);
1723 module_init(eventpoll_init);
1724 module_exit(eventpoll_exit);
1726 MODULE_LICENSE("GPL");