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