xref: /freebsd/sys/kern/sys_generic.c (revision daf1cffce2e07931f27c6c6998652e90df6ba87e)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)sys_generic.c	8.5 (Berkeley) 1/21/94
39  * $FreeBSD$
40  */
41 
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/filedesc.h>
48 #include <sys/filio.h>
49 #include <sys/fcntl.h>
50 #include <sys/file.h>
51 #include <sys/proc.h>
52 #include <sys/signalvar.h>
53 #include <sys/socketvar.h>
54 #include <sys/uio.h>
55 #include <sys/kernel.h>
56 #include <sys/malloc.h>
57 #include <sys/poll.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysent.h>
60 #ifdef KTRACE
61 #include <sys/ktrace.h>
62 #endif
63 
64 #include <machine/limits.h>
65 
66 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
67 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
68 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
69 
70 static int	pollscan __P((struct proc *, struct pollfd *, int));
71 static int	selscan __P((struct proc *, fd_mask **, fd_mask **, int));
72 static struct file* getfp __P((struct filedesc *, int, int));
73 static int	dofileread __P((struct proc *, struct file *, int, void *,
74 		    size_t, off_t, int));
75 static int	dofilewrite __P((struct proc *, struct file *, int,
76 		    const void *, size_t, off_t, int));
77 
78 static struct file*
79 getfp(fdp, fd, flag)
80 	struct filedesc* fdp;
81 	int fd, flag;
82 {
83 	struct file* fp;
84 
85 	if (((u_int)fd) >= fdp->fd_nfiles ||
86 	    (fp = fdp->fd_ofiles[fd]) == NULL ||
87 	    (fp->f_flag & flag) == 0)
88 		return (NULL);
89 	return (fp);
90 }
91 
92 /*
93  * Read system call.
94  */
95 #ifndef _SYS_SYSPROTO_H_
96 struct read_args {
97 	int	fd;
98 	void	*buf;
99 	size_t	nbyte;
100 };
101 #endif
102 int
103 read(p, uap)
104 	struct proc *p;
105 	register struct read_args *uap;
106 {
107 	register struct file *fp;
108 
109 	if ((fp = getfp(p->p_fd, uap->fd, FREAD)) == NULL)
110 		return (EBADF);
111 	return (dofileread(p, fp, uap->fd, uap->buf, uap->nbyte, (off_t)-1, 0));
112 }
113 
114 /*
115  * Pread system call
116  */
117 #ifndef _SYS_SYSPROTO_H_
118 struct pread_args {
119 	int	fd;
120 	void	*buf;
121 	size_t	nbyte;
122 	int	pad;
123 	off_t	offset;
124 };
125 #endif
126 int
127 pread(p, uap)
128 	struct proc *p;
129 	register struct pread_args *uap;
130 {
131 	register struct file *fp;
132 
133 	if ((fp = getfp(p->p_fd, uap->fd, FREAD)) == NULL)
134 		return (EBADF);
135 	if (fp->f_type != DTYPE_VNODE)
136 		return (ESPIPE);
137 	return (dofileread(p, fp, uap->fd, uap->buf, uap->nbyte, uap->offset,
138 	    FOF_OFFSET));
139 }
140 
141 /*
142  * Code common for read and pread
143  */
144 int
145 dofileread(p, fp, fd, buf, nbyte, offset, flags)
146 	struct proc *p;
147 	struct file *fp;
148 	int fd, flags;
149 	void *buf;
150 	size_t nbyte;
151 	off_t offset;
152 {
153 	struct uio auio;
154 	struct iovec aiov;
155 	long cnt, error = 0;
156 #ifdef KTRACE
157 	struct iovec ktriov;
158 #endif
159 
160 	aiov.iov_base = (caddr_t)buf;
161 	aiov.iov_len = nbyte;
162 	auio.uio_iov = &aiov;
163 	auio.uio_iovcnt = 1;
164 	auio.uio_offset = offset;
165 	if (nbyte > INT_MAX)
166 		return (EINVAL);
167 	auio.uio_resid = nbyte;
168 	auio.uio_rw = UIO_READ;
169 	auio.uio_segflg = UIO_USERSPACE;
170 	auio.uio_procp = p;
171 #ifdef KTRACE
172 	/*
173 	 * if tracing, save a copy of iovec
174 	 */
175 	if (KTRPOINT(p, KTR_GENIO))
176 		ktriov = aiov;
177 #endif
178 	cnt = nbyte;
179 	if ((error = fo_read(fp, &auio, fp->f_cred, flags, p)))
180 		if (auio.uio_resid != cnt && (error == ERESTART ||
181 		    error == EINTR || error == EWOULDBLOCK))
182 			error = 0;
183 	cnt -= auio.uio_resid;
184 #ifdef KTRACE
185 	if (KTRPOINT(p, KTR_GENIO) && error == 0)
186 		ktrgenio(p->p_tracep, fd, UIO_READ, &ktriov, cnt, error);
187 #endif
188 	p->p_retval[0] = cnt;
189 	return (error);
190 }
191 
192 /*
193  * Scatter read system call.
194  */
195 #ifndef _SYS_SYSPROTO_H_
196 struct readv_args {
197 	int	fd;
198 	struct	iovec *iovp;
199 	u_int	iovcnt;
200 };
201 #endif
202 int
203 readv(p, uap)
204 	struct proc *p;
205 	register struct readv_args *uap;
206 {
207 	register struct file *fp;
208 	register struct filedesc *fdp = p->p_fd;
209 	struct uio auio;
210 	register struct iovec *iov;
211 	struct iovec *needfree;
212 	struct iovec aiov[UIO_SMALLIOV];
213 	long i, cnt, error = 0;
214 	u_int iovlen;
215 #ifdef KTRACE
216 	struct iovec *ktriov = NULL;
217 #endif
218 
219 	if ((fp = getfp(fdp, uap->fd, FREAD)) == NULL)
220 		return (EBADF);
221 	/* note: can't use iovlen until iovcnt is validated */
222 	iovlen = uap->iovcnt * sizeof (struct iovec);
223 	if (uap->iovcnt > UIO_SMALLIOV) {
224 		if (uap->iovcnt > UIO_MAXIOV)
225 			return (EINVAL);
226 		MALLOC(iov, struct iovec *, iovlen, M_IOV, M_WAITOK);
227 		needfree = iov;
228 	} else {
229 		iov = aiov;
230 		needfree = NULL;
231 	}
232 	auio.uio_iov = iov;
233 	auio.uio_iovcnt = uap->iovcnt;
234 	auio.uio_rw = UIO_READ;
235 	auio.uio_segflg = UIO_USERSPACE;
236 	auio.uio_procp = p;
237 	auio.uio_offset = -1;
238 	if ((error = copyin((caddr_t)uap->iovp, (caddr_t)iov, iovlen)))
239 		goto done;
240 	auio.uio_resid = 0;
241 	for (i = 0; i < uap->iovcnt; i++) {
242 		if (iov->iov_len > INT_MAX - auio.uio_resid) {
243 			error = EINVAL;
244 			goto done;
245 		}
246 		auio.uio_resid += iov->iov_len;
247 		iov++;
248 	}
249 #ifdef KTRACE
250 	/*
251 	 * if tracing, save a copy of iovec
252 	 */
253 	if (KTRPOINT(p, KTR_GENIO))  {
254 		MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
255 		bcopy((caddr_t)auio.uio_iov, (caddr_t)ktriov, iovlen);
256 	}
257 #endif
258 	cnt = auio.uio_resid;
259 	if ((error = fo_read(fp, &auio, fp->f_cred, 0, p)))
260 		if (auio.uio_resid != cnt && (error == ERESTART ||
261 		    error == EINTR || error == EWOULDBLOCK))
262 			error = 0;
263 	cnt -= auio.uio_resid;
264 #ifdef KTRACE
265 	if (ktriov != NULL) {
266 		if (error == 0)
267 			ktrgenio(p->p_tracep, uap->fd, UIO_READ, ktriov,
268 			    cnt, error);
269 		FREE(ktriov, M_TEMP);
270 	}
271 #endif
272 	p->p_retval[0] = cnt;
273 done:
274 	if (needfree)
275 		FREE(needfree, M_IOV);
276 	return (error);
277 }
278 
279 /*
280  * Write system call
281  */
282 #ifndef _SYS_SYSPROTO_H_
283 struct write_args {
284 	int	fd;
285 	const void *buf;
286 	size_t	nbyte;
287 };
288 #endif
289 int
290 write(p, uap)
291 	struct proc *p;
292 	register struct write_args *uap;
293 {
294 	register struct file *fp;
295 
296 	if ((fp = getfp(p->p_fd, uap->fd, FWRITE)) == NULL)
297 		return (EBADF);
298 	return (dofilewrite(p, fp, uap->fd, uap->buf, uap->nbyte, (off_t)-1, 0));
299 }
300 
301 /*
302  * Pwrite system call
303  */
304 #ifndef _SYS_SYSPROTO_H_
305 struct pwrite_args {
306 	int	fd;
307 	const void *buf;
308 	size_t	nbyte;
309 	int	pad;
310 	off_t	offset;
311 };
312 #endif
313 int
314 pwrite(p, uap)
315 	struct proc *p;
316 	register struct pwrite_args *uap;
317 {
318 	register struct file *fp;
319 
320 	if ((fp = getfp(p->p_fd, uap->fd, FWRITE)) == NULL)
321 		return (EBADF);
322 	if (fp->f_type != DTYPE_VNODE)
323 		return (ESPIPE);
324 	return (dofilewrite(p, fp, uap->fd, uap->buf, uap->nbyte, uap->offset,
325 	    FOF_OFFSET));
326 }
327 
328 static int
329 dofilewrite(p, fp, fd, buf, nbyte, offset, flags)
330 	struct proc *p;
331 	struct file *fp;
332 	int fd, flags;
333 	const void *buf;
334 	size_t nbyte;
335 	off_t offset;
336 {
337 	struct uio auio;
338 	struct iovec aiov;
339 	long cnt, error = 0;
340 #ifdef KTRACE
341 	struct iovec ktriov;
342 #endif
343 
344 	aiov.iov_base = (void *)buf;
345 	aiov.iov_len = nbyte;
346 	auio.uio_iov = &aiov;
347 	auio.uio_iovcnt = 1;
348 	auio.uio_offset = offset;
349 	if (nbyte > INT_MAX)
350 		return (EINVAL);
351 	auio.uio_resid = nbyte;
352 	auio.uio_rw = UIO_WRITE;
353 	auio.uio_segflg = UIO_USERSPACE;
354 	auio.uio_procp = p;
355 #ifdef KTRACE
356 	/*
357 	 * if tracing, save a copy of iovec
358 	 */
359 	if (KTRPOINT(p, KTR_GENIO))
360 		ktriov = aiov;
361 #endif
362 	cnt = nbyte;
363 	if ((error = fo_write(fp, &auio, fp->f_cred, flags, p))) {
364 		if (auio.uio_resid != cnt && (error == ERESTART ||
365 		    error == EINTR || error == EWOULDBLOCK))
366 			error = 0;
367 		if (error == EPIPE)
368 			psignal(p, SIGPIPE);
369 	}
370 	cnt -= auio.uio_resid;
371 #ifdef KTRACE
372 	if (KTRPOINT(p, KTR_GENIO) && error == 0)
373 		ktrgenio(p->p_tracep, fd, UIO_WRITE,
374 		    &ktriov, cnt, error);
375 #endif
376 	p->p_retval[0] = cnt;
377 	return (error);
378 }
379 
380 /*
381  * Gather write system call
382  */
383 #ifndef _SYS_SYSPROTO_H_
384 struct writev_args {
385 	int	fd;
386 	struct	iovec *iovp;
387 	u_int	iovcnt;
388 };
389 #endif
390 int
391 writev(p, uap)
392 	struct proc *p;
393 	register struct writev_args *uap;
394 {
395 	register struct file *fp;
396 	register struct filedesc *fdp = p->p_fd;
397 	struct uio auio;
398 	register struct iovec *iov;
399 	struct iovec *needfree;
400 	struct iovec aiov[UIO_SMALLIOV];
401 	long i, cnt, error = 0;
402 	u_int iovlen;
403 #ifdef KTRACE
404 	struct iovec *ktriov = NULL;
405 #endif
406 
407 	if ((fp = getfp(fdp, uap->fd, FWRITE)) == NULL)
408 		return (EBADF);
409 	fhold(fp);
410 	/* note: can't use iovlen until iovcnt is validated */
411 	iovlen = uap->iovcnt * sizeof (struct iovec);
412 	if (uap->iovcnt > UIO_SMALLIOV) {
413 		if (uap->iovcnt > UIO_MAXIOV) {
414 			needfree = NULL;
415 			error = EINVAL;
416 			goto done;
417 		}
418 		MALLOC(iov, struct iovec *, iovlen, M_IOV, M_WAITOK);
419 		needfree = iov;
420 	} else {
421 		iov = aiov;
422 		needfree = NULL;
423 	}
424 	auio.uio_iov = iov;
425 	auio.uio_iovcnt = uap->iovcnt;
426 	auio.uio_rw = UIO_WRITE;
427 	auio.uio_segflg = UIO_USERSPACE;
428 	auio.uio_procp = p;
429 	auio.uio_offset = -1;
430 	if ((error = copyin((caddr_t)uap->iovp, (caddr_t)iov, iovlen)))
431 		goto done;
432 	auio.uio_resid = 0;
433 	for (i = 0; i < uap->iovcnt; i++) {
434 		if (iov->iov_len > INT_MAX - auio.uio_resid) {
435 			error = EINVAL;
436 			goto done;
437 		}
438 		auio.uio_resid += iov->iov_len;
439 		iov++;
440 	}
441 #ifdef KTRACE
442 	/*
443 	 * if tracing, save a copy of iovec
444 	 */
445 	if (KTRPOINT(p, KTR_GENIO))  {
446 		MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
447 		bcopy((caddr_t)auio.uio_iov, (caddr_t)ktriov, iovlen);
448 	}
449 #endif
450 	cnt = auio.uio_resid;
451 	if ((error = fo_write(fp, &auio, fp->f_cred, 0, p))) {
452 		if (auio.uio_resid != cnt && (error == ERESTART ||
453 		    error == EINTR || error == EWOULDBLOCK))
454 			error = 0;
455 		if (error == EPIPE)
456 			psignal(p, SIGPIPE);
457 	}
458 	cnt -= auio.uio_resid;
459 #ifdef KTRACE
460 	if (ktriov != NULL) {
461 		if (error == 0)
462 			ktrgenio(p->p_tracep, uap->fd, UIO_WRITE,
463 				ktriov, cnt, error);
464 		FREE(ktriov, M_TEMP);
465 	}
466 #endif
467 	p->p_retval[0] = cnt;
468 done:
469 	fdrop(fp, p);
470 	if (needfree)
471 		FREE(needfree, M_IOV);
472 	return (error);
473 }
474 
475 /*
476  * Ioctl system call
477  */
478 #ifndef _SYS_SYSPROTO_H_
479 struct ioctl_args {
480 	int	fd;
481 	u_long	com;
482 	caddr_t	data;
483 };
484 #endif
485 /* ARGSUSED */
486 int
487 ioctl(p, uap)
488 	struct proc *p;
489 	register struct ioctl_args *uap;
490 {
491 	register struct file *fp;
492 	register struct filedesc *fdp;
493 	register u_long com;
494 	int error;
495 	register u_int size;
496 	caddr_t data, memp;
497 	int tmp;
498 #define STK_PARAMS	128
499 	char stkbuf[STK_PARAMS];
500 
501 	fdp = p->p_fd;
502 	if ((u_int)uap->fd >= fdp->fd_nfiles ||
503 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
504 		return (EBADF);
505 
506 	if ((fp->f_flag & (FREAD | FWRITE)) == 0)
507 		return (EBADF);
508 
509 	switch (com = uap->com) {
510 	case FIONCLEX:
511 		fdp->fd_ofileflags[uap->fd] &= ~UF_EXCLOSE;
512 		return (0);
513 	case FIOCLEX:
514 		fdp->fd_ofileflags[uap->fd] |= UF_EXCLOSE;
515 		return (0);
516 	}
517 
518 	/*
519 	 * Interpret high order word to find amount of data to be
520 	 * copied to/from the user's address space.
521 	 */
522 	size = IOCPARM_LEN(com);
523 	if (size > IOCPARM_MAX)
524 		return (ENOTTY);
525 	memp = NULL;
526 	if (size > sizeof (stkbuf)) {
527 		memp = (caddr_t)malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
528 		data = memp;
529 	} else
530 		data = stkbuf;
531 	if (com&IOC_IN) {
532 		if (size) {
533 			error = copyin(uap->data, data, (u_int)size);
534 			if (error) {
535 				if (memp)
536 					free(memp, M_IOCTLOPS);
537 				return (error);
538 			}
539 		} else
540 			*(caddr_t *)data = uap->data;
541 	} else if ((com&IOC_OUT) && size)
542 		/*
543 		 * Zero the buffer so the user always
544 		 * gets back something deterministic.
545 		 */
546 		bzero(data, size);
547 	else if (com&IOC_VOID)
548 		*(caddr_t *)data = uap->data;
549 
550 	switch (com) {
551 
552 	case FIONBIO:
553 		if ((tmp = *(int *)data))
554 			fp->f_flag |= FNONBLOCK;
555 		else
556 			fp->f_flag &= ~FNONBLOCK;
557 		error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, p);
558 		break;
559 
560 	case FIOASYNC:
561 		if ((tmp = *(int *)data))
562 			fp->f_flag |= FASYNC;
563 		else
564 			fp->f_flag &= ~FASYNC;
565 		error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, p);
566 		break;
567 
568 	default:
569 		error = fo_ioctl(fp, com, data, p);
570 		/*
571 		 * Copy any data to user, size was
572 		 * already set and checked above.
573 		 */
574 		if (error == 0 && (com&IOC_OUT) && size)
575 			error = copyout(data, uap->data, (u_int)size);
576 		break;
577 	}
578 	if (memp)
579 		free(memp, M_IOCTLOPS);
580 	return (error);
581 }
582 
583 static int	nselcoll;	/* Select collisions since boot */
584 int	selwait;
585 SYSCTL_INT(_kern, OID_AUTO, nselcoll, CTLFLAG_RD, &nselcoll, 0, "");
586 
587 /*
588  * Select system call.
589  */
590 #ifndef _SYS_SYSPROTO_H_
591 struct select_args {
592 	int	nd;
593 	fd_set	*in, *ou, *ex;
594 	struct	timeval *tv;
595 };
596 #endif
597 int
598 select(p, uap)
599 	register struct proc *p;
600 	register struct select_args *uap;
601 {
602 	/*
603 	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
604 	 * infds with the new FD_SETSIZE of 1024, and more than enough for
605 	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
606 	 * of 256.
607 	 */
608 	fd_mask s_selbits[howmany(2048, NFDBITS)];
609 	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
610 	struct timeval atv, rtv, ttv;
611 	int s, ncoll, error, timo;
612 	u_int nbufbytes, ncpbytes, nfdbits;
613 
614 	if (uap->nd < 0)
615 		return (EINVAL);
616 	if (uap->nd > p->p_fd->fd_nfiles)
617 		uap->nd = p->p_fd->fd_nfiles;   /* forgiving; slightly wrong */
618 
619 	/*
620 	 * Allocate just enough bits for the non-null fd_sets.  Use the
621 	 * preallocated auto buffer if possible.
622 	 */
623 	nfdbits = roundup(uap->nd, NFDBITS);
624 	ncpbytes = nfdbits / NBBY;
625 	nbufbytes = 0;
626 	if (uap->in != NULL)
627 		nbufbytes += 2 * ncpbytes;
628 	if (uap->ou != NULL)
629 		nbufbytes += 2 * ncpbytes;
630 	if (uap->ex != NULL)
631 		nbufbytes += 2 * ncpbytes;
632 	if (nbufbytes <= sizeof s_selbits)
633 		selbits = &s_selbits[0];
634 	else
635 		selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
636 
637 	/*
638 	 * Assign pointers into the bit buffers and fetch the input bits.
639 	 * Put the output buffers together so that they can be bzeroed
640 	 * together.
641 	 */
642 	sbp = selbits;
643 #define	getbits(name, x) \
644 	do {								\
645 		if (uap->name == NULL)					\
646 			ibits[x] = NULL;				\
647 		else {							\
648 			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
649 			obits[x] = sbp;					\
650 			sbp += ncpbytes / sizeof *sbp;			\
651 			error = copyin(uap->name, ibits[x], ncpbytes);	\
652 			if (error != 0)					\
653 				goto done;				\
654 		}							\
655 	} while (0)
656 	getbits(in, 0);
657 	getbits(ou, 1);
658 	getbits(ex, 2);
659 #undef	getbits
660 	if (nbufbytes != 0)
661 		bzero(selbits, nbufbytes / 2);
662 
663 	if (uap->tv) {
664 		error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
665 			sizeof (atv));
666 		if (error)
667 			goto done;
668 		if (itimerfix(&atv)) {
669 			error = EINVAL;
670 			goto done;
671 		}
672 		getmicrouptime(&rtv);
673 		timevaladd(&atv, &rtv);
674 	} else
675 		atv.tv_sec = 0;
676 	timo = 0;
677 retry:
678 	ncoll = nselcoll;
679 	p->p_flag |= P_SELECT;
680 	error = selscan(p, ibits, obits, uap->nd);
681 	if (error || p->p_retval[0])
682 		goto done;
683 	if (atv.tv_sec) {
684 		getmicrouptime(&rtv);
685 		if (timevalcmp(&rtv, &atv, >=))
686 			goto done;
687 		ttv = atv;
688 		timevalsub(&ttv, &rtv);
689 		timo = ttv.tv_sec > 24 * 60 * 60 ?
690 		    24 * 60 * 60 * hz : tvtohz(&ttv);
691 	}
692 	s = splhigh();
693 	if ((p->p_flag & P_SELECT) == 0 || nselcoll != ncoll) {
694 		splx(s);
695 		goto retry;
696 	}
697 	p->p_flag &= ~P_SELECT;
698 
699 	error = tsleep((caddr_t)&selwait, PSOCK | PCATCH, "select", timo);
700 
701 	splx(s);
702 	if (error == 0)
703 		goto retry;
704 done:
705 	p->p_flag &= ~P_SELECT;
706 	/* select is not restarted after signals... */
707 	if (error == ERESTART)
708 		error = EINTR;
709 	if (error == EWOULDBLOCK)
710 		error = 0;
711 #define	putbits(name, x) \
712 	if (uap->name && (error2 = copyout(obits[x], uap->name, ncpbytes))) \
713 		error = error2;
714 	if (error == 0) {
715 		int error2;
716 
717 		putbits(in, 0);
718 		putbits(ou, 1);
719 		putbits(ex, 2);
720 #undef putbits
721 	}
722 	if (selbits != &s_selbits[0])
723 		free(selbits, M_SELECT);
724 	return (error);
725 }
726 
727 static int
728 selscan(p, ibits, obits, nfd)
729 	struct proc *p;
730 	fd_mask **ibits, **obits;
731 	int nfd;
732 {
733 	struct filedesc *fdp = p->p_fd;
734 	int msk, i, fd;
735 	fd_mask bits;
736 	struct file *fp;
737 	int n = 0;
738 	/* Note: backend also returns POLLHUP/POLLERR if appropriate. */
739 	static int flag[3] = { POLLRDNORM, POLLWRNORM, POLLRDBAND };
740 
741 	for (msk = 0; msk < 3; msk++) {
742 		if (ibits[msk] == NULL)
743 			continue;
744 		for (i = 0; i < nfd; i += NFDBITS) {
745 			bits = ibits[msk][i/NFDBITS];
746 			/* ffs(int mask) not portable, fd_mask is long */
747 			for (fd = i; bits && fd < nfd; fd++, bits >>= 1) {
748 				if (!(bits & 1))
749 					continue;
750 				fp = fdp->fd_ofiles[fd];
751 				if (fp == NULL)
752 					return (EBADF);
753 				if (fo_poll(fp, flag[msk], fp->f_cred, p)) {
754 					obits[msk][(fd)/NFDBITS] |=
755 					    ((fd_mask)1 << ((fd) % NFDBITS));
756 					n++;
757 				}
758 			}
759 		}
760 	}
761 	p->p_retval[0] = n;
762 	return (0);
763 }
764 
765 /*
766  * Poll system call.
767  */
768 #ifndef _SYS_SYSPROTO_H_
769 struct poll_args {
770 	struct pollfd *fds;
771 	u_int	nfds;
772 	int	timeout;
773 };
774 #endif
775 int
776 poll(p, uap)
777 	register struct proc *p;
778 	register struct poll_args *uap;
779 {
780 	caddr_t bits;
781 	char smallbits[32 * sizeof(struct pollfd)];
782 	struct timeval atv, rtv, ttv;
783 	int s, ncoll, error = 0, timo;
784 	size_t ni;
785 
786 	if (SCARG(uap, nfds) > p->p_fd->fd_nfiles) {
787 		/* forgiving; slightly wrong */
788 		SCARG(uap, nfds) = p->p_fd->fd_nfiles;
789 	}
790 	ni = SCARG(uap, nfds) * sizeof(struct pollfd);
791 	if (ni > sizeof(smallbits))
792 		bits = malloc(ni, M_TEMP, M_WAITOK);
793 	else
794 		bits = smallbits;
795 	error = copyin(SCARG(uap, fds), bits, ni);
796 	if (error)
797 		goto done;
798 	if (SCARG(uap, timeout) != INFTIM) {
799 		atv.tv_sec = SCARG(uap, timeout) / 1000;
800 		atv.tv_usec = (SCARG(uap, timeout) % 1000) * 1000;
801 		if (itimerfix(&atv)) {
802 			error = EINVAL;
803 			goto done;
804 		}
805 		getmicrouptime(&rtv);
806 		timevaladd(&atv, &rtv);
807 	} else
808 		atv.tv_sec = 0;
809 	timo = 0;
810 retry:
811 	ncoll = nselcoll;
812 	p->p_flag |= P_SELECT;
813 	error = pollscan(p, (struct pollfd *)bits, SCARG(uap, nfds));
814 	if (error || p->p_retval[0])
815 		goto done;
816 	if (atv.tv_sec) {
817 		getmicrouptime(&rtv);
818 		if (timevalcmp(&rtv, &atv, >=))
819 			goto done;
820 		ttv = atv;
821 		timevalsub(&ttv, &rtv);
822 		timo = ttv.tv_sec > 24 * 60 * 60 ?
823 		    24 * 60 * 60 * hz : tvtohz(&ttv);
824 	}
825 	s = splhigh();
826 	if ((p->p_flag & P_SELECT) == 0 || nselcoll != ncoll) {
827 		splx(s);
828 		goto retry;
829 	}
830 	p->p_flag &= ~P_SELECT;
831 	error = tsleep((caddr_t)&selwait, PSOCK | PCATCH, "poll", timo);
832 	splx(s);
833 	if (error == 0)
834 		goto retry;
835 done:
836 	p->p_flag &= ~P_SELECT;
837 	/* poll is not restarted after signals... */
838 	if (error == ERESTART)
839 		error = EINTR;
840 	if (error == EWOULDBLOCK)
841 		error = 0;
842 	if (error == 0) {
843 		error = copyout(bits, SCARG(uap, fds), ni);
844 		if (error)
845 			goto out;
846 	}
847 out:
848 	if (ni > sizeof(smallbits))
849 		free(bits, M_TEMP);
850 	return (error);
851 }
852 
853 static int
854 pollscan(p, fds, nfd)
855 	struct proc *p;
856 	struct pollfd *fds;
857 	int nfd;
858 {
859 	register struct filedesc *fdp = p->p_fd;
860 	int i;
861 	struct file *fp;
862 	int n = 0;
863 
864 	for (i = 0; i < nfd; i++, fds++) {
865 		if (fds->fd >= fdp->fd_nfiles) {
866 			fds->revents = POLLNVAL;
867 			n++;
868 		} else if (fds->fd < 0) {
869 			fds->revents = 0;
870 		} else {
871 			fp = fdp->fd_ofiles[fds->fd];
872 			if (fp == 0) {
873 				fds->revents = POLLNVAL;
874 				n++;
875 			} else {
876 				/*
877 				 * Note: backend also returns POLLHUP and
878 				 * POLLERR if appropriate.
879 				 */
880 				fds->revents = fo_poll(fp, fds->events,
881 				    fp->f_cred, p);
882 				if (fds->revents != 0)
883 					n++;
884 			}
885 		}
886 	}
887 	p->p_retval[0] = n;
888 	return (0);
889 }
890 
891 /*
892  * OpenBSD poll system call.
893  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
894  */
895 #ifndef _SYS_SYSPROTO_H_
896 struct openbsd_poll_args {
897 	struct pollfd *fds;
898 	u_int	nfds;
899 	int	timeout;
900 };
901 #endif
902 int
903 openbsd_poll(p, uap)
904 	register struct proc *p;
905 	register struct openbsd_poll_args *uap;
906 {
907 	return (poll(p, (struct poll_args *)uap));
908 }
909 
910 /*ARGSUSED*/
911 int
912 seltrue(dev, events, p)
913 	dev_t dev;
914 	int events;
915 	struct proc *p;
916 {
917 
918 	return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
919 }
920 
921 /*
922  * Record a select request.
923  */
924 void
925 selrecord(selector, sip)
926 	struct proc *selector;
927 	struct selinfo *sip;
928 {
929 	struct proc *p;
930 	pid_t mypid;
931 
932 	mypid = selector->p_pid;
933 	if (sip->si_pid == mypid)
934 		return;
935 	if (sip->si_pid && (p = pfind(sip->si_pid)) &&
936 	    p->p_wchan == (caddr_t)&selwait)
937 		sip->si_flags |= SI_COLL;
938 	else
939 		sip->si_pid = mypid;
940 }
941 
942 /*
943  * Do a wakeup when a selectable event occurs.
944  */
945 void
946 selwakeup(sip)
947 	register struct selinfo *sip;
948 {
949 	register struct proc *p;
950 	int s;
951 
952 	if (sip->si_pid == 0)
953 		return;
954 	if (sip->si_flags & SI_COLL) {
955 		nselcoll++;
956 		sip->si_flags &= ~SI_COLL;
957 		wakeup((caddr_t)&selwait);
958 	}
959 	p = pfind(sip->si_pid);
960 	sip->si_pid = 0;
961 	if (p != NULL) {
962 		s = splhigh();
963 		if (p->p_wchan == (caddr_t)&selwait) {
964 			if (p->p_stat == SSLEEP)
965 				setrunnable(p);
966 			else
967 				unsleep(p);
968 		} else if (p->p_flag & P_SELECT)
969 			p->p_flag &= ~P_SELECT;
970 		splx(s);
971 	}
972 }
973