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/slab.h>
18 #include <linux/smp_lock.h>
19 #include <linux/poll.h>
20 #include <linux/personality.h> /* for STICKY_TIMEOUTS */
21 #include <linux/file.h>
22 
23 #include <asm/uaccess.h>
24 
25 #define ROUND_UP(x,y) (((x)+(y)-1)/(y))
26 #define DEFAULT_POLLMASK (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM)
27 
28 struct poll_table_entry {
29 	struct file * filp;
30 	wait_queue_t wait;
31 	wait_queue_head_t * wait_address;
32 };
33 
34 struct poll_table_page {
35 	struct poll_table_page * next;
36 	struct poll_table_entry * entry;
37 	struct poll_table_entry entries[0];
38 };
39 
40 #define POLL_TABLE_FULL(table) \
41 	((unsigned long)((table)->entry+1) > PAGE_SIZE + (unsigned long)(table))
42 
43 /*
44  * Ok, Peter made a complicated, but straightforward multiple_wait() function.
45  * I have rewritten this, taking some shortcuts: This code may not be easy to
46  * follow, but it should be free of race-conditions, and it's practical. If you
47  * understand what I'm doing here, then you understand how the linux
48  * sleep/wakeup mechanism works.
49  *
50  * Two very simple procedures, poll_wait() and poll_freewait() make all the
51  * work.  poll_wait() is an inline-function defined in <linux/poll.h>,
52  * as all select/poll functions have to call it to add an entry to the
53  * poll table.
54  */
55 
poll_freewait(poll_table * pt)56 void poll_freewait(poll_table* pt)
57 {
58 	struct poll_table_page * p = pt->table;
59 	while (p) {
60 		struct poll_table_entry * entry;
61 		struct poll_table_page *old;
62 
63 		entry = p->entry;
64 		do {
65 			entry--;
66 			remove_wait_queue(entry->wait_address,&entry->wait);
67 			fput(entry->filp);
68 		} while (entry > p->entries);
69 		old = p;
70 		p = p->next;
71 		free_page((unsigned long) old);
72 	}
73 }
74 
__pollwait(struct file * filp,wait_queue_head_t * wait_address,poll_table * p)75 void __pollwait(struct file * filp, wait_queue_head_t * wait_address, poll_table *p)
76 {
77 	struct poll_table_page *table = p->table;
78 
79 	if (!table || POLL_TABLE_FULL(table)) {
80 		struct poll_table_page *new_table;
81 
82 		new_table = (struct poll_table_page *) __get_free_page(GFP_KERNEL);
83 		if (!new_table) {
84 			p->error = -ENOMEM;
85 			__set_current_state(TASK_RUNNING);
86 			return;
87 		}
88 		new_table->entry = new_table->entries;
89 		new_table->next = table;
90 		p->table = new_table;
91 		table = new_table;
92 	}
93 
94 	/* Add a new entry */
95 	{
96 		struct poll_table_entry * entry = table->entry;
97 		table->entry = entry+1;
98 	 	get_file(filp);
99 	 	entry->filp = filp;
100 		entry->wait_address = wait_address;
101 		init_waitqueue_entry(&entry->wait, current);
102 		add_wait_queue(wait_address,&entry->wait);
103 	}
104 }
105 
106 #define __IN(fds, n)		(fds->in + n)
107 #define __OUT(fds, n)		(fds->out + n)
108 #define __EX(fds, n)		(fds->ex + n)
109 #define __RES_IN(fds, n)	(fds->res_in + n)
110 #define __RES_OUT(fds, n)	(fds->res_out + n)
111 #define __RES_EX(fds, n)	(fds->res_ex + n)
112 
113 #define BITS(fds, n)		(*__IN(fds, n)|*__OUT(fds, n)|*__EX(fds, n))
114 
max_select_fd(unsigned long n,fd_set_bits * fds)115 static int max_select_fd(unsigned long n, fd_set_bits *fds)
116 {
117 	unsigned long *open_fds;
118 	unsigned long set;
119 	int max;
120 
121 	/* handle last in-complete long-word first */
122 	set = ~(~0UL << (n & (__NFDBITS-1)));
123 	n /= __NFDBITS;
124 	open_fds = current->files->open_fds->fds_bits+n;
125 	max = 0;
126 	if (set) {
127 		set &= BITS(fds, n);
128 		if (set) {
129 			if (!(set & ~*open_fds))
130 				goto get_max;
131 			return -EBADF;
132 		}
133 	}
134 	while (n) {
135 		open_fds--;
136 		n--;
137 		set = BITS(fds, n);
138 		if (!set)
139 			continue;
140 		if (set & ~*open_fds)
141 			return -EBADF;
142 		if (max)
143 			continue;
144 get_max:
145 		do {
146 			max++;
147 			set >>= 1;
148 		} while (set);
149 		max += n * __NFDBITS;
150 	}
151 
152 	return max;
153 }
154 
155 #define BIT(i)		(1UL << ((i)&(__NFDBITS-1)))
156 #define MEM(i,m)	((m)+(unsigned)(i)/__NFDBITS)
157 #define ISSET(i,m)	(((i)&*(m)) != 0)
158 #define SET(i,m)	(*(m) |= (i))
159 
160 #define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
161 #define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
162 #define POLLEX_SET (POLLPRI)
163 
do_select(int n,fd_set_bits * fds,long * timeout)164 int do_select(int n, fd_set_bits *fds, long *timeout)
165 {
166 	poll_table table, *wait;
167 	int retval, i, off;
168 	long __timeout = *timeout;
169 
170  	read_lock(&current->files->file_lock);
171 	retval = max_select_fd(n, fds);
172 	read_unlock(&current->files->file_lock);
173 
174 	if (retval < 0)
175 		return retval;
176 	n = retval;
177 
178 	poll_initwait(&table);
179 	wait = &table;
180 	if (!__timeout)
181 		wait = NULL;
182 	retval = 0;
183 	for (;;) {
184 		set_current_state(TASK_INTERRUPTIBLE);
185 		for (i = 0 ; i < n; i++) {
186 			unsigned long bit = BIT(i);
187 			unsigned long mask;
188 			struct file *file;
189 
190 			off = i / __NFDBITS;
191 			if (!(bit & BITS(fds, off)))
192 				continue;
193 			file = fget(i);
194 			mask = POLLNVAL;
195 			if (file) {
196 				mask = DEFAULT_POLLMASK;
197 				if (file->f_op && file->f_op->poll)
198 					mask = file->f_op->poll(file, wait);
199 				fput(file);
200 			}
201 			if ((mask & POLLIN_SET) && ISSET(bit, __IN(fds,off))) {
202 				SET(bit, __RES_IN(fds,off));
203 				retval++;
204 				wait = NULL;
205 			}
206 			if ((mask & POLLOUT_SET) && ISSET(bit, __OUT(fds,off))) {
207 				SET(bit, __RES_OUT(fds,off));
208 				retval++;
209 				wait = NULL;
210 			}
211 			if ((mask & POLLEX_SET) && ISSET(bit, __EX(fds,off))) {
212 				SET(bit, __RES_EX(fds,off));
213 				retval++;
214 				wait = NULL;
215 			}
216 		}
217 		wait = NULL;
218 		if (retval || !__timeout || signal_pending(current))
219 			break;
220 		if(table.error) {
221 			retval = table.error;
222 			break;
223 		}
224 		__timeout = schedule_timeout(__timeout);
225 	}
226 	current->state = TASK_RUNNING;
227 
228 	poll_freewait(&table);
229 
230 	/*
231 	 * Up-to-date the caller timeout.
232 	 */
233 	*timeout = __timeout;
234 	return retval;
235 }
236 
select_bits_alloc(int size)237 static void *select_bits_alloc(int size)
238 {
239 	return kmalloc(6 * size, GFP_KERNEL);
240 }
241 
select_bits_free(void * bits,int size)242 static void select_bits_free(void *bits, int size)
243 {
244 	kfree(bits);
245 }
246 
247 /*
248  * We can actually return ERESTARTSYS instead of EINTR, but I'd
249  * like to be certain this leads to no problems. So I return
250  * EINTR just for safety.
251  *
252  * Update: ERESTARTSYS breaks at least the xview clock binary, so
253  * I'm trying ERESTARTNOHAND which restart only when you want to.
254  */
255 #define MAX_SELECT_SECONDS \
256 	((unsigned long) (MAX_SCHEDULE_TIMEOUT / HZ)-1)
257 
258 asmlinkage long
sys_select(int n,fd_set * inp,fd_set * outp,fd_set * exp,struct timeval * tvp)259 sys_select(int n, fd_set *inp, fd_set *outp, fd_set *exp, struct timeval *tvp)
260 {
261 	fd_set_bits fds;
262 	char *bits;
263 	long timeout;
264 	int ret, size, max_fdset;
265 
266 	timeout = MAX_SCHEDULE_TIMEOUT;
267 	if (tvp) {
268 		time_t sec, usec;
269 
270 		if ((ret = verify_area(VERIFY_READ, tvp, sizeof(*tvp)))
271 		    || (ret = __get_user(sec, &tvp->tv_sec))
272 		    || (ret = __get_user(usec, &tvp->tv_usec)))
273 			goto out_nofds;
274 
275 		ret = -EINVAL;
276 		if (sec < 0 || usec < 0)
277 			goto out_nofds;
278 
279 		if ((unsigned long) sec < MAX_SELECT_SECONDS) {
280 			timeout = ROUND_UP(usec, 1000000/HZ);
281 			timeout += sec * (unsigned long) HZ;
282 		}
283 	}
284 
285 	ret = -EINVAL;
286 	if (n < 0)
287 		goto out_nofds;
288 
289 	/* max_fdset can increase, so grab it once to avoid race */
290 	max_fdset = current->files->max_fdset;
291 	if (n > max_fdset)
292 		n = max_fdset;
293 
294 	/*
295 	 * We need 6 bitmaps (in/out/ex for both incoming and outgoing),
296 	 * since we used fdset we need to allocate memory in units of
297 	 * long-words.
298 	 */
299 	ret = -ENOMEM;
300 	size = FDS_BYTES(n);
301 	bits = select_bits_alloc(size);
302 	if (!bits)
303 		goto out_nofds;
304 	fds.in      = (unsigned long *)  bits;
305 	fds.out     = (unsigned long *) (bits +   size);
306 	fds.ex      = (unsigned long *) (bits + 2*size);
307 	fds.res_in  = (unsigned long *) (bits + 3*size);
308 	fds.res_out = (unsigned long *) (bits + 4*size);
309 	fds.res_ex  = (unsigned long *) (bits + 5*size);
310 
311 	if ((ret = get_fd_set(n, inp, fds.in)) ||
312 	    (ret = get_fd_set(n, outp, fds.out)) ||
313 	    (ret = get_fd_set(n, exp, fds.ex)))
314 		goto out;
315 	zero_fd_set(n, fds.res_in);
316 	zero_fd_set(n, fds.res_out);
317 	zero_fd_set(n, fds.res_ex);
318 
319 	ret = do_select(n, &fds, &timeout);
320 
321 	if (tvp && !(current->personality & STICKY_TIMEOUTS)) {
322 		time_t sec = 0, usec = 0;
323 		if (timeout) {
324 			sec = timeout / HZ;
325 			usec = timeout % HZ;
326 			usec *= (1000000/HZ);
327 		}
328 		put_user(sec, &tvp->tv_sec);
329 		put_user(usec, &tvp->tv_usec);
330 	}
331 
332 	if (ret < 0)
333 		goto out;
334 	if (!ret) {
335 		ret = -ERESTARTNOHAND;
336 		if (signal_pending(current))
337 			goto out;
338 		ret = 0;
339 	}
340 
341 	set_fd_set(n, inp, fds.res_in);
342 	set_fd_set(n, outp, fds.res_out);
343 	set_fd_set(n, exp, fds.res_ex);
344 
345 out:
346 	select_bits_free(bits, size);
347 out_nofds:
348 	return ret;
349 }
350 
351 #define POLLFD_PER_PAGE  ((PAGE_SIZE) / sizeof(struct pollfd))
352 
do_pollfd(unsigned int num,struct pollfd * fdpage,poll_table ** pwait,int * count)353 static void do_pollfd(unsigned int num, struct pollfd * fdpage,
354 	poll_table ** pwait, int *count)
355 {
356 	int i;
357 
358 	for (i = 0; i < num; i++) {
359 		int fd;
360 		unsigned int mask;
361 		struct pollfd *fdp;
362 
363 		mask = 0;
364 		fdp = fdpage+i;
365 		fd = fdp->fd;
366 		if (fd >= 0) {
367 			struct file * file = fget(fd);
368 			mask = POLLNVAL;
369 			if (file != NULL) {
370 				mask = DEFAULT_POLLMASK;
371 				if (file->f_op && file->f_op->poll)
372 					mask = file->f_op->poll(file, *pwait);
373 				mask &= fdp->events | POLLERR | POLLHUP;
374 				fput(file);
375 			}
376 			if (mask) {
377 				*pwait = NULL;
378 				(*count)++;
379 			}
380 		}
381 		fdp->revents = mask;
382 	}
383 }
384 
do_poll(unsigned int nfds,unsigned int nchunks,unsigned int nleft,struct pollfd * fds[],poll_table * wait,long timeout)385 static int do_poll(unsigned int nfds, unsigned int nchunks, unsigned int nleft,
386 	struct pollfd *fds[], poll_table *wait, long timeout)
387 {
388 	int count;
389 	poll_table* pt = wait;
390 
391 	for (;;) {
392 		unsigned int i;
393 
394 		set_current_state(TASK_INTERRUPTIBLE);
395 		count = 0;
396 		for (i=0; i < nchunks; i++)
397 			do_pollfd(POLLFD_PER_PAGE, fds[i], &pt, &count);
398 		if (nleft)
399 			do_pollfd(nleft, fds[nchunks], &pt, &count);
400 		pt = NULL;
401 		if (count || !timeout || signal_pending(current))
402 			break;
403 		count = wait->error;
404 		if (count)
405 			break;
406 		timeout = schedule_timeout(timeout);
407 	}
408 	current->state = TASK_RUNNING;
409 	return count;
410 }
411 
sys_poll(struct pollfd * ufds,unsigned int nfds,long timeout)412 asmlinkage long sys_poll(struct pollfd * ufds, unsigned int nfds, long timeout)
413 {
414 	int i, j, fdcount, err;
415 	struct pollfd **fds;
416 	poll_table table, *wait;
417 	int nchunks, nleft;
418 
419 	/* Do a sanity check on nfds ... */
420 	if (nfds > current->files->max_fdset && nfds > OPEN_MAX)
421 		return -EINVAL;
422 
423 	if (timeout) {
424 		/* Careful about overflow in the intermediate values */
425 		if ((unsigned long) timeout < MAX_SCHEDULE_TIMEOUT / HZ)
426 			timeout = (unsigned long)(timeout*HZ+999)/1000+1;
427 		else /* Negative or overflow */
428 			timeout = MAX_SCHEDULE_TIMEOUT;
429 	}
430 
431 	poll_initwait(&table);
432 	wait = &table;
433 	if (!timeout)
434 		wait = NULL;
435 
436 	err = -ENOMEM;
437 	fds = NULL;
438 	if (nfds != 0) {
439 		fds = (struct pollfd **)kmalloc(
440 			(1 + (nfds - 1) / POLLFD_PER_PAGE) * sizeof(struct pollfd *),
441 			GFP_KERNEL);
442 		if (fds == NULL)
443 			goto out;
444 	}
445 
446 	nchunks = 0;
447 	nleft = nfds;
448 	while (nleft > POLLFD_PER_PAGE) { /* allocate complete PAGE_SIZE chunks */
449 		fds[nchunks] = (struct pollfd *)__get_free_page(GFP_KERNEL);
450 		if (fds[nchunks] == NULL)
451 			goto out_fds;
452 		nchunks++;
453 		nleft -= POLLFD_PER_PAGE;
454 	}
455 	if (nleft) { /* allocate last PAGE_SIZE chunk, only nleft elements used */
456 		fds[nchunks] = (struct pollfd *)__get_free_page(GFP_KERNEL);
457 		if (fds[nchunks] == NULL)
458 			goto out_fds;
459 	}
460 
461 	err = -EFAULT;
462 	for (i=0; i < nchunks; i++)
463 		if (copy_from_user(fds[i], ufds + i*POLLFD_PER_PAGE, PAGE_SIZE))
464 			goto out_fds1;
465 	if (nleft) {
466 		if (copy_from_user(fds[nchunks], ufds + nchunks*POLLFD_PER_PAGE,
467 				nleft * sizeof(struct pollfd)))
468 			goto out_fds1;
469 	}
470 
471 	fdcount = do_poll(nfds, nchunks, nleft, fds, wait, timeout);
472 
473 	/* OK, now copy the revents fields back to user space. */
474 	for(i=0; i < nchunks; i++)
475 		for (j=0; j < POLLFD_PER_PAGE; j++, ufds++)
476 			__put_user((fds[i] + j)->revents, &ufds->revents);
477 	if (nleft)
478 		for (j=0; j < nleft; j++, ufds++)
479 			__put_user((fds[nchunks] + j)->revents, &ufds->revents);
480 
481 	err = fdcount;
482 	if (!fdcount && signal_pending(current))
483 		err = -EINTR;
484 
485 out_fds1:
486 	if (nleft)
487 		free_page((unsigned long)(fds[nchunks]));
488 out_fds:
489 	for (i=0; i < nchunks; i++)
490 		free_page((unsigned long)(fds[i]));
491 	if (nfds != 0)
492 		kfree(fds);
493 out:
494 	poll_freewait(&table);
495 	return err;
496 }
497