This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / fs / eventpoll.c
1 /*
2  *  fs/eventpoll.c ( Efficent event polling implementation )
3  *  Copyright (C) 2001,...,2003  Davide Libenzi
4  *
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.
9  *
10  *  Davide Libenzi <davidel@xmailserver.org>
11  *
12  */
13
14 #include <linux/module.h>
15 #include <linux/init.h>
16 #include <linux/kernel.h>
17 #include <linux/sched.h>
18 #include <linux/fs.h>
19 #include <linux/file.h>
20 #include <linux/signal.h>
21 #include <linux/errno.h>
22 #include <linux/mm.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>
38 #include <asm/io.h>
39 #include <asm/mman.h>
40 #include <asm/atomic.h>
41 #include <asm/semaphore.h>
42
43
44 /*
45  * LOCKING:
46  * There are three level of locking required by epoll :
47  *
48  * 1) epsem (semaphore)
49  * 2) ep->sem (rw_semaphore)
50  * 3) ep->lock (rw_lock)
51  *
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.
74  */
75
76
77 #define EVENTPOLLFS_MAGIC 0x03111965 /* My birthday should work for this :) */
78
79 #define DEBUG_EPOLL 0
80
81 #if DEBUG_EPOLL > 0
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 */
88
89 #define DEBUG_EPI 0
90
91 #if DEBUG_EPI != 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 */
96
97 /* Epoll private bits inside the event mask */
98 #define EP_PRIVATE_BITS (EPOLLONESHOT | EPOLLET)
99
100 /* Maximum number of poll wake up nests we are allowing */
101 #define EP_MAX_POLLWAKE_NESTS 4
102
103 /* Maximum size of the hash in bits ( 2^N ) */
104 #define EP_MAX_HASH_BITS 17
105
106 /* Minimum size of the hash in bits ( 2^N ) */
107 #define EP_MIN_HASH_BITS 9
108
109 /* Number of hash entries ( "struct list_head" ) inside a page */
110 #define EP_HENTRY_X_PAGE (PAGE_SIZE / sizeof(struct list_head))
111
112 /* Maximum size of the hash in pages */
113 #define EP_MAX_HPAGES ((1 << EP_MAX_HASH_BITS) / EP_HENTRY_X_PAGE + 1)
114
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)))
118
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)
121
122 /* Macro to free a "struct epitem" to the slab cache */
123 #define EPI_MEM_FREE(p) kmem_cache_free(epi_cache, p)
124
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)
127
128 /* Macro to free a "struct eppoll_entry" to the slab cache */
129 #define PWQ_MEM_FREE(p) kmem_cache_free(pwq_cache, p)
130
131 /* Fast test to see if the file is an evenpoll file */
132 #define IS_FILE_EPOLL(f) ((f)->f_op == &eventpoll_fops)
133
134 /*
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)".
138  */
139 #define EP_LIST_DEL(p) do { list_del(p); INIT_LIST_HEAD(p); } while (0)
140
141 /* Tells us if the item is currently linked */
142 #define EP_IS_LINKED(p) (!list_empty(p))
143
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)
146
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)
149
150 /*
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.
156  */
157 struct wake_task_node {
158         struct list_head llink;
159         task_t *task;
160         wait_queue_head_t *wq;
161 };
162
163 /*
164  * This is used to implement the safe poll wake up avoiding to reenter
165  * the poll callback from inside wake_up().
166  */
167 struct poll_safewake {
168         struct list_head wake_task_list;
169         spinlock_t lock;
170 };
171
172 /*
173  * This structure is stored inside the "private_data" member of the file
174  * structure and rapresent the main data sructure for the eventpoll
175  * interface.
176  */
177 struct eventpoll {
178         /* Protect the this structure access */
179         rwlock_t lock;
180
181         /*
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.
186          */
187         struct rw_semaphore sem;
188
189         /* Wait queue used by sys_epoll_wait() */
190         wait_queue_head_t wq;
191
192         /* Wait queue used by file->poll() */
193         wait_queue_head_t poll_wait;
194
195         /* List of ready file descriptors */
196         struct list_head rdllist;
197
198         /* Size of the hash */
199         unsigned int hashbits;
200
201         /* Pages for the "struct epitem" hash */
202         char *hpages[EP_MAX_HPAGES];
203 };
204
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;
209
210         /* The "base" pointer is set to the container "struct epitem" */
211         void *base;
212
213         /*
214          * Wait queue item that will be linked to the target file wait
215          * queue head.
216          */
217         wait_queue_t wait;
218
219         /* The wait queue head that linked the "wait" wait queue item */
220         wait_queue_head_t *whead;
221 };
222
223 /*
224  * Each file descriptor added to the eventpoll interface will
225  * have an entry of this type linked to the hash.
226  */
227 struct epitem {
228         /* List header used to link this structure to the eventpoll hash */
229         struct list_head llink;
230
231         /* List header used to link this structure to the eventpoll ready list */
232         struct list_head rdllink;
233
234         /* The file descriptor this item refers to */
235         int fd;
236
237         /* Number of active wait queue attached to poll operations */
238         int nwait;
239
240         /* List containing poll wait queues */
241         struct list_head pwqlist;
242
243         /* The "container" of this item */
244         struct eventpoll *ep;
245
246         /* The file this item refers to */
247         struct file *file;
248
249         /* The structure that describe the interested events and the source fd */
250         struct epoll_event event;
251
252         /*
253          * Used to keep track of the usage count of the structure. This avoids
254          * that the structure will desappear from underneath our processing.
255          */
256         atomic_t usecnt;
257
258         /* List header used to link this item to the "struct file" items list */
259         struct list_head fllink;
260
261         /* List header used to link the item to the transfer list */
262         struct list_head txlink;
263
264         /*
265          * This is used during the collection/transfer of events to userspace
266          * to pin items empty events set.
267          */
268         unsigned int revents;
269 };
270
271 /* Wrapper struct used by poll queueing */
272 struct ep_pqueue {
273         poll_table pt;
274         struct epitem *epi;
275 };
276
277
278
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,
287                                   int fd);
288 static struct list_head *ep_hash_entry(struct eventpoll *ep,
289                                        unsigned int index);
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,
296                                  poll_table *pt);
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,
314                               int maxevents);
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,
321                                               void *data);
322
323 /*
324  * This semaphore is used to serialize ep_free() and eventpoll_release_file().
325  */
326 struct semaphore epsem;
327
328 /* Safe wake up implementation */
329 static struct poll_safewake psw;
330
331 /* Slab cache used to allocate "struct epitem" */
332 static kmem_cache_t *epi_cache;
333
334 /* Slab cache used to allocate "struct eppoll_entry" */
335 static kmem_cache_t *pwq_cache;
336
337 /* Virtual fs used to allocate inodes for eventpoll files */
338 static struct vfsmount *eventpoll_mnt;
339
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
344 };
345
346 /*
347  * This is used to register the virtual file system from where
348  * eventpoll inodes are allocated.
349  */
350 static struct file_system_type eventpoll_fs_type = {
351         .name           = "eventpollfs",
352         .get_sb         = eventpollfs_get_sb,
353         .kill_sb        = kill_anon_super,
354 };
355
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,
359 };
360
361
362
363 /* Initialize the poll safe wake up structure */
364 static void ep_poll_safewake_init(struct poll_safewake *psw)
365 {
366
367         INIT_LIST_HEAD(&psw->wake_task_list);
368         spin_lock_init(&psw->lock);
369 }
370
371
372 /*
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.
383  */
384 static void ep_poll_safewake(struct poll_safewake *psw, wait_queue_head_t *wq)
385 {
386         int wake_nests = 0;
387         unsigned long flags;
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;
392
393         spin_lock_irqsave(&psw->lock, flags);
394
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);
398
399                 if (tncur->wq == wq ||
400                     (tncur->task == this_task && ++wake_nests > EP_MAX_POLLWAKE_NESTS)) {
401                         /*
402                          * Ops ... loop detected or maximum nest level reached.
403                          * We abort this wake by breaking the cycle itself.
404                          */
405                         spin_unlock_irqrestore(&psw->lock, flags);
406                         return;
407                 }
408         }
409
410         /* Add the current task to the list */
411         tnode.task = this_task;
412         tnode.wq = wq;
413         list_add(&tnode.llink, lsthead);
414
415         spin_unlock_irqrestore(&psw->lock, flags);
416
417         /* Do really wake up now */
418         wake_up(wq);
419
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);
424 }
425
426
427 /*
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.
430  */
431 static unsigned int ep_get_hash_bits(unsigned int hintsize)
432 {
433         unsigned int i, val;
434
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;
437 }
438
439
440 /* Used to initialize the epoll bits inside the "struct file" */
441 void eventpoll_init_file(struct file *file)
442 {
443
444         INIT_LIST_HEAD(&file->f_ep_links);
445         spin_lock_init(&file->f_ep_lock);
446 }
447
448
449 /*
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.
453  */
454 void eventpoll_release_file(struct file *file)
455 {
456         struct list_head *lsthead = &file->f_ep_links;
457         struct eventpoll *ep;
458         struct epitem *epi;
459
460         /*
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().
468          */
469         down(&epsem);
470
471         while (!list_empty(lsthead)) {
472                 epi = list_entry(lsthead->next, struct epitem, fllink);
473
474                 ep = epi->ep;
475                 EP_LIST_DEL(&epi->fllink);
476                 down_write(&ep->sem);
477                 ep_remove(ep, epi);
478                 up_write(&ep->sem);
479         }
480
481         up(&epsem);
482 }
483
484
485 /*
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).
491  */
492 asmlinkage long sys_epoll_create(int size)
493 {
494         int error, fd;
495         unsigned int hashbits;
496         struct inode *inode;
497         struct file *file;
498
499         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d)\n",
500                      current, size));
501
502         /* Correctly size the hash */
503         hashbits = ep_get_hash_bits((unsigned int) size);
504
505         /*
506          * Creates all the items needed to setup an eventpoll file. That is,
507          * a file structure, and inode and a free file descriptor.
508          */
509         error = ep_getfd(&fd, &inode, &file);
510         if (error)
511                 goto eexit_1;
512
513         /* Setup the file internal data structure ( "struct eventpoll" ) */
514         error = ep_file_init(file, hashbits);
515         if (error)
516                 goto eexit_2;
517
518
519         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d) = %d\n",
520                      current, size, fd));
521
522         return fd;
523
524 eexit_2:
525         sys_close(fd);
526 eexit_1:
527         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_create(%d) = %d\n",
528                      current, size, error));
529         return error;
530 }
531
532
533 /*
534  * The following function implements the controller interface for
535  * the eventpoll file that enables the insertion/removal/change of
536  * file descriptors inside the interest set.  It represents
537  * the kernel part of the user space epoll_ctl(2).
538  */
539 asmlinkage long
540 sys_epoll_ctl(int epfd, int op, int fd, struct epoll_event __user *event)
541 {
542         int error;
543         struct file *file, *tfile;
544         struct eventpoll *ep;
545         struct epitem *epi;
546         struct epoll_event epds;
547
548         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_ctl(%d, %d, %d, %p)\n",
549                      current, epfd, op, fd, event));
550
551         error = -EFAULT;
552         if (copy_from_user(&epds, event, sizeof(struct epoll_event)))
553                 goto eexit_1;
554
555         /* Get the "struct file *" for the eventpoll file */
556         error = -EBADF;
557         file = fget(epfd);
558         if (!file)
559                 goto eexit_1;
560
561         /* Get the "struct file *" for the target file */
562         tfile = fget(fd);
563         if (!tfile)
564                 goto eexit_2;
565
566         /* The target file descriptor must support poll */
567         error = -EPERM;
568         if (!tfile->f_op || !tfile->f_op->poll)
569                 goto eexit_3;
570
571         /*
572          * We have to check that the file structure underneath the file descriptor
573          * the user passed to us _is_ an eventpoll file. And also we do not permit
574          * adding an epoll file descriptor inside itself.
575          */
576         error = -EINVAL;
577         if (file == tfile || !IS_FILE_EPOLL(file))
578                 goto eexit_3;
579
580         /*
581          * At this point it is safe to assume that the "private_data" contains
582          * our own data structure.
583          */
584         ep = file->private_data;
585
586         down_write(&ep->sem);
587
588         /* Try to lookup the file inside our hash table */
589         epi = ep_find(ep, tfile, fd);
590
591         error = -EINVAL;
592         switch (op) {
593         case EPOLL_CTL_ADD:
594                 if (!epi) {
595                         epds.events |= POLLERR | POLLHUP;
596
597                         error = ep_insert(ep, &epds, tfile, fd);
598                 } else
599                         error = -EEXIST;
600                 break;
601         case EPOLL_CTL_DEL:
602                 if (epi)
603                         error = ep_remove(ep, epi);
604                 else
605                         error = -ENOENT;
606                 break;
607         case EPOLL_CTL_MOD:
608                 if (epi) {
609                         epds.events |= POLLERR | POLLHUP;
610                         error = ep_modify(ep, epi, &epds);
611                 } else
612                         error = -ENOENT;
613                 break;
614         }
615
616         /*
617          * The function ep_find() increments the usage count of the structure
618          * so, if this is not NULL, we need to release it.
619          */
620         if (epi)
621                 ep_release_epitem(epi);
622
623         up_write(&ep->sem);
624
625 eexit_3:
626         fput(tfile);
627 eexit_2:
628         fput(file);
629 eexit_1:
630         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_ctl(%d, %d, %d, %p) = %d\n",
631                      current, epfd, op, fd, event, error));
632
633         return error;
634 }
635
636
637 /*
638  * Implement the event wait interface for the eventpoll file. It is the kernel
639  * part of the user space epoll_wait(2).
640  */
641 asmlinkage long sys_epoll_wait(int epfd, struct epoll_event __user *events,
642                                int maxevents, int timeout)
643 {
644         int error;
645         struct file *file;
646         struct eventpoll *ep;
647
648         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_wait(%d, %p, %d, %d)\n",
649                      current, epfd, events, maxevents, timeout));
650
651         /* The maximum number of event must be greater than zero */
652         if (maxevents <= 0)
653                 return -EINVAL;
654
655         /* Verify that the area passed by the user is writeable */
656         if ((error = verify_area(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event))))
657                 goto eexit_1;
658
659         /* Get the "struct file *" for the eventpoll file */
660         error = -EBADF;
661         file = fget(epfd);
662         if (!file)
663                 goto eexit_1;
664
665         /*
666          * We have to check that the file structure underneath the fd
667          * the user passed to us _is_ an eventpoll file.
668          */
669         error = -EINVAL;
670         if (!IS_FILE_EPOLL(file))
671                 goto eexit_2;
672
673         /*
674          * At this point it is safe to assume that the "private_data" contains
675          * our own data structure.
676          */
677         ep = file->private_data;
678
679         /* Time to fish for events ... */
680         error = ep_poll(ep, events, maxevents, timeout);
681
682 eexit_2:
683         fput(file);
684 eexit_1:
685         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: sys_epoll_wait(%d, %p, %d, %d) = %d\n",
686                      current, epfd, events, maxevents, timeout, error));
687
688         return error;
689 }
690
691
692 /*
693  * Creates the file descriptor to be used by the epoll interface.
694  */
695 static int ep_getfd(int *efd, struct inode **einode, struct file **efile)
696 {
697         struct qstr this;
698         char name[32];
699         struct dentry *dentry;
700         struct inode *inode;
701         struct file *file;
702         int error, fd;
703
704         /* Get an ready to use file */
705         error = -ENFILE;
706         file = get_empty_filp();
707         if (!file)
708                 goto eexit_1;
709
710         /* Allocates an inode from the eventpoll file system */
711         inode = ep_eventpoll_inode();
712         error = PTR_ERR(inode);
713         if (IS_ERR(inode))
714                 goto eexit_2;
715
716         /* Allocates a free descriptor to plug the file onto */
717         error = get_unused_fd();
718         if (error < 0)
719                 goto eexit_3;
720         fd = error;
721
722         /*
723          * Link the inode to a directory entry by creating a unique name
724          * using the inode number.
725          */
726         error = -ENOMEM;
727         sprintf(name, "[%lu]", inode->i_ino);
728         this.name = name;
729         this.len = strlen(name);
730         this.hash = inode->i_ino;
731         dentry = d_alloc(eventpoll_mnt->mnt_sb->s_root, &this);
732         if (!dentry)
733                 goto eexit_4;
734         dentry->d_op = &eventpollfs_dentry_operations;
735         d_add(dentry, inode);
736         file->f_vfsmnt = mntget(eventpoll_mnt);
737         file->f_dentry = dget(dentry);
738         file->f_mapping = inode->i_mapping;
739
740         file->f_pos = 0;
741         file->f_flags = O_RDONLY;
742         file->f_op = &eventpoll_fops;
743         file->f_mode = FMODE_READ;
744         file->f_version = 0;
745         file->private_data = NULL;
746
747         /* Install the new setup file into the allocated fd. */
748         fd_install(fd, file);
749
750         *efd = fd;
751         *einode = inode;
752         *efile = file;
753         return 0;
754
755 eexit_4:
756         put_unused_fd(fd);
757 eexit_3:
758         iput(inode);
759 eexit_2:
760         put_filp(file);
761 eexit_1:
762         return error;
763 }
764
765
766 static int ep_alloc_pages(char **pages, int numpages)
767 {
768         int i;
769
770         for (i = 0; i < numpages; i++) {
771                 pages[i] = (char *) __get_free_pages(GFP_KERNEL, 0);
772                 if (!pages[i]) {
773                         for (--i; i >= 0; i--) {
774                                 ClearPageReserved(virt_to_page(pages[i]));
775                                 free_pages((unsigned long) pages[i], 0);
776                         }
777                         return -ENOMEM;
778                 }
779                 SetPageReserved(virt_to_page(pages[i]));
780         }
781         return 0;
782 }
783
784
785 static int ep_free_pages(char **pages, int numpages)
786 {
787         int i;
788
789         for (i = 0; i < numpages; i++) {
790                 ClearPageReserved(virt_to_page(pages[i]));
791                 free_pages((unsigned long) pages[i], 0);
792         }
793         return 0;
794 }
795
796
797 static int ep_file_init(struct file *file, unsigned int hashbits)
798 {
799         int error;
800         struct eventpoll *ep;
801
802         if (!(ep = kmalloc(sizeof(struct eventpoll), GFP_KERNEL)))
803                 return -ENOMEM;
804
805         memset(ep, 0, sizeof(*ep));
806
807         error = ep_init(ep, hashbits);
808         if (error) {
809                 kfree(ep);
810                 return error;
811         }
812
813         file->private_data = ep;
814
815         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_file_init() ep=%p\n",
816                      current, ep));
817         return 0;
818 }
819
820
821 /*
822  * Calculate the index of the hash relative to "file".
823  */
824 static unsigned int ep_hash_index(struct eventpoll *ep, struct file *file, int fd)
825 {
826         unsigned long ptr = (unsigned long) file ^ (fd << ep->hashbits);
827
828         return (unsigned int) hash_ptr((void *) ptr, ep->hashbits);
829 }
830
831
832 /*
833  * Returns the hash entry ( struct list_head * ) of the passed index.
834  */
835 static struct list_head *ep_hash_entry(struct eventpoll *ep, unsigned int index)
836 {
837
838         return (struct list_head *) (ep->hpages[index / EP_HENTRY_X_PAGE] +
839                                      (index % EP_HENTRY_X_PAGE) * sizeof(struct list_head));
840 }
841
842
843 static int ep_init(struct eventpoll *ep, unsigned int hashbits)
844 {
845         int error;
846         unsigned int i, hsize;
847
848         rwlock_init(&ep->lock);
849         init_rwsem(&ep->sem);
850         init_waitqueue_head(&ep->wq);
851         init_waitqueue_head(&ep->poll_wait);
852         INIT_LIST_HEAD(&ep->rdllist);
853
854         /* Hash allocation and setup */
855         ep->hashbits = hashbits;
856         error = ep_alloc_pages(ep->hpages, EP_HASH_PAGES(ep->hashbits));
857         if (error)
858                 goto eexit_1;
859
860         /* Initialize hash buckets */
861         for (i = 0, hsize = 1 << hashbits; i < hsize; i++)
862                 INIT_LIST_HEAD(ep_hash_entry(ep, i));
863
864         return 0;
865 eexit_1:
866         return error;
867 }
868
869
870 static void ep_free(struct eventpoll *ep)
871 {
872         unsigned int i, hsize;
873         struct list_head *lsthead, *lnk;
874         struct epitem *epi;
875
876         /* We need to release all tasks waiting for these file */
877         if (waitqueue_active(&ep->poll_wait))
878                 ep_poll_safewake(&psw, &ep->poll_wait);
879
880         /*
881          * We need to lock this because we could be hit by
882          * eventpoll_release_file() while we're freeing the "struct eventpoll".
883          * We do not need to hold "ep->sem" here because the epoll file
884          * is on the way to be removed and no one has references to it
885          * anymore. The only hit might come from eventpoll_release_file() but
886          * holding "epsem" is sufficent here.
887          */
888         down(&epsem);
889
890         /*
891          * Walks through the whole hash by unregistering poll callbacks.
892          */
893         for (i = 0, hsize = 1 << ep->hashbits; i < hsize; i++) {
894                 lsthead = ep_hash_entry(ep, i);
895
896                 list_for_each(lnk, lsthead) {
897                         epi = list_entry(lnk, struct epitem, llink);
898
899                         ep_unregister_pollwait(ep, epi);
900                 }
901         }
902
903         /*
904          * Walks through the whole hash by freeing each "struct epitem". At this
905          * point we are sure no poll callbacks will be lingering around, and also by
906          * write-holding "sem" we can be sure that no file cleanup code will hit
907          * us during this operation. So we can avoid the lock on "ep->lock".
908          */
909         for (i = 0, hsize = 1 << ep->hashbits; i < hsize; i++) {
910                 lsthead = ep_hash_entry(ep, i);
911
912                 while (!list_empty(lsthead)) {
913                         epi = list_entry(lsthead->next, struct epitem, llink);
914
915                         ep_remove(ep, epi);
916                 }
917         }
918
919         up(&epsem);
920
921         /* Free hash pages */
922         ep_free_pages(ep->hpages, EP_HASH_PAGES(ep->hashbits));
923 }
924
925
926 /*
927  * Search the file inside the eventpoll hash. It add usage count to
928  * the returned item, so the caller must call ep_release_epitem()
929  * after finished using the "struct epitem".
930  */
931 static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
932 {
933         unsigned long flags;
934         struct list_head *lsthead, *lnk;
935         struct epitem *epi = NULL;
936
937         read_lock_irqsave(&ep->lock, flags);
938
939         lsthead = ep_hash_entry(ep, ep_hash_index(ep, file, fd));
940         list_for_each(lnk, lsthead) {
941                 epi = list_entry(lnk, struct epitem, llink);
942
943                 if (epi->file == file && epi->fd == fd) {
944                         ep_use_epitem(epi);
945                         break;
946                 }
947                 epi = NULL;
948         }
949
950         read_unlock_irqrestore(&ep->lock, flags);
951
952         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_find(%p) -> %p\n",
953                      current, file, epi));
954
955         return epi;
956 }
957
958
959 /*
960  * Increment the usage count of the "struct epitem" making it sure
961  * that the user will have a valid pointer to reference.
962  */
963 static void ep_use_epitem(struct epitem *epi)
964 {
965
966         atomic_inc(&epi->usecnt);
967 }
968
969
970 /*
971  * Decrement ( release ) the usage count by signaling that the user
972  * has finished using the structure. It might lead to freeing the
973  * structure itself if the count goes to zero.
974  */
975 static void ep_release_epitem(struct epitem *epi)
976 {
977
978         if (atomic_dec_and_test(&epi->usecnt))
979                 EPI_MEM_FREE(epi);
980 }
981
982
983 /*
984  * This is the callback that is used to add our wait queue to the
985  * target file wakeup lists.
986  */
987 static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
988                                  poll_table *pt)
989 {
990         struct epitem *epi = EP_ITEM_FROM_EPQUEUE(pt);
991         struct eppoll_entry *pwq;
992
993         if (epi->nwait >= 0 && (pwq = PWQ_MEM_ALLOC())) {
994                 init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
995                 pwq->whead = whead;
996                 pwq->base = epi;
997                 add_wait_queue(whead, &pwq->wait);
998                 list_add_tail(&pwq->llink, &epi->pwqlist);
999                 epi->nwait++;
1000         } else {
1001                 /* We have to signal that an error occurred */
1002                 epi->nwait = -1;
1003         }
1004 }
1005
1006
1007 static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
1008                      struct file *tfile, int fd)
1009 {
1010         int error, revents, pwake = 0;
1011         unsigned long flags;
1012         struct epitem *epi;
1013         struct ep_pqueue epq;
1014
1015         error = -ENOMEM;
1016         if (!(epi = EPI_MEM_ALLOC()))
1017                 goto eexit_1;
1018
1019         /* Item initialization follow here ... */
1020         INIT_LIST_HEAD(&epi->llink);
1021         INIT_LIST_HEAD(&epi->rdllink);
1022         INIT_LIST_HEAD(&epi->fllink);
1023         INIT_LIST_HEAD(&epi->txlink);
1024         INIT_LIST_HEAD(&epi->pwqlist);
1025         epi->ep = ep;
1026         epi->file = tfile;
1027         epi->fd = fd;
1028         epi->event = *event;
1029         atomic_set(&epi->usecnt, 1);
1030         epi->nwait = 0;
1031
1032         /* Initialize the poll table using the queue callback */
1033         epq.epi = epi;
1034         init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);
1035
1036         /*
1037          * Attach the item to the poll hooks and get current event bits.
1038          * We can safely use the file* here because its usage count has
1039          * been increased by the caller of this function.
1040          */
1041         revents = tfile->f_op->poll(tfile, &epq.pt);
1042
1043         /*
1044          * We have to check if something went wrong during the poll wait queue
1045          * install process. Namely an allocation for a wait queue failed due
1046          * high memory pressure.
1047          */
1048         if (epi->nwait < 0)
1049                 goto eexit_2;
1050
1051         /* Add the current item to the list of active epoll hook for this file */
1052         spin_lock(&tfile->f_ep_lock);
1053         list_add_tail(&epi->fllink, &tfile->f_ep_links);
1054         spin_unlock(&tfile->f_ep_lock);
1055
1056         /* We have to drop the new item inside our item list to keep track of it */
1057         write_lock_irqsave(&ep->lock, flags);
1058
1059         /* Add the current item to the hash table */
1060         list_add(&epi->llink, ep_hash_entry(ep, ep_hash_index(ep, tfile, fd)));
1061
1062         /* If the file is already "ready" we drop it inside the ready list */
1063         if ((revents & event->events) && !EP_IS_LINKED(&epi->rdllink)) {
1064                 list_add_tail(&epi->rdllink, &ep->rdllist);
1065
1066                 /* Notify waiting tasks that events are available */
1067                 if (waitqueue_active(&ep->wq))
1068                         wake_up(&ep->wq);
1069                 if (waitqueue_active(&ep->poll_wait))
1070                         pwake++;
1071         }
1072
1073         write_unlock_irqrestore(&ep->lock, flags);
1074
1075         /* We have to call this outside the lock */
1076         if (pwake)
1077                 ep_poll_safewake(&psw, &ep->poll_wait);
1078
1079         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_insert(%p, %p, %d)\n",
1080                      current, ep, tfile, fd));
1081
1082         return 0;
1083
1084 eexit_2:
1085         ep_unregister_pollwait(ep, epi);
1086
1087         /*
1088          * We need to do this because an event could have been arrived on some
1089          * allocated wait queue.
1090          */
1091         write_lock_irqsave(&ep->lock, flags);
1092         if (EP_IS_LINKED(&epi->rdllink))
1093                 EP_LIST_DEL(&epi->rdllink);
1094         write_unlock_irqrestore(&ep->lock, flags);
1095
1096         EPI_MEM_FREE(epi);
1097 eexit_1:
1098         return error;
1099 }
1100
1101
1102 /*
1103  * Modify the interest event mask by dropping an event if the new mask
1104  * has a match in the current file status.
1105  */
1106 static int ep_modify(struct eventpoll *ep, struct epitem *epi, struct epoll_event *event)
1107 {
1108         int pwake = 0;
1109         unsigned int revents;
1110         unsigned long flags;
1111
1112         /*
1113          * Set the new event interest mask before calling f_op->poll(), otherwise
1114          * a potential race might occur. In fact if we do this operation inside
1115          * the lock, an event might happen between the f_op->poll() call and the
1116          * new event set registering.
1117          */
1118         epi->event.events = event->events;
1119
1120         /*
1121          * Get current event bits. We can safely use the file* here because
1122          * its usage count has been increased by the caller of this function.
1123          */
1124         revents = epi->file->f_op->poll(epi->file, NULL);
1125
1126         write_lock_irqsave(&ep->lock, flags);
1127
1128         /* Copy the data member from inside the lock */
1129         epi->event.data = event->data;
1130
1131         /*
1132          * If the item is not linked to the hash it means that it's on its
1133          * way toward the removal. Do nothing in this case.
1134          */
1135         if (EP_IS_LINKED(&epi->llink)) {
1136                 /*
1137                  * If the item is "hot" and it is not registered inside the ready
1138                  * list, push it inside. If the item is not "hot" and it is currently
1139                  * registered inside the ready list, unlink it.
1140                  */
1141                 if (revents & event->events) {
1142                         if (!EP_IS_LINKED(&epi->rdllink)) {
1143                                 list_add_tail(&epi->rdllink, &ep->rdllist);
1144
1145                                 /* Notify waiting tasks that events are available */
1146                                 if (waitqueue_active(&ep->wq))
1147                                         wake_up(&ep->wq);
1148                                 if (waitqueue_active(&ep->poll_wait))
1149                                         pwake++;
1150                         }
1151                 }
1152         }
1153
1154         write_unlock_irqrestore(&ep->lock, flags);
1155
1156         /* We have to call this outside the lock */
1157         if (pwake)
1158                 ep_poll_safewake(&psw, &ep->poll_wait);
1159
1160         return 0;
1161 }
1162
1163
1164 /*
1165  * This function unregister poll callbacks from the associated file descriptor.
1166  * Since this must be called without holding "ep->lock" the atomic exchange trick
1167  * will protect us from multiple unregister.
1168  */
1169 static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi)
1170 {
1171         int nwait;
1172         struct list_head *lsthead = &epi->pwqlist;
1173         struct eppoll_entry *pwq;
1174
1175         /* This is called without locks, so we need the atomic exchange */
1176         nwait = xchg(&epi->nwait, 0);
1177
1178         if (nwait) {
1179                 while (!list_empty(lsthead)) {
1180                         pwq = list_entry(lsthead->next, struct eppoll_entry, llink);
1181
1182                         EP_LIST_DEL(&pwq->llink);
1183                         remove_wait_queue(pwq->whead, &pwq->wait);
1184                         PWQ_MEM_FREE(pwq);
1185                 }
1186         }
1187 }
1188
1189
1190 /*
1191  * Unlink the "struct epitem" from all places it might have been hooked up.
1192  * This function must be called with write IRQ lock on "ep->lock".
1193  */
1194 static int ep_unlink(struct eventpoll *ep, struct epitem *epi)
1195 {
1196         int error;
1197
1198         /*
1199          * It can happen that this one is called for an item already unlinked.
1200          * The check protect us from doing a double unlink ( crash ).
1201          */
1202         error = -ENOENT;
1203         if (!EP_IS_LINKED(&epi->llink))
1204                 goto eexit_1;
1205
1206         /*
1207          * Clear the event mask for the unlinked item. This will avoid item
1208          * notifications to be sent after the unlink operation from inside
1209          * the kernel->userspace event transfer loop.
1210          */
1211         epi->event.events = 0;
1212
1213         /*
1214          * At this point is safe to do the job, unlink the item from our list.
1215          * This operation togheter with the above check closes the door to
1216          * double unlinks.
1217          */
1218         EP_LIST_DEL(&epi->llink);
1219
1220         /*
1221          * If the item we are going to remove is inside the ready file descriptors
1222          * we want to remove it from this list to avoid stale events.
1223          */
1224         if (EP_IS_LINKED(&epi->rdllink))
1225                 EP_LIST_DEL(&epi->rdllink);
1226
1227         error = 0;
1228 eexit_1:
1229
1230         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_unlink(%p, %p) = %d\n",
1231                      current, ep, epi->file, error));
1232
1233         return error;
1234 }
1235
1236
1237 /*
1238  * Removes a "struct epitem" from the eventpoll hash and deallocates
1239  * all the associated resources.
1240  */
1241 static int ep_remove(struct eventpoll *ep, struct epitem *epi)
1242 {
1243         int error;
1244         unsigned long flags;
1245         struct file *file = epi->file;
1246
1247         /*
1248          * Removes poll wait queue hooks. We _have_ to do this without holding
1249          * the "ep->lock" otherwise a deadlock might occur. This because of the
1250          * sequence of the lock acquisition. Here we do "ep->lock" then the wait
1251          * queue head lock when unregistering the wait queue. The wakeup callback
1252          * will run by holding the wait queue head lock and will call our callback
1253          * that will try to get "ep->lock".
1254          */
1255         ep_unregister_pollwait(ep, epi);
1256
1257         /* Remove the current item from the list of epoll hooks */
1258         spin_lock(&file->f_ep_lock);
1259         if (EP_IS_LINKED(&epi->fllink))
1260                 EP_LIST_DEL(&epi->fllink);
1261         spin_unlock(&file->f_ep_lock);
1262
1263         /* We need to acquire the write IRQ lock before calling ep_unlink() */
1264         write_lock_irqsave(&ep->lock, flags);
1265
1266         /* Really unlink the item from the hash */
1267         error = ep_unlink(ep, epi);
1268
1269         write_unlock_irqrestore(&ep->lock, flags);
1270
1271         if (error)
1272                 goto eexit_1;
1273
1274         /* At this point it is safe to free the eventpoll item */
1275         ep_release_epitem(epi);
1276
1277         error = 0;
1278 eexit_1:
1279         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: ep_remove(%p, %p) = %d\n",
1280                      current, ep, file, error));
1281
1282         return error;
1283 }
1284
1285
1286 /*
1287  * This is the callback that is passed to the wait queue wakeup
1288  * machanism. It is called by the stored file descriptors when they
1289  * have events to report.
1290  */
1291 static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *key)
1292 {
1293         int pwake = 0;
1294         unsigned long flags;
1295         struct epitem *epi = EP_ITEM_FROM_WAIT(wait);
1296         struct eventpoll *ep = epi->ep;
1297
1298         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: poll_callback(%p) epi=%p ep=%p\n",
1299                      current, epi->file, epi, ep));
1300
1301         write_lock_irqsave(&ep->lock, flags);
1302
1303         /*
1304          * If the event mask does not contain any poll(2) event, we consider the
1305          * descriptor to be disabled. This condition is likely the effect of the
1306          * EPOLLONESHOT bit that disables the descriptor when an event is received,
1307          * until the next EPOLL_CTL_MOD will be issued.
1308          */
1309         if (!(epi->event.events & ~EP_PRIVATE_BITS))
1310                 goto is_disabled;
1311
1312         /* If this file is already in the ready list we exit soon */
1313         if (EP_IS_LINKED(&epi->rdllink))
1314                 goto is_linked;
1315
1316         list_add_tail(&epi->rdllink, &ep->rdllist);
1317
1318 is_linked:
1319         /*
1320          * Wake up ( if active ) both the eventpoll wait list and the ->poll()
1321          * wait list.
1322          */
1323         if (waitqueue_active(&ep->wq))
1324                 wake_up(&ep->wq);
1325         if (waitqueue_active(&ep->poll_wait))
1326                 pwake++;
1327
1328 is_disabled:
1329         write_unlock_irqrestore(&ep->lock, flags);
1330
1331         /* We have to call this outside the lock */
1332         if (pwake)
1333                 ep_poll_safewake(&psw, &ep->poll_wait);
1334
1335         return 1;
1336 }
1337
1338
1339 static int ep_eventpoll_close(struct inode *inode, struct file *file)
1340 {
1341         struct eventpoll *ep = file->private_data;
1342
1343         if (ep) {
1344                 ep_free(ep);
1345                 kfree(ep);
1346         }
1347
1348         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: close() ep=%p\n", current, ep));
1349         return 0;
1350 }
1351
1352
1353 static unsigned int ep_eventpoll_poll(struct file *file, poll_table *wait)
1354 {
1355         unsigned int pollflags = 0;
1356         unsigned long flags;
1357         struct eventpoll *ep = file->private_data;
1358
1359         /* Insert inside our poll wait queue */
1360         poll_wait(file, &ep->poll_wait, wait);
1361
1362         /* Check our condition */
1363         read_lock_irqsave(&ep->lock, flags);
1364         if (!list_empty(&ep->rdllist))
1365                 pollflags = POLLIN | POLLRDNORM;
1366         read_unlock_irqrestore(&ep->lock, flags);
1367
1368         return pollflags;
1369 }
1370
1371
1372 /*
1373  * Since we have to release the lock during the __copy_to_user() operation and
1374  * during the f_op->poll() call, we try to collect the maximum number of items
1375  * by reducing the irqlock/irqunlock switching rate.
1376  */
1377 static int ep_collect_ready_items(struct eventpoll *ep, struct list_head *txlist, int maxevents)
1378 {
1379         int nepi;
1380         unsigned long flags;
1381         struct list_head *lsthead = &ep->rdllist, *lnk;
1382         struct epitem *epi;
1383
1384         write_lock_irqsave(&ep->lock, flags);
1385
1386         for (nepi = 0, lnk = lsthead->next; lnk != lsthead && nepi < maxevents;) {
1387                 epi = list_entry(lnk, struct epitem, rdllink);
1388
1389                 lnk = lnk->next;
1390
1391                 /* If this file is already in the ready list we exit soon */
1392                 if (!EP_IS_LINKED(&epi->txlink)) {
1393                         /*
1394                          * This is initialized in this way so that the default
1395                          * behaviour of the reinjecting code will be to push back
1396                          * the item inside the ready list.
1397                          */
1398                         epi->revents = epi->event.events;
1399
1400                         /* Link the ready item into the transfer list */
1401                         list_add(&epi->txlink, txlist);
1402                         nepi++;
1403
1404                         /*
1405                          * Unlink the item from the ready list.
1406                          */
1407                         EP_LIST_DEL(&epi->rdllink);
1408                 }
1409         }
1410
1411         write_unlock_irqrestore(&ep->lock, flags);
1412
1413         return nepi;
1414 }
1415
1416
1417 /*
1418  * This function is called without holding the "ep->lock" since the call to
1419  * __copy_to_user() might sleep, and also f_op->poll() might reenable the IRQ
1420  * because of the way poll() is traditionally implemented in Linux.
1421  */
1422 static int ep_send_events(struct eventpoll *ep, struct list_head *txlist,
1423                           struct epoll_event __user *events)
1424 {
1425         int eventcnt = 0;
1426         unsigned int revents;
1427         struct list_head *lnk;
1428         struct epitem *epi;
1429
1430         /*
1431          * We can loop without lock because this is a task private list.
1432          * The test done during the collection loop will guarantee us that
1433          * another task will not try to collect this file. Also, items
1434          * cannot vanish during the loop because we are holding "sem".
1435          */
1436         list_for_each(lnk, txlist) {
1437                 epi = list_entry(lnk, struct epitem, txlink);
1438
1439                 /*
1440                  * Get the ready file event set. We can safely use the file
1441                  * because we are holding the "sem" in read and this will
1442                  * guarantee that both the file and the item will not vanish.
1443                  */
1444                 revents = epi->file->f_op->poll(epi->file, NULL);
1445
1446                 /*
1447                  * Set the return event set for the current file descriptor.
1448                  * Note that only the task task was successfully able to link
1449                  * the item to its "txlist" will write this field.
1450                  */
1451                 epi->revents = revents & epi->event.events;
1452
1453                 if (epi->revents) {
1454                         if (__put_user(epi->revents,
1455                                        &events[eventcnt].events) ||
1456                             __put_user(epi->event.data,
1457                                        &events[eventcnt].data))
1458                                 return -EFAULT;
1459                         if (epi->event.events & EPOLLONESHOT)
1460                                 epi->event.events &= EP_PRIVATE_BITS;
1461                         eventcnt++;
1462                 }
1463         }
1464         return eventcnt;
1465 }
1466
1467
1468 /*
1469  * Walk through the transfer list we collected with ep_collect_ready_items()
1470  * and, if 1) the item is still "alive" 2) its event set is not empty 3) it's
1471  * not already linked, links it to the ready list. Same as above, we are holding
1472  * "sem" so items cannot vanish underneath our nose.
1473  */
1474 static void ep_reinject_items(struct eventpoll *ep, struct list_head *txlist)
1475 {
1476         int ricnt = 0, pwake = 0;
1477         unsigned long flags;
1478         struct epitem *epi;
1479
1480         write_lock_irqsave(&ep->lock, flags);
1481
1482         while (!list_empty(txlist)) {
1483                 epi = list_entry(txlist->next, struct epitem, txlink);
1484
1485                 /* Unlink the current item from the transfer list */
1486                 EP_LIST_DEL(&epi->txlink);
1487
1488                 /*
1489                  * If the item is no more linked to the interest set, we don't
1490                  * have to push it inside the ready list because the following
1491                  * ep_release_epitem() is going to drop it. Also, if the current
1492                  * item is set to have an Edge Triggered behaviour, we don't have
1493                  * to push it back either.
1494                  */
1495                 if (EP_IS_LINKED(&epi->llink) && !(epi->event.events & EPOLLET) &&
1496                     (epi->revents & epi->event.events) && !EP_IS_LINKED(&epi->rdllink)) {
1497                         list_add_tail(&epi->rdllink, &ep->rdllist);
1498                         ricnt++;
1499                 }
1500         }
1501
1502         if (ricnt) {
1503                 /*
1504                  * Wake up ( if active ) both the eventpoll wait list and the ->poll()
1505                  * wait list.
1506                  */
1507                 if (waitqueue_active(&ep->wq))
1508                         wake_up(&ep->wq);
1509                 if (waitqueue_active(&ep->poll_wait))
1510                         pwake++;
1511         }
1512
1513         write_unlock_irqrestore(&ep->lock, flags);
1514
1515         /* We have to call this outside the lock */
1516         if (pwake)
1517                 ep_poll_safewake(&psw, &ep->poll_wait);
1518 }
1519
1520
1521 /*
1522  * Perform the transfer of events to user space.
1523  */
1524 static int ep_events_transfer(struct eventpoll *ep,
1525                               struct epoll_event __user *events, int maxevents)
1526 {
1527         int eventcnt = 0;
1528         struct list_head txlist;
1529
1530         INIT_LIST_HEAD(&txlist);
1531
1532         /*
1533          * We need to lock this because we could be hit by
1534          * eventpoll_release_file() and epoll_ctl(EPOLL_CTL_DEL).
1535          */
1536         down_read(&ep->sem);
1537
1538         /* Collect/extract ready items */
1539         if (ep_collect_ready_items(ep, &txlist, maxevents) > 0) {
1540                 /* Build result set in userspace */
1541                 eventcnt = ep_send_events(ep, &txlist, events);
1542
1543                 /* Reinject ready items into the ready list */
1544                 ep_reinject_items(ep, &txlist);
1545         }
1546
1547         up_read(&ep->sem);
1548
1549         return eventcnt;
1550 }
1551
1552
1553 static int ep_poll(struct eventpoll *ep, struct epoll_event __user *events,
1554                    int maxevents, long timeout)
1555 {
1556         int res, eavail;
1557         unsigned long flags;
1558         long jtimeout;
1559         wait_queue_t wait;
1560
1561         /*
1562          * Calculate the timeout by checking for the "infinite" value ( -1 )
1563          * and the overflow condition. The passed timeout is in milliseconds,
1564          * that why (t * HZ) / 1000.
1565          */
1566         jtimeout = timeout == -1 || timeout > (MAX_SCHEDULE_TIMEOUT - 1000) / HZ ?
1567                 MAX_SCHEDULE_TIMEOUT: (timeout * HZ + 999) / 1000;
1568
1569 retry:
1570         write_lock_irqsave(&ep->lock, flags);
1571
1572         res = 0;
1573         if (list_empty(&ep->rdllist)) {
1574                 /*
1575                  * We don't have any available event to return to the caller.
1576                  * We need to sleep here, and we will be wake up by
1577                  * ep_poll_callback() when events will become available.
1578                  */
1579                 init_waitqueue_entry(&wait, current);
1580                 add_wait_queue(&ep->wq, &wait);
1581
1582                 for (;;) {
1583                         /*
1584                          * We don't want to sleep if the ep_poll_callback() sends us
1585                          * a wakeup in between. That's why we set the task state
1586                          * to TASK_INTERRUPTIBLE before doing the checks.
1587                          */
1588                         set_current_state(TASK_INTERRUPTIBLE);
1589                         if (!list_empty(&ep->rdllist) || !jtimeout)
1590                                 break;
1591                         if (signal_pending(current)) {
1592                                 res = -EINTR;
1593                                 break;
1594                         }
1595
1596                         write_unlock_irqrestore(&ep->lock, flags);
1597                         jtimeout = schedule_timeout(jtimeout);
1598                         write_lock_irqsave(&ep->lock, flags);
1599                 }
1600                 remove_wait_queue(&ep->wq, &wait);
1601
1602                 set_current_state(TASK_RUNNING);
1603         }
1604
1605         /* Is it worth to try to dig for events ? */
1606         eavail = !list_empty(&ep->rdllist);
1607
1608         write_unlock_irqrestore(&ep->lock, flags);
1609
1610         /*
1611          * Try to transfer events to user space. In case we get 0 events and
1612          * there's still timeout left over, we go trying again in search of
1613          * more luck.
1614          */
1615         if (!res && eavail &&
1616             !(res = ep_events_transfer(ep, events, maxevents)) && jtimeout)
1617                 goto retry;
1618
1619         return res;
1620 }
1621
1622
1623 static int eventpollfs_delete_dentry(struct dentry *dentry)
1624 {
1625
1626         return 1;
1627 }
1628
1629
1630 static struct inode *ep_eventpoll_inode(void)
1631 {
1632         int error = -ENOMEM;
1633         struct inode *inode = new_inode(eventpoll_mnt->mnt_sb);
1634
1635         if (!inode)
1636                 goto eexit_1;
1637
1638         inode->i_fop = &eventpoll_fops;
1639
1640         /*
1641          * Mark the inode dirty from the very beginning,
1642          * that way it will never be moved to the dirty
1643          * list because mark_inode_dirty() will think
1644          * that it already _is_ on the dirty list.
1645          */
1646         inode->i_state = I_DIRTY;
1647         inode->i_mode = S_IRUSR | S_IWUSR;
1648         inode->i_uid = current->fsuid;
1649         inode->i_gid = current->fsgid;
1650         inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1651         inode->i_blksize = PAGE_SIZE;
1652         return inode;
1653
1654 eexit_1:
1655         return ERR_PTR(error);
1656 }
1657
1658
1659 static struct super_block *
1660 eventpollfs_get_sb(struct file_system_type *fs_type, int flags,
1661                    const char *dev_name, void *data)
1662 {
1663         return get_sb_pseudo(fs_type, "eventpoll:", NULL, EVENTPOLLFS_MAGIC);
1664 }
1665
1666
1667 static int __init eventpoll_init(void)
1668 {
1669         int error;
1670
1671         init_MUTEX(&epsem);
1672
1673         /* Initialize the structure used to perform safe poll wait head wake ups */
1674         ep_poll_safewake_init(&psw);
1675
1676         /* Allocates slab cache used to allocate "struct epitem" items */
1677         epi_cache = kmem_cache_create("eventpoll_epi", sizeof(struct epitem),
1678                         0, SLAB_HWCACHE_ALIGN|EPI_SLAB_DEBUG|SLAB_PANIC,
1679                         NULL, NULL);
1680
1681         /* Allocates slab cache used to allocate "struct eppoll_entry" */
1682         pwq_cache = kmem_cache_create("eventpoll_pwq",
1683                         sizeof(struct eppoll_entry), 0,
1684                         EPI_SLAB_DEBUG|SLAB_PANIC, NULL, NULL);
1685
1686         /*
1687          * Register the virtual file system that will be the source of inodes
1688          * for the eventpoll files
1689          */
1690         error = register_filesystem(&eventpoll_fs_type);
1691         if (error)
1692                 goto epanic;
1693
1694         /* Mount the above commented virtual file system */
1695         eventpoll_mnt = kern_mount(&eventpoll_fs_type);
1696         error = PTR_ERR(eventpoll_mnt);
1697         if (IS_ERR(eventpoll_mnt))
1698                 goto epanic;
1699
1700         DNPRINTK(3, (KERN_INFO "[%p] eventpoll: successfully initialized.\n",
1701                         current));
1702         return 0;
1703
1704 epanic:
1705         panic("eventpoll_init() failed\n");
1706 }
1707
1708
1709 static void __exit eventpoll_exit(void)
1710 {
1711         /* Undo all operations done inside eventpoll_init() */
1712         unregister_filesystem(&eventpoll_fs_type);
1713         mntput(eventpoll_mnt);
1714         kmem_cache_destroy(pwq_cache);
1715         kmem_cache_destroy(epi_cache);
1716 }
1717
1718 module_init(eventpoll_init);
1719 module_exit(eventpoll_exit);
1720
1721 MODULE_LICENSE("GPL");