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