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