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