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