xref: /linux/fs/select.c (revision 6d729e44a55547c009d7a87ea66bff21a8e0afea)
1 /*
2  * This file contains the procedures for the handling of select and poll
3  *
4  * Created for Linux based loosely upon Mathius Lattner's minix
5  * patches by Peter MacDonald. Heavily edited by Linus.
6  *
7  *  4 February 1994
8  *     COFF/ELF binary emulation. If the process has the STICKY_TIMEOUTS
9  *     flag set in its personality we do *not* modify the given timeout
10  *     parameter to reflect time remaining.
11  *
12  *  24 January 2000
13  *     Changed sys_poll()/do_poll() to use PAGE_SIZE chunk-based allocation
14  *     of fds to overcome nfds < 16390 descriptors limit (Tigran Aivazian).
15  */
16 
17 #include <linux/kernel.h>
18 #include <linux/syscalls.h>
19 #include <linux/module.h>
20 #include <linux/slab.h>
21 #include <linux/poll.h>
22 #include <linux/personality.h> /* for STICKY_TIMEOUTS */
23 #include <linux/file.h>
24 #include <linux/fdtable.h>
25 #include <linux/fs.h>
26 #include <linux/rcupdate.h>
27 #include <linux/hrtimer.h>
28 
29 #include <asm/uaccess.h>
30 
31 
32 /*
33  * Estimate expected accuracy in ns from a timeval.
34  *
35  * After quite a bit of churning around, we've settled on
36  * a simple thing of taking 0.1% of the timeout as the
37  * slack, with a cap of 100 msec.
38  * "nice" tasks get a 0.5% slack instead.
39  *
40  * Consider this comment an open invitation to come up with even
41  * better solutions..
42  */
43 
44 #define MAX_SLACK	(100 * NSEC_PER_MSEC)
45 
46 static long __estimate_accuracy(struct timespec *tv)
47 {
48 	long slack;
49 	int divfactor = 1000;
50 
51 	if (tv->tv_sec < 0)
52 		return 0;
53 
54 	if (task_nice(current) > 0)
55 		divfactor = divfactor / 5;
56 
57 	if (tv->tv_sec > MAX_SLACK / (NSEC_PER_SEC/divfactor))
58 		return MAX_SLACK;
59 
60 	slack = tv->tv_nsec / divfactor;
61 	slack += tv->tv_sec * (NSEC_PER_SEC/divfactor);
62 
63 	if (slack > MAX_SLACK)
64 		return MAX_SLACK;
65 
66 	return slack;
67 }
68 
69 static long estimate_accuracy(struct timespec *tv)
70 {
71 	unsigned long ret;
72 	struct timespec now;
73 
74 	/*
75 	 * Realtime tasks get a slack of 0 for obvious reasons.
76 	 */
77 
78 	if (rt_task(current))
79 		return 0;
80 
81 	ktime_get_ts(&now);
82 	now = timespec_sub(*tv, now);
83 	ret = __estimate_accuracy(&now);
84 	if (ret < current->timer_slack_ns)
85 		return current->timer_slack_ns;
86 	return ret;
87 }
88 
89 
90 
91 struct poll_table_page {
92 	struct poll_table_page * next;
93 	struct poll_table_entry * entry;
94 	struct poll_table_entry entries[0];
95 };
96 
97 #define POLL_TABLE_FULL(table) \
98 	((unsigned long)((table)->entry+1) > PAGE_SIZE + (unsigned long)(table))
99 
100 /*
101  * Ok, Peter made a complicated, but straightforward multiple_wait() function.
102  * I have rewritten this, taking some shortcuts: This code may not be easy to
103  * follow, but it should be free of race-conditions, and it's practical. If you
104  * understand what I'm doing here, then you understand how the linux
105  * sleep/wakeup mechanism works.
106  *
107  * Two very simple procedures, poll_wait() and poll_freewait() make all the
108  * work.  poll_wait() is an inline-function defined in <linux/poll.h>,
109  * as all select/poll functions have to call it to add an entry to the
110  * poll table.
111  */
112 static void __pollwait(struct file *filp, wait_queue_head_t *wait_address,
113 		       poll_table *p);
114 
115 void poll_initwait(struct poll_wqueues *pwq)
116 {
117 	init_poll_funcptr(&pwq->pt, __pollwait);
118 	pwq->polling_task = current;
119 	pwq->triggered = 0;
120 	pwq->error = 0;
121 	pwq->table = NULL;
122 	pwq->inline_index = 0;
123 }
124 EXPORT_SYMBOL(poll_initwait);
125 
126 static void free_poll_entry(struct poll_table_entry *entry)
127 {
128 	remove_wait_queue(entry->wait_address, &entry->wait);
129 	fput(entry->filp);
130 }
131 
132 void poll_freewait(struct poll_wqueues *pwq)
133 {
134 	struct poll_table_page * p = pwq->table;
135 	int i;
136 	for (i = 0; i < pwq->inline_index; i++)
137 		free_poll_entry(pwq->inline_entries + i);
138 	while (p) {
139 		struct poll_table_entry * entry;
140 		struct poll_table_page *old;
141 
142 		entry = p->entry;
143 		do {
144 			entry--;
145 			free_poll_entry(entry);
146 		} while (entry > p->entries);
147 		old = p;
148 		p = p->next;
149 		free_page((unsigned long) old);
150 	}
151 }
152 EXPORT_SYMBOL(poll_freewait);
153 
154 static struct poll_table_entry *poll_get_entry(struct poll_wqueues *p)
155 {
156 	struct poll_table_page *table = p->table;
157 
158 	if (p->inline_index < N_INLINE_POLL_ENTRIES)
159 		return p->inline_entries + p->inline_index++;
160 
161 	if (!table || POLL_TABLE_FULL(table)) {
162 		struct poll_table_page *new_table;
163 
164 		new_table = (struct poll_table_page *) __get_free_page(GFP_KERNEL);
165 		if (!new_table) {
166 			p->error = -ENOMEM;
167 			return NULL;
168 		}
169 		new_table->entry = new_table->entries;
170 		new_table->next = table;
171 		p->table = new_table;
172 		table = new_table;
173 	}
174 
175 	return table->entry++;
176 }
177 
178 static int __pollwake(wait_queue_t *wait, unsigned mode, int sync, void *key)
179 {
180 	struct poll_wqueues *pwq = wait->private;
181 	DECLARE_WAITQUEUE(dummy_wait, pwq->polling_task);
182 
183 	/*
184 	 * Although this function is called under waitqueue lock, LOCK
185 	 * doesn't imply write barrier and the users expect write
186 	 * barrier semantics on wakeup functions.  The following
187 	 * smp_wmb() is equivalent to smp_wmb() in try_to_wake_up()
188 	 * and is paired with set_mb() in poll_schedule_timeout.
189 	 */
190 	smp_wmb();
191 	pwq->triggered = 1;
192 
193 	/*
194 	 * Perform the default wake up operation using a dummy
195 	 * waitqueue.
196 	 *
197 	 * TODO: This is hacky but there currently is no interface to
198 	 * pass in @sync.  @sync is scheduled to be removed and once
199 	 * that happens, wake_up_process() can be used directly.
200 	 */
201 	return default_wake_function(&dummy_wait, mode, sync, key);
202 }
203 
204 static int pollwake(wait_queue_t *wait, unsigned mode, int sync, void *key)
205 {
206 	struct poll_table_entry *entry;
207 
208 	entry = container_of(wait, struct poll_table_entry, wait);
209 	if (key && !((unsigned long)key & entry->key))
210 		return 0;
211 	return __pollwake(wait, mode, sync, key);
212 }
213 
214 /* Add a new entry */
215 static void __pollwait(struct file *filp, wait_queue_head_t *wait_address,
216 				poll_table *p)
217 {
218 	struct poll_wqueues *pwq = container_of(p, struct poll_wqueues, pt);
219 	struct poll_table_entry *entry = poll_get_entry(pwq);
220 	if (!entry)
221 		return;
222 	get_file(filp);
223 	entry->filp = filp;
224 	entry->wait_address = wait_address;
225 	entry->key = p->key;
226 	init_waitqueue_func_entry(&entry->wait, pollwake);
227 	entry->wait.private = pwq;
228 	add_wait_queue(wait_address, &entry->wait);
229 }
230 
231 int poll_schedule_timeout(struct poll_wqueues *pwq, int state,
232 			  ktime_t *expires, unsigned long slack)
233 {
234 	int rc = -EINTR;
235 
236 	set_current_state(state);
237 	if (!pwq->triggered)
238 		rc = schedule_hrtimeout_range(expires, slack, HRTIMER_MODE_ABS);
239 	__set_current_state(TASK_RUNNING);
240 
241 	/*
242 	 * Prepare for the next iteration.
243 	 *
244 	 * The following set_mb() serves two purposes.  First, it's
245 	 * the counterpart rmb of the wmb in pollwake() such that data
246 	 * written before wake up is always visible after wake up.
247 	 * Second, the full barrier guarantees that triggered clearing
248 	 * doesn't pass event check of the next iteration.  Note that
249 	 * this problem doesn't exist for the first iteration as
250 	 * add_wait_queue() has full barrier semantics.
251 	 */
252 	set_mb(pwq->triggered, 0);
253 
254 	return rc;
255 }
256 EXPORT_SYMBOL(poll_schedule_timeout);
257 
258 /**
259  * poll_select_set_timeout - helper function to setup the timeout value
260  * @to:		pointer to timespec variable for the final timeout
261  * @sec:	seconds (from user space)
262  * @nsec:	nanoseconds (from user space)
263  *
264  * Note, we do not use a timespec for the user space value here, That
265  * way we can use the function for timeval and compat interfaces as well.
266  *
267  * Returns -EINVAL if sec/nsec are not normalized. Otherwise 0.
268  */
269 int poll_select_set_timeout(struct timespec *to, long sec, long nsec)
270 {
271 	struct timespec ts = {.tv_sec = sec, .tv_nsec = nsec};
272 
273 	if (!timespec_valid(&ts))
274 		return -EINVAL;
275 
276 	/* Optimize for the zero timeout value here */
277 	if (!sec && !nsec) {
278 		to->tv_sec = to->tv_nsec = 0;
279 	} else {
280 		ktime_get_ts(to);
281 		*to = timespec_add_safe(*to, ts);
282 	}
283 	return 0;
284 }
285 
286 static int poll_select_copy_remaining(struct timespec *end_time, void __user *p,
287 				      int timeval, int ret)
288 {
289 	struct timespec rts;
290 	struct timeval rtv;
291 
292 	if (!p)
293 		return ret;
294 
295 	if (current->personality & STICKY_TIMEOUTS)
296 		goto sticky;
297 
298 	/* No update for zero timeout */
299 	if (!end_time->tv_sec && !end_time->tv_nsec)
300 		return ret;
301 
302 	ktime_get_ts(&rts);
303 	rts = timespec_sub(*end_time, rts);
304 	if (rts.tv_sec < 0)
305 		rts.tv_sec = rts.tv_nsec = 0;
306 
307 	if (timeval) {
308 		rtv.tv_sec = rts.tv_sec;
309 		rtv.tv_usec = rts.tv_nsec / NSEC_PER_USEC;
310 
311 		if (!copy_to_user(p, &rtv, sizeof(rtv)))
312 			return ret;
313 
314 	} else if (!copy_to_user(p, &rts, sizeof(rts)))
315 		return ret;
316 
317 	/*
318 	 * If an application puts its timeval in read-only memory, we
319 	 * don't want the Linux-specific update to the timeval to
320 	 * cause a fault after the select has completed
321 	 * successfully. However, because we're not updating the
322 	 * timeval, we can't restart the system call.
323 	 */
324 
325 sticky:
326 	if (ret == -ERESTARTNOHAND)
327 		ret = -EINTR;
328 	return ret;
329 }
330 
331 #define FDS_IN(fds, n)		(fds->in + n)
332 #define FDS_OUT(fds, n)		(fds->out + n)
333 #define FDS_EX(fds, n)		(fds->ex + n)
334 
335 #define BITS(fds, n)	(*FDS_IN(fds, n)|*FDS_OUT(fds, n)|*FDS_EX(fds, n))
336 
337 static int max_select_fd(unsigned long n, fd_set_bits *fds)
338 {
339 	unsigned long *open_fds;
340 	unsigned long set;
341 	int max;
342 	struct fdtable *fdt;
343 
344 	/* handle last in-complete long-word first */
345 	set = ~(~0UL << (n & (__NFDBITS-1)));
346 	n /= __NFDBITS;
347 	fdt = files_fdtable(current->files);
348 	open_fds = fdt->open_fds->fds_bits+n;
349 	max = 0;
350 	if (set) {
351 		set &= BITS(fds, n);
352 		if (set) {
353 			if (!(set & ~*open_fds))
354 				goto get_max;
355 			return -EBADF;
356 		}
357 	}
358 	while (n) {
359 		open_fds--;
360 		n--;
361 		set = BITS(fds, n);
362 		if (!set)
363 			continue;
364 		if (set & ~*open_fds)
365 			return -EBADF;
366 		if (max)
367 			continue;
368 get_max:
369 		do {
370 			max++;
371 			set >>= 1;
372 		} while (set);
373 		max += n * __NFDBITS;
374 	}
375 
376 	return max;
377 }
378 
379 #define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
380 #define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
381 #define POLLEX_SET (POLLPRI)
382 
383 static inline void wait_key_set(poll_table *wait, unsigned long in,
384 				unsigned long out, unsigned long bit)
385 {
386 	if (wait) {
387 		wait->key = POLLEX_SET;
388 		if (in & bit)
389 			wait->key |= POLLIN_SET;
390 		if (out & bit)
391 			wait->key |= POLLOUT_SET;
392 	}
393 }
394 
395 int do_select(int n, fd_set_bits *fds, struct timespec *end_time)
396 {
397 	ktime_t expire, *to = NULL;
398 	struct poll_wqueues table;
399 	poll_table *wait;
400 	int retval, i, timed_out = 0;
401 	unsigned long slack = 0;
402 
403 	rcu_read_lock();
404 	retval = max_select_fd(n, fds);
405 	rcu_read_unlock();
406 
407 	if (retval < 0)
408 		return retval;
409 	n = retval;
410 
411 	poll_initwait(&table);
412 	wait = &table.pt;
413 	if (end_time && !end_time->tv_sec && !end_time->tv_nsec) {
414 		wait = NULL;
415 		timed_out = 1;
416 	}
417 
418 	if (end_time && !timed_out)
419 		slack = estimate_accuracy(end_time);
420 
421 	retval = 0;
422 	for (;;) {
423 		unsigned long *rinp, *routp, *rexp, *inp, *outp, *exp;
424 
425 		inp = fds->in; outp = fds->out; exp = fds->ex;
426 		rinp = fds->res_in; routp = fds->res_out; rexp = fds->res_ex;
427 
428 		for (i = 0; i < n; ++rinp, ++routp, ++rexp) {
429 			unsigned long in, out, ex, all_bits, bit = 1, mask, j;
430 			unsigned long res_in = 0, res_out = 0, res_ex = 0;
431 			const struct file_operations *f_op = NULL;
432 			struct file *file = NULL;
433 
434 			in = *inp++; out = *outp++; ex = *exp++;
435 			all_bits = in | out | ex;
436 			if (all_bits == 0) {
437 				i += __NFDBITS;
438 				continue;
439 			}
440 
441 			for (j = 0; j < __NFDBITS; ++j, ++i, bit <<= 1) {
442 				int fput_needed;
443 				if (i >= n)
444 					break;
445 				if (!(bit & all_bits))
446 					continue;
447 				file = fget_light(i, &fput_needed);
448 				if (file) {
449 					f_op = file->f_op;
450 					mask = DEFAULT_POLLMASK;
451 					if (f_op && f_op->poll) {
452 						wait_key_set(wait, in, out, bit);
453 						mask = (*f_op->poll)(file, wait);
454 					}
455 					fput_light(file, fput_needed);
456 					if ((mask & POLLIN_SET) && (in & bit)) {
457 						res_in |= bit;
458 						retval++;
459 						wait = NULL;
460 					}
461 					if ((mask & POLLOUT_SET) && (out & bit)) {
462 						res_out |= bit;
463 						retval++;
464 						wait = NULL;
465 					}
466 					if ((mask & POLLEX_SET) && (ex & bit)) {
467 						res_ex |= bit;
468 						retval++;
469 						wait = NULL;
470 					}
471 				}
472 			}
473 			if (res_in)
474 				*rinp = res_in;
475 			if (res_out)
476 				*routp = res_out;
477 			if (res_ex)
478 				*rexp = res_ex;
479 			cond_resched();
480 		}
481 		wait = NULL;
482 		if (retval || timed_out || signal_pending(current))
483 			break;
484 		if (table.error) {
485 			retval = table.error;
486 			break;
487 		}
488 
489 		/*
490 		 * If this is the first loop and we have a timeout
491 		 * given, then we convert to ktime_t and set the to
492 		 * pointer to the expiry value.
493 		 */
494 		if (end_time && !to) {
495 			expire = timespec_to_ktime(*end_time);
496 			to = &expire;
497 		}
498 
499 		if (!poll_schedule_timeout(&table, TASK_INTERRUPTIBLE,
500 					   to, slack))
501 			timed_out = 1;
502 	}
503 
504 	poll_freewait(&table);
505 
506 	return retval;
507 }
508 
509 /*
510  * We can actually return ERESTARTSYS instead of EINTR, but I'd
511  * like to be certain this leads to no problems. So I return
512  * EINTR just for safety.
513  *
514  * Update: ERESTARTSYS breaks at least the xview clock binary, so
515  * I'm trying ERESTARTNOHAND which restart only when you want to.
516  */
517 #define MAX_SELECT_SECONDS \
518 	((unsigned long) (MAX_SCHEDULE_TIMEOUT / HZ)-1)
519 
520 int core_sys_select(int n, fd_set __user *inp, fd_set __user *outp,
521 			   fd_set __user *exp, struct timespec *end_time)
522 {
523 	fd_set_bits fds;
524 	void *bits;
525 	int ret, max_fds;
526 	unsigned int size;
527 	struct fdtable *fdt;
528 	/* Allocate small arguments on the stack to save memory and be faster */
529 	long stack_fds[SELECT_STACK_ALLOC/sizeof(long)];
530 
531 	ret = -EINVAL;
532 	if (n < 0)
533 		goto out_nofds;
534 
535 	/* max_fds can increase, so grab it once to avoid race */
536 	rcu_read_lock();
537 	fdt = files_fdtable(current->files);
538 	max_fds = fdt->max_fds;
539 	rcu_read_unlock();
540 	if (n > max_fds)
541 		n = max_fds;
542 
543 	/*
544 	 * We need 6 bitmaps (in/out/ex for both incoming and outgoing),
545 	 * since we used fdset we need to allocate memory in units of
546 	 * long-words.
547 	 */
548 	size = FDS_BYTES(n);
549 	bits = stack_fds;
550 	if (size > sizeof(stack_fds) / 6) {
551 		/* Not enough space in on-stack array; must use kmalloc */
552 		ret = -ENOMEM;
553 		bits = kmalloc(6 * size, GFP_KERNEL);
554 		if (!bits)
555 			goto out_nofds;
556 	}
557 	fds.in      = bits;
558 	fds.out     = bits +   size;
559 	fds.ex      = bits + 2*size;
560 	fds.res_in  = bits + 3*size;
561 	fds.res_out = bits + 4*size;
562 	fds.res_ex  = bits + 5*size;
563 
564 	if ((ret = get_fd_set(n, inp, fds.in)) ||
565 	    (ret = get_fd_set(n, outp, fds.out)) ||
566 	    (ret = get_fd_set(n, exp, fds.ex)))
567 		goto out;
568 	zero_fd_set(n, fds.res_in);
569 	zero_fd_set(n, fds.res_out);
570 	zero_fd_set(n, fds.res_ex);
571 
572 	ret = do_select(n, &fds, end_time);
573 
574 	if (ret < 0)
575 		goto out;
576 	if (!ret) {
577 		ret = -ERESTARTNOHAND;
578 		if (signal_pending(current))
579 			goto out;
580 		ret = 0;
581 	}
582 
583 	if (set_fd_set(n, inp, fds.res_in) ||
584 	    set_fd_set(n, outp, fds.res_out) ||
585 	    set_fd_set(n, exp, fds.res_ex))
586 		ret = -EFAULT;
587 
588 out:
589 	if (bits != stack_fds)
590 		kfree(bits);
591 out_nofds:
592 	return ret;
593 }
594 
595 SYSCALL_DEFINE5(select, int, n, fd_set __user *, inp, fd_set __user *, outp,
596 		fd_set __user *, exp, struct timeval __user *, tvp)
597 {
598 	struct timespec end_time, *to = NULL;
599 	struct timeval tv;
600 	int ret;
601 
602 	if (tvp) {
603 		if (copy_from_user(&tv, tvp, sizeof(tv)))
604 			return -EFAULT;
605 
606 		to = &end_time;
607 		if (poll_select_set_timeout(to,
608 				tv.tv_sec + (tv.tv_usec / USEC_PER_SEC),
609 				(tv.tv_usec % USEC_PER_SEC) * NSEC_PER_USEC))
610 			return -EINVAL;
611 	}
612 
613 	ret = core_sys_select(n, inp, outp, exp, to);
614 	ret = poll_select_copy_remaining(&end_time, tvp, 1, ret);
615 
616 	return ret;
617 }
618 
619 #ifdef HAVE_SET_RESTORE_SIGMASK
620 static long do_pselect(int n, fd_set __user *inp, fd_set __user *outp,
621 		       fd_set __user *exp, struct timespec __user *tsp,
622 		       const sigset_t __user *sigmask, size_t sigsetsize)
623 {
624 	sigset_t ksigmask, sigsaved;
625 	struct timespec ts, end_time, *to = NULL;
626 	int ret;
627 
628 	if (tsp) {
629 		if (copy_from_user(&ts, tsp, sizeof(ts)))
630 			return -EFAULT;
631 
632 		to = &end_time;
633 		if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
634 			return -EINVAL;
635 	}
636 
637 	if (sigmask) {
638 		/* XXX: Don't preclude handling different sized sigset_t's.  */
639 		if (sigsetsize != sizeof(sigset_t))
640 			return -EINVAL;
641 		if (copy_from_user(&ksigmask, sigmask, sizeof(ksigmask)))
642 			return -EFAULT;
643 
644 		sigdelsetmask(&ksigmask, sigmask(SIGKILL)|sigmask(SIGSTOP));
645 		sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
646 	}
647 
648 	ret = core_sys_select(n, inp, outp, exp, to);
649 	ret = poll_select_copy_remaining(&end_time, tsp, 0, ret);
650 
651 	if (ret == -ERESTARTNOHAND) {
652 		/*
653 		 * Don't restore the signal mask yet. Let do_signal() deliver
654 		 * the signal on the way back to userspace, before the signal
655 		 * mask is restored.
656 		 */
657 		if (sigmask) {
658 			memcpy(&current->saved_sigmask, &sigsaved,
659 					sizeof(sigsaved));
660 			set_restore_sigmask();
661 		}
662 	} else if (sigmask)
663 		sigprocmask(SIG_SETMASK, &sigsaved, NULL);
664 
665 	return ret;
666 }
667 
668 /*
669  * Most architectures can't handle 7-argument syscalls. So we provide a
670  * 6-argument version where the sixth argument is a pointer to a structure
671  * which has a pointer to the sigset_t itself followed by a size_t containing
672  * the sigset size.
673  */
674 SYSCALL_DEFINE6(pselect6, int, n, fd_set __user *, inp, fd_set __user *, outp,
675 		fd_set __user *, exp, struct timespec __user *, tsp,
676 		void __user *, sig)
677 {
678 	size_t sigsetsize = 0;
679 	sigset_t __user *up = NULL;
680 
681 	if (sig) {
682 		if (!access_ok(VERIFY_READ, sig, sizeof(void *)+sizeof(size_t))
683 		    || __get_user(up, (sigset_t __user * __user *)sig)
684 		    || __get_user(sigsetsize,
685 				(size_t __user *)(sig+sizeof(void *))))
686 			return -EFAULT;
687 	}
688 
689 	return do_pselect(n, inp, outp, exp, tsp, up, sigsetsize);
690 }
691 #endif /* HAVE_SET_RESTORE_SIGMASK */
692 
693 struct poll_list {
694 	struct poll_list *next;
695 	int len;
696 	struct pollfd entries[0];
697 };
698 
699 #define POLLFD_PER_PAGE  ((PAGE_SIZE-sizeof(struct poll_list)) / sizeof(struct pollfd))
700 
701 /*
702  * Fish for pollable events on the pollfd->fd file descriptor. We're only
703  * interested in events matching the pollfd->events mask, and the result
704  * matching that mask is both recorded in pollfd->revents and returned. The
705  * pwait poll_table will be used by the fd-provided poll handler for waiting,
706  * if non-NULL.
707  */
708 static inline unsigned int do_pollfd(struct pollfd *pollfd, poll_table *pwait)
709 {
710 	unsigned int mask;
711 	int fd;
712 
713 	mask = 0;
714 	fd = pollfd->fd;
715 	if (fd >= 0) {
716 		int fput_needed;
717 		struct file * file;
718 
719 		file = fget_light(fd, &fput_needed);
720 		mask = POLLNVAL;
721 		if (file != NULL) {
722 			mask = DEFAULT_POLLMASK;
723 			if (file->f_op && file->f_op->poll) {
724 				if (pwait)
725 					pwait->key = pollfd->events |
726 							POLLERR | POLLHUP;
727 				mask = file->f_op->poll(file, pwait);
728 			}
729 			/* Mask out unneeded events. */
730 			mask &= pollfd->events | POLLERR | POLLHUP;
731 			fput_light(file, fput_needed);
732 		}
733 	}
734 	pollfd->revents = mask;
735 
736 	return mask;
737 }
738 
739 static int do_poll(unsigned int nfds,  struct poll_list *list,
740 		   struct poll_wqueues *wait, struct timespec *end_time)
741 {
742 	poll_table* pt = &wait->pt;
743 	ktime_t expire, *to = NULL;
744 	int timed_out = 0, count = 0;
745 	unsigned long slack = 0;
746 
747 	/* Optimise the no-wait case */
748 	if (end_time && !end_time->tv_sec && !end_time->tv_nsec) {
749 		pt = NULL;
750 		timed_out = 1;
751 	}
752 
753 	if (end_time && !timed_out)
754 		slack = estimate_accuracy(end_time);
755 
756 	for (;;) {
757 		struct poll_list *walk;
758 
759 		for (walk = list; walk != NULL; walk = walk->next) {
760 			struct pollfd * pfd, * pfd_end;
761 
762 			pfd = walk->entries;
763 			pfd_end = pfd + walk->len;
764 			for (; pfd != pfd_end; pfd++) {
765 				/*
766 				 * Fish for events. If we found one, record it
767 				 * and kill the poll_table, so we don't
768 				 * needlessly register any other waiters after
769 				 * this. They'll get immediately deregistered
770 				 * when we break out and return.
771 				 */
772 				if (do_pollfd(pfd, pt)) {
773 					count++;
774 					pt = NULL;
775 				}
776 			}
777 		}
778 		/*
779 		 * All waiters have already been registered, so don't provide
780 		 * a poll_table to them on the next loop iteration.
781 		 */
782 		pt = NULL;
783 		if (!count) {
784 			count = wait->error;
785 			if (signal_pending(current))
786 				count = -EINTR;
787 		}
788 		if (count || timed_out)
789 			break;
790 
791 		/*
792 		 * If this is the first loop and we have a timeout
793 		 * given, then we convert to ktime_t and set the to
794 		 * pointer to the expiry value.
795 		 */
796 		if (end_time && !to) {
797 			expire = timespec_to_ktime(*end_time);
798 			to = &expire;
799 		}
800 
801 		if (!poll_schedule_timeout(wait, TASK_INTERRUPTIBLE, to, slack))
802 			timed_out = 1;
803 	}
804 	return count;
805 }
806 
807 #define N_STACK_PPS ((sizeof(stack_pps) - sizeof(struct poll_list))  / \
808 			sizeof(struct pollfd))
809 
810 int do_sys_poll(struct pollfd __user *ufds, unsigned int nfds,
811 		struct timespec *end_time)
812 {
813 	struct poll_wqueues table;
814  	int err = -EFAULT, fdcount, len, size;
815 	/* Allocate small arguments on the stack to save memory and be
816 	   faster - use long to make sure the buffer is aligned properly
817 	   on 64 bit archs to avoid unaligned access */
818 	long stack_pps[POLL_STACK_ALLOC/sizeof(long)];
819 	struct poll_list *const head = (struct poll_list *)stack_pps;
820  	struct poll_list *walk = head;
821  	unsigned long todo = nfds;
822 
823 	if (nfds > current->signal->rlim[RLIMIT_NOFILE].rlim_cur)
824 		return -EINVAL;
825 
826 	len = min_t(unsigned int, nfds, N_STACK_PPS);
827 	for (;;) {
828 		walk->next = NULL;
829 		walk->len = len;
830 		if (!len)
831 			break;
832 
833 		if (copy_from_user(walk->entries, ufds + nfds-todo,
834 					sizeof(struct pollfd) * walk->len))
835 			goto out_fds;
836 
837 		todo -= walk->len;
838 		if (!todo)
839 			break;
840 
841 		len = min(todo, POLLFD_PER_PAGE);
842 		size = sizeof(struct poll_list) + sizeof(struct pollfd) * len;
843 		walk = walk->next = kmalloc(size, GFP_KERNEL);
844 		if (!walk) {
845 			err = -ENOMEM;
846 			goto out_fds;
847 		}
848 	}
849 
850 	poll_initwait(&table);
851 	fdcount = do_poll(nfds, head, &table, end_time);
852 	poll_freewait(&table);
853 
854 	for (walk = head; walk; walk = walk->next) {
855 		struct pollfd *fds = walk->entries;
856 		int j;
857 
858 		for (j = 0; j < walk->len; j++, ufds++)
859 			if (__put_user(fds[j].revents, &ufds->revents))
860 				goto out_fds;
861   	}
862 
863 	err = fdcount;
864 out_fds:
865 	walk = head->next;
866 	while (walk) {
867 		struct poll_list *pos = walk;
868 		walk = walk->next;
869 		kfree(pos);
870 	}
871 
872 	return err;
873 }
874 
875 static long do_restart_poll(struct restart_block *restart_block)
876 {
877 	struct pollfd __user *ufds = restart_block->poll.ufds;
878 	int nfds = restart_block->poll.nfds;
879 	struct timespec *to = NULL, end_time;
880 	int ret;
881 
882 	if (restart_block->poll.has_timeout) {
883 		end_time.tv_sec = restart_block->poll.tv_sec;
884 		end_time.tv_nsec = restart_block->poll.tv_nsec;
885 		to = &end_time;
886 	}
887 
888 	ret = do_sys_poll(ufds, nfds, to);
889 
890 	if (ret == -EINTR) {
891 		restart_block->fn = do_restart_poll;
892 		ret = -ERESTART_RESTARTBLOCK;
893 	}
894 	return ret;
895 }
896 
897 SYSCALL_DEFINE3(poll, struct pollfd __user *, ufds, unsigned int, nfds,
898 		long, timeout_msecs)
899 {
900 	struct timespec end_time, *to = NULL;
901 	int ret;
902 
903 	if (timeout_msecs >= 0) {
904 		to = &end_time;
905 		poll_select_set_timeout(to, timeout_msecs / MSEC_PER_SEC,
906 			NSEC_PER_MSEC * (timeout_msecs % MSEC_PER_SEC));
907 	}
908 
909 	ret = do_sys_poll(ufds, nfds, to);
910 
911 	if (ret == -EINTR) {
912 		struct restart_block *restart_block;
913 
914 		restart_block = &current_thread_info()->restart_block;
915 		restart_block->fn = do_restart_poll;
916 		restart_block->poll.ufds = ufds;
917 		restart_block->poll.nfds = nfds;
918 
919 		if (timeout_msecs >= 0) {
920 			restart_block->poll.tv_sec = end_time.tv_sec;
921 			restart_block->poll.tv_nsec = end_time.tv_nsec;
922 			restart_block->poll.has_timeout = 1;
923 		} else
924 			restart_block->poll.has_timeout = 0;
925 
926 		ret = -ERESTART_RESTARTBLOCK;
927 	}
928 	return ret;
929 }
930 
931 #ifdef HAVE_SET_RESTORE_SIGMASK
932 SYSCALL_DEFINE5(ppoll, struct pollfd __user *, ufds, unsigned int, nfds,
933 		struct timespec __user *, tsp, const sigset_t __user *, sigmask,
934 		size_t, sigsetsize)
935 {
936 	sigset_t ksigmask, sigsaved;
937 	struct timespec ts, end_time, *to = NULL;
938 	int ret;
939 
940 	if (tsp) {
941 		if (copy_from_user(&ts, tsp, sizeof(ts)))
942 			return -EFAULT;
943 
944 		to = &end_time;
945 		if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec))
946 			return -EINVAL;
947 	}
948 
949 	if (sigmask) {
950 		/* XXX: Don't preclude handling different sized sigset_t's.  */
951 		if (sigsetsize != sizeof(sigset_t))
952 			return -EINVAL;
953 		if (copy_from_user(&ksigmask, sigmask, sizeof(ksigmask)))
954 			return -EFAULT;
955 
956 		sigdelsetmask(&ksigmask, sigmask(SIGKILL)|sigmask(SIGSTOP));
957 		sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
958 	}
959 
960 	ret = do_sys_poll(ufds, nfds, to);
961 
962 	/* We can restart this syscall, usually */
963 	if (ret == -EINTR) {
964 		/*
965 		 * Don't restore the signal mask yet. Let do_signal() deliver
966 		 * the signal on the way back to userspace, before the signal
967 		 * mask is restored.
968 		 */
969 		if (sigmask) {
970 			memcpy(&current->saved_sigmask, &sigsaved,
971 					sizeof(sigsaved));
972 			set_restore_sigmask();
973 		}
974 		ret = -ERESTARTNOHAND;
975 	} else if (sigmask)
976 		sigprocmask(SIG_SETMASK, &sigsaved, NULL);
977 
978 	ret = poll_select_copy_remaining(&end_time, tsp, 0, ret);
979 
980 	return ret;
981 }
982 #endif /* HAVE_SET_RESTORE_SIGMASK */
983