xref: /freebsd/sys/kern/sys_generic.c (revision ba54cdcdda639bebc917b1796ecbc35a83ff8625)
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)sys_generic.c	8.5 (Berkeley) 1/21/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_ktrace.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/sysproto.h>
45 #include <sys/filedesc.h>
46 #include <sys/filio.h>
47 #include <sys/fcntl.h>
48 #include <sys/file.h>
49 #include <sys/proc.h>
50 #include <sys/signalvar.h>
51 #include <sys/socketvar.h>
52 #include <sys/uio.h>
53 #include <sys/kernel.h>
54 #include <sys/limits.h>
55 #include <sys/malloc.h>
56 #include <sys/poll.h>
57 #include <sys/resourcevar.h>
58 #include <sys/selinfo.h>
59 #include <sys/sleepqueue.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysent.h>
63 #include <sys/vnode.h>
64 #include <sys/bio.h>
65 #include <sys/buf.h>
66 #include <sys/condvar.h>
67 #ifdef KTRACE
68 #include <sys/ktrace.h>
69 #endif
70 #include <vm/vm.h>
71 #include <vm/vm_page.h>
72 
73 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
74 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
75 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
76 
77 static int	pollscan(struct thread *, struct pollfd *, u_int);
78 static int	selscan(struct thread *, fd_mask **, fd_mask **, int);
79 static int	dofileread(struct thread *, struct file *, int, void *,
80 		    size_t, off_t, int);
81 static int	dofilewrite(struct thread *, struct file *, int,
82 		    const void *, size_t, off_t, int);
83 static void	doselwakeup(struct selinfo *, int);
84 
85 /*
86  * Read system call.
87  */
88 #ifndef _SYS_SYSPROTO_H_
89 struct read_args {
90 	int	fd;
91 	void	*buf;
92 	size_t	nbyte;
93 };
94 #endif
95 /*
96  * MPSAFE
97  */
98 int
99 read(td, uap)
100 	struct thread *td;
101 	struct read_args *uap;
102 {
103 	struct file *fp;
104 	int error;
105 
106 	if ((error = fget_read(td, uap->fd, &fp)) == 0) {
107 		error = dofileread(td, fp, uap->fd, uap->buf,
108 			    uap->nbyte, (off_t)-1, 0);
109 		fdrop(fp, td);
110 	}
111 	return(error);
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 /*
127  * MPSAFE
128  */
129 int
130 pread(td, uap)
131 	struct thread *td;
132 	struct pread_args *uap;
133 {
134 	struct file *fp;
135 	int error;
136 
137 	if ((error = fget_read(td, uap->fd, &fp)) != 0)
138 		return (error);
139 	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
140 		error = ESPIPE;
141 	else if (uap->offset < 0 && fp->f_vnode->v_type != VCHR)
142 		error = EINVAL;
143 	else {
144 		error = dofileread(td, fp, uap->fd, uap->buf, uap->nbyte,
145 			    uap->offset, FOF_OFFSET);
146 	}
147 	fdrop(fp, td);
148 	return(error);
149 }
150 
151 /*
152  * Code common for read and pread
153  */
154 static int
155 dofileread(td, fp, fd, buf, nbyte, offset, flags)
156 	struct thread *td;
157 	struct file *fp;
158 	int fd, flags;
159 	void *buf;
160 	size_t nbyte;
161 	off_t offset;
162 {
163 	struct uio auio;
164 	struct iovec aiov;
165 	long cnt, error = 0;
166 #ifdef KTRACE
167 	struct uio *ktruio = NULL;
168 #endif
169 
170 	aiov.iov_base = buf;
171 	aiov.iov_len = nbyte;
172 	auio.uio_iov = &aiov;
173 	auio.uio_iovcnt = 1;
174 	auio.uio_offset = offset;
175 	if (nbyte > INT_MAX)
176 		return (EINVAL);
177 	auio.uio_resid = nbyte;
178 	auio.uio_rw = UIO_READ;
179 	auio.uio_segflg = UIO_USERSPACE;
180 	auio.uio_td = td;
181 #ifdef KTRACE
182 	if (KTRPOINT(td, KTR_GENIO))
183 		ktruio = cloneuio(&auio);
184 #endif
185 	cnt = nbyte;
186 
187 	if ((error = fo_read(fp, &auio, td->td_ucred, flags, td))) {
188 		if (auio.uio_resid != cnt && (error == ERESTART ||
189 		    error == EINTR || error == EWOULDBLOCK))
190 			error = 0;
191 	}
192 	cnt -= auio.uio_resid;
193 #ifdef KTRACE
194 	if (ktruio != NULL) {
195 		ktruio->uio_resid = cnt;
196 		ktrgenio(fd, UIO_READ, ktruio, error);
197 	}
198 #endif
199 	td->td_retval[0] = cnt;
200 	return (error);
201 }
202 
203 /*
204  * Scatter read system call.
205  */
206 #ifndef _SYS_SYSPROTO_H_
207 struct readv_args {
208 	int	fd;
209 	struct	iovec *iovp;
210 	u_int	iovcnt;
211 };
212 #endif
213 /*
214  * MPSAFE
215  */
216 int
217 readv(struct thread *td, struct readv_args *uap)
218 {
219 	struct file *fp;
220 	struct uio *auio = NULL;
221 	long cnt;
222 	int error;
223 #ifdef KTRACE
224 	struct uio *ktruio = NULL;
225 #endif
226 
227 	error = fget_read(td, uap->fd, &fp);
228 	if (error)
229 		return (error);
230 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
231 	if (error) {
232 		fdrop(fp, td);
233 		return (error);
234 	}
235 	auio->uio_rw = UIO_READ;
236 	auio->uio_td = td;
237 #ifdef KTRACE
238 	if (KTRPOINT(td, KTR_GENIO))
239 		ktruio = cloneuio(auio);
240 #endif
241 	cnt = auio->uio_resid;
242 	if ((error = fo_read(fp, auio, td->td_ucred, 0, td))) {
243 		if (auio->uio_resid != cnt && (error == ERESTART ||
244 		    error == EINTR || error == EWOULDBLOCK))
245 			error = 0;
246 	}
247 	cnt -= auio->uio_resid;
248 #ifdef KTRACE
249 	if (ktruio != NULL) {
250 		ktruio->uio_resid = cnt;
251 		ktrgenio(uap->fd, UIO_READ, ktruio, error);
252 	}
253 #endif
254 	td->td_retval[0] = cnt;
255 	free(auio, M_IOV);
256 	fdrop(fp, td);
257 	return (error);
258 }
259 
260 /*
261  * Write system call
262  */
263 #ifndef _SYS_SYSPROTO_H_
264 struct write_args {
265 	int	fd;
266 	const void *buf;
267 	size_t	nbyte;
268 };
269 #endif
270 /*
271  * MPSAFE
272  */
273 int
274 write(td, uap)
275 	struct thread *td;
276 	struct write_args *uap;
277 {
278 	struct file *fp;
279 	int error;
280 
281 	if ((error = fget_write(td, uap->fd, &fp)) == 0) {
282 		error = dofilewrite(td, fp, uap->fd, uap->buf, uap->nbyte,
283 			    (off_t)-1, 0);
284 		fdrop(fp, td);
285 	} else {
286 		error = EBADF;	/* XXX this can't be right */
287 	}
288 	return(error);
289 }
290 
291 /*
292  * Pwrite system call
293  */
294 #ifndef _SYS_SYSPROTO_H_
295 struct pwrite_args {
296 	int	fd;
297 	const void *buf;
298 	size_t	nbyte;
299 	int	pad;
300 	off_t	offset;
301 };
302 #endif
303 /*
304  * MPSAFE
305  */
306 int
307 pwrite(td, uap)
308 	struct thread *td;
309 	struct pwrite_args *uap;
310 {
311 	struct file *fp;
312 	int error;
313 
314 	if ((error = fget_write(td, uap->fd, &fp)) == 0) {
315 		if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
316 			error = ESPIPE;
317 		else if (uap->offset < 0 && fp->f_vnode->v_type != VCHR)
318 			error = EINVAL;
319 		else {
320 			error = dofilewrite(td, fp, uap->fd, uap->buf,
321 				    uap->nbyte, uap->offset, FOF_OFFSET);
322 		}
323 		fdrop(fp, td);
324 	} else {
325 		error = EBADF;	/* this can't be right */
326 	}
327 	return(error);
328 }
329 
330 static int
331 dofilewrite(td, fp, fd, buf, nbyte, offset, flags)
332 	struct thread *td;
333 	struct file *fp;
334 	int fd, flags;
335 	const void *buf;
336 	size_t nbyte;
337 	off_t offset;
338 {
339 	struct uio auio;
340 	struct iovec aiov;
341 	long cnt, error = 0;
342 #ifdef KTRACE
343 	struct uio *ktruio = NULL;
344 #endif
345 
346 	aiov.iov_base = (void *)(uintptr_t)buf;
347 	aiov.iov_len = nbyte;
348 	auio.uio_iov = &aiov;
349 	auio.uio_iovcnt = 1;
350 	auio.uio_offset = offset;
351 	if (nbyte > INT_MAX)
352 		return (EINVAL);
353 	auio.uio_resid = nbyte;
354 	auio.uio_rw = UIO_WRITE;
355 	auio.uio_segflg = UIO_USERSPACE;
356 	auio.uio_td = td;
357 #ifdef KTRACE
358 	if (KTRPOINT(td, KTR_GENIO))
359 		ktruio = cloneuio(&auio);
360 #endif
361 	cnt = nbyte;
362 	if (fp->f_type == DTYPE_VNODE)
363 		bwillwrite();
364 	if ((error = fo_write(fp, &auio, td->td_ucred, flags, td))) {
365 		if (auio.uio_resid != cnt && (error == ERESTART ||
366 		    error == EINTR || error == EWOULDBLOCK))
367 			error = 0;
368 		/* Socket layer is responsible for issuing SIGPIPE. */
369 		if (error == EPIPE && fp->f_type != DTYPE_SOCKET) {
370 			PROC_LOCK(td->td_proc);
371 			psignal(td->td_proc, SIGPIPE);
372 			PROC_UNLOCK(td->td_proc);
373 		}
374 	}
375 	cnt -= auio.uio_resid;
376 #ifdef KTRACE
377 	if (ktruio != NULL) {
378 		ktruio->uio_resid = cnt;
379 		ktrgenio(fd, UIO_WRITE, ktruio, error);
380 	}
381 #endif
382 	td->td_retval[0] = cnt;
383 	return (error);
384 }
385 
386 /*
387  * Gather write system call
388  */
389 #ifndef _SYS_SYSPROTO_H_
390 struct writev_args {
391 	int	fd;
392 	struct	iovec *iovp;
393 	u_int	iovcnt;
394 };
395 #endif
396 /*
397  * MPSAFE
398  */
399 int
400 writev(struct thread *td, struct writev_args *uap)
401 {
402 	struct file *fp;
403 	struct uio *auio = NULL;
404 	long cnt;
405 	int error;
406 #ifdef KTRACE
407 	struct uio *ktruio = NULL;
408 #endif
409 
410 	error = fget_write(td, uap->fd, &fp);
411 	if (error)
412 		return (EBADF);
413 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
414 	if (error) {
415 		fdrop(fp, td);
416 		return (error);
417 	}
418 	auio->uio_rw = UIO_WRITE;
419 	auio->uio_td = td;
420 #ifdef KTRACE
421 	if (KTRPOINT(td, KTR_GENIO))
422 		ktruio = cloneuio(auio);
423 #endif
424 	cnt = auio->uio_resid;
425 	if (fp->f_type == DTYPE_VNODE)
426 		bwillwrite();
427 	if ((error = fo_write(fp, auio, td->td_ucred, 0, td))) {
428 		if (auio->uio_resid != cnt && (error == ERESTART ||
429 		    error == EINTR || error == EWOULDBLOCK))
430 			error = 0;
431 		if (error == EPIPE) {
432 			PROC_LOCK(td->td_proc);
433 			psignal(td->td_proc, SIGPIPE);
434 			PROC_UNLOCK(td->td_proc);
435 		}
436 	}
437 	cnt -= auio->uio_resid;
438 #ifdef KTRACE
439 	if (ktruio != NULL) {
440 		ktruio->uio_resid = cnt;
441 		ktrgenio(uap->fd, UIO_WRITE, ktruio, error);
442 	}
443 #endif
444 	td->td_retval[0] = cnt;
445 	fdrop(fp, td);
446 	free(auio, M_IOV);
447 	return (error);
448 }
449 
450 /*
451  * Ioctl system call
452  */
453 #ifndef _SYS_SYSPROTO_H_
454 struct ioctl_args {
455 	int	fd;
456 	u_long	com;
457 	caddr_t	data;
458 };
459 #endif
460 /*
461  * MPSAFE
462  */
463 /* ARGSUSED */
464 int
465 ioctl(struct thread *td, struct ioctl_args *uap)
466 {
467 	struct file *fp;
468 	struct filedesc *fdp;
469 	u_long com;
470 	int error = 0;
471 	u_int size;
472 	caddr_t data, memp;
473 	int tmp;
474 
475 	if (uap->com > 0xffffffff) {
476 		printf(
477 		    "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
478 		    td->td_proc->p_pid, td->td_proc->p_comm, uap->com);
479 		uap->com &= 0xffffffff;
480 	}
481 	if ((error = fget(td, uap->fd, &fp)) != 0)
482 		return (error);
483 	if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
484 		fdrop(fp, td);
485 		return (EBADF);
486 	}
487 	fdp = td->td_proc->p_fd;
488 	switch (com = uap->com) {
489 	case FIONCLEX:
490 		FILEDESC_LOCK_FAST(fdp);
491 		fdp->fd_ofileflags[uap->fd] &= ~UF_EXCLOSE;
492 		FILEDESC_UNLOCK_FAST(fdp);
493 		fdrop(fp, td);
494 		return (0);
495 	case FIOCLEX:
496 		FILEDESC_LOCK_FAST(fdp);
497 		fdp->fd_ofileflags[uap->fd] |= UF_EXCLOSE;
498 		FILEDESC_UNLOCK_FAST(fdp);
499 		fdrop(fp, td);
500 		return (0);
501 	}
502 
503 	/*
504 	 * Interpret high order word to find amount of data to be
505 	 * copied to/from the user's address space.
506 	 */
507 	size = IOCPARM_LEN(com);
508 	if ((size > IOCPARM_MAX) ||
509 	    ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
510 	    ((com & IOC_VOID) && size > 0) ||
511 	    ((com & (IOC_IN | IOC_OUT)) && size == 0)) {
512 		fdrop(fp, td);
513 		return (ENOTTY);
514 	}
515 
516 	if (size > 0) {
517 		memp = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
518 		data = memp;
519 	} else {
520 		memp = NULL;
521 		data = (void *)&uap->data;
522 	}
523 	if (com & IOC_IN) {
524 		error = copyin(uap->data, data, (u_int)size);
525 		if (error) {
526 			free(memp, M_IOCTLOPS);
527 			fdrop(fp, td);
528 			return (error);
529 		}
530 	} else if (com & IOC_OUT) {
531 		/*
532 		 * Zero the buffer so the user always
533 		 * gets back something deterministic.
534 		 */
535 		bzero(data, size);
536 	}
537 
538 	if (com == FIONBIO) {
539 		FILE_LOCK(fp);
540 		if ((tmp = *(int *)data))
541 			fp->f_flag |= FNONBLOCK;
542 		else
543 			fp->f_flag &= ~FNONBLOCK;
544 		FILE_UNLOCK(fp);
545 		data = (void *)&tmp;
546 	} else if (com == FIOASYNC) {
547 		FILE_LOCK(fp);
548 		if ((tmp = *(int *)data))
549 			fp->f_flag |= FASYNC;
550 		else
551 			fp->f_flag &= ~FASYNC;
552 		FILE_UNLOCK(fp);
553 		data = (void *)&tmp;
554 	}
555 
556 	error = fo_ioctl(fp, com, data, td->td_ucred, td);
557 
558 	if (error == 0 && (com & IOC_OUT))
559 		error = copyout(data, uap->data, (u_int)size);
560 
561 	if (memp != NULL)
562 		free(memp, M_IOCTLOPS);
563 	fdrop(fp, td);
564 	return (error);
565 }
566 
567 /*
568  * sellock and selwait are initialized in selectinit() via SYSINIT.
569  */
570 struct mtx	sellock;
571 struct cv	selwait;
572 u_int		nselcoll;	/* Select collisions since boot */
573 SYSCTL_UINT(_kern, OID_AUTO, nselcoll, CTLFLAG_RD, &nselcoll, 0, "");
574 
575 /*
576  * Select system call.
577  */
578 #ifndef _SYS_SYSPROTO_H_
579 struct select_args {
580 	int	nd;
581 	fd_set	*in, *ou, *ex;
582 	struct	timeval *tv;
583 };
584 #endif
585 /*
586  * MPSAFE
587  */
588 int
589 select(td, uap)
590 	register struct thread *td;
591 	register struct select_args *uap;
592 {
593 	struct timeval tv, *tvp;
594 	int error;
595 
596 	if (uap->tv != NULL) {
597 		error = copyin(uap->tv, &tv, sizeof(tv));
598 		if (error)
599 			return (error);
600 		tvp = &tv;
601 	} else
602 		tvp = NULL;
603 
604 	return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp));
605 }
606 
607 int
608 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
609     fd_set *fd_ex, struct timeval *tvp)
610 {
611 	struct filedesc *fdp;
612 	/*
613 	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
614 	 * infds with the new FD_SETSIZE of 1024, and more than enough for
615 	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
616 	 * of 256.
617 	 */
618 	fd_mask s_selbits[howmany(2048, NFDBITS)];
619 	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
620 	struct timeval atv, rtv, ttv;
621 	int error, timo;
622 	u_int ncoll, nbufbytes, ncpbytes, nfdbits;
623 
624 	if (nd < 0)
625 		return (EINVAL);
626 	fdp = td->td_proc->p_fd;
627 
628 	FILEDESC_LOCK_FAST(fdp);
629 
630 	if (nd > td->td_proc->p_fd->fd_nfiles)
631 		nd = td->td_proc->p_fd->fd_nfiles;   /* forgiving; slightly wrong */
632 	FILEDESC_UNLOCK_FAST(fdp);
633 
634 	/*
635 	 * Allocate just enough bits for the non-null fd_sets.  Use the
636 	 * preallocated auto buffer if possible.
637 	 */
638 	nfdbits = roundup(nd, NFDBITS);
639 	ncpbytes = nfdbits / NBBY;
640 	nbufbytes = 0;
641 	if (fd_in != NULL)
642 		nbufbytes += 2 * ncpbytes;
643 	if (fd_ou != NULL)
644 		nbufbytes += 2 * ncpbytes;
645 	if (fd_ex != NULL)
646 		nbufbytes += 2 * ncpbytes;
647 	if (nbufbytes <= sizeof s_selbits)
648 		selbits = &s_selbits[0];
649 	else
650 		selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
651 
652 	/*
653 	 * Assign pointers into the bit buffers and fetch the input bits.
654 	 * Put the output buffers together so that they can be bzeroed
655 	 * together.
656 	 */
657 	sbp = selbits;
658 #define	getbits(name, x) \
659 	do {								\
660 		if (name == NULL)					\
661 			ibits[x] = NULL;				\
662 		else {							\
663 			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
664 			obits[x] = sbp;					\
665 			sbp += ncpbytes / sizeof *sbp;			\
666 			error = copyin(name, ibits[x], ncpbytes);	\
667 			if (error != 0)					\
668 				goto done_nosellock;			\
669 		}							\
670 	} while (0)
671 	getbits(fd_in, 0);
672 	getbits(fd_ou, 1);
673 	getbits(fd_ex, 2);
674 #undef	getbits
675 	if (nbufbytes != 0)
676 		bzero(selbits, nbufbytes / 2);
677 
678 	if (tvp != NULL) {
679 		atv = *tvp;
680 		if (itimerfix(&atv)) {
681 			error = EINVAL;
682 			goto done_nosellock;
683 		}
684 		getmicrouptime(&rtv);
685 		timevaladd(&atv, &rtv);
686 	} else {
687 		atv.tv_sec = 0;
688 		atv.tv_usec = 0;
689 	}
690 	timo = 0;
691 	TAILQ_INIT(&td->td_selq);
692 	mtx_lock(&sellock);
693 retry:
694 	ncoll = nselcoll;
695 	mtx_lock_spin(&sched_lock);
696 	td->td_flags |= TDF_SELECT;
697 	mtx_unlock_spin(&sched_lock);
698 	mtx_unlock(&sellock);
699 
700 	error = selscan(td, ibits, obits, nd);
701 	mtx_lock(&sellock);
702 	if (error || td->td_retval[0])
703 		goto done;
704 	if (atv.tv_sec || atv.tv_usec) {
705 		getmicrouptime(&rtv);
706 		if (timevalcmp(&rtv, &atv, >=))
707 			goto done;
708 		ttv = atv;
709 		timevalsub(&ttv, &rtv);
710 		timo = ttv.tv_sec > 24 * 60 * 60 ?
711 		    24 * 60 * 60 * hz : tvtohz(&ttv);
712 	}
713 
714 	/*
715 	 * An event of interest may occur while we do not hold
716 	 * sellock, so check TDF_SELECT and the number of
717 	 * collisions and rescan the file descriptors if
718 	 * necessary.
719 	 */
720 	mtx_lock_spin(&sched_lock);
721 	if ((td->td_flags & TDF_SELECT) == 0 || nselcoll != ncoll) {
722 		mtx_unlock_spin(&sched_lock);
723 		goto retry;
724 	}
725 	mtx_unlock_spin(&sched_lock);
726 
727 	if (timo > 0)
728 		error = cv_timedwait_sig(&selwait, &sellock, timo);
729 	else
730 		error = cv_wait_sig(&selwait, &sellock);
731 
732 	if (error == 0)
733 		goto retry;
734 
735 done:
736 	clear_selinfo_list(td);
737 	mtx_lock_spin(&sched_lock);
738 	td->td_flags &= ~TDF_SELECT;
739 	mtx_unlock_spin(&sched_lock);
740 	mtx_unlock(&sellock);
741 
742 done_nosellock:
743 	/* select is not restarted after signals... */
744 	if (error == ERESTART)
745 		error = EINTR;
746 	if (error == EWOULDBLOCK)
747 		error = 0;
748 #define	putbits(name, x) \
749 	if (name && (error2 = copyout(obits[x], name, ncpbytes))) \
750 		error = error2;
751 	if (error == 0) {
752 		int error2;
753 
754 		putbits(fd_in, 0);
755 		putbits(fd_ou, 1);
756 		putbits(fd_ex, 2);
757 #undef putbits
758 	}
759 	if (selbits != &s_selbits[0])
760 		free(selbits, M_SELECT);
761 
762 	return (error);
763 }
764 
765 static int
766 selscan(td, ibits, obits, nfd)
767 	struct thread *td;
768 	fd_mask **ibits, **obits;
769 	int nfd;
770 {
771 	int msk, i, fd;
772 	fd_mask bits;
773 	struct file *fp;
774 	int n = 0;
775 	/* Note: backend also returns POLLHUP/POLLERR if appropriate. */
776 	static int flag[3] = { POLLRDNORM, POLLWRNORM, POLLRDBAND };
777 	struct filedesc *fdp = td->td_proc->p_fd;
778 
779 	FILEDESC_LOCK(fdp);
780 	for (msk = 0; msk < 3; msk++) {
781 		if (ibits[msk] == NULL)
782 			continue;
783 		for (i = 0; i < nfd; i += NFDBITS) {
784 			bits = ibits[msk][i/NFDBITS];
785 			/* ffs(int mask) not portable, fd_mask is long */
786 			for (fd = i; bits && fd < nfd; fd++, bits >>= 1) {
787 				if (!(bits & 1))
788 					continue;
789 				if ((fp = fget_locked(fdp, fd)) == NULL) {
790 					FILEDESC_UNLOCK(fdp);
791 					return (EBADF);
792 				}
793 				if (fo_poll(fp, flag[msk], td->td_ucred,
794 				    td)) {
795 					obits[msk][(fd)/NFDBITS] |=
796 					    ((fd_mask)1 << ((fd) % NFDBITS));
797 					n++;
798 				}
799 			}
800 		}
801 	}
802 	FILEDESC_UNLOCK(fdp);
803 	td->td_retval[0] = n;
804 	return (0);
805 }
806 
807 /*
808  * Poll system call.
809  */
810 #ifndef _SYS_SYSPROTO_H_
811 struct poll_args {
812 	struct pollfd *fds;
813 	u_int	nfds;
814 	int	timeout;
815 };
816 #endif
817 /*
818  * MPSAFE
819  */
820 int
821 poll(td, uap)
822 	struct thread *td;
823 	struct poll_args *uap;
824 {
825 	struct pollfd *bits;
826 	struct pollfd smallbits[32];
827 	struct timeval atv, rtv, ttv;
828 	int error = 0, timo;
829 	u_int ncoll, nfds;
830 	size_t ni;
831 
832 	nfds = uap->nfds;
833 
834 	/*
835 	 * This is kinda bogus.  We have fd limits, but that is not
836 	 * really related to the size of the pollfd array.  Make sure
837 	 * we let the process use at least FD_SETSIZE entries and at
838 	 * least enough for the current limits.  We want to be reasonably
839 	 * safe, but not overly restrictive.
840 	 */
841 	PROC_LOCK(td->td_proc);
842 	if ((nfds > lim_cur(td->td_proc, RLIMIT_NOFILE)) &&
843 	    (nfds > FD_SETSIZE)) {
844 		PROC_UNLOCK(td->td_proc);
845 		error = EINVAL;
846 		goto done2;
847 	}
848 	PROC_UNLOCK(td->td_proc);
849 	ni = nfds * sizeof(struct pollfd);
850 	if (ni > sizeof(smallbits))
851 		bits = malloc(ni, M_TEMP, M_WAITOK);
852 	else
853 		bits = smallbits;
854 	error = copyin(uap->fds, bits, ni);
855 	if (error)
856 		goto done_nosellock;
857 	if (uap->timeout != INFTIM) {
858 		atv.tv_sec = uap->timeout / 1000;
859 		atv.tv_usec = (uap->timeout % 1000) * 1000;
860 		if (itimerfix(&atv)) {
861 			error = EINVAL;
862 			goto done_nosellock;
863 		}
864 		getmicrouptime(&rtv);
865 		timevaladd(&atv, &rtv);
866 	} else {
867 		atv.tv_sec = 0;
868 		atv.tv_usec = 0;
869 	}
870 	timo = 0;
871 	TAILQ_INIT(&td->td_selq);
872 	mtx_lock(&sellock);
873 retry:
874 	ncoll = nselcoll;
875 	mtx_lock_spin(&sched_lock);
876 	td->td_flags |= TDF_SELECT;
877 	mtx_unlock_spin(&sched_lock);
878 	mtx_unlock(&sellock);
879 
880 	error = pollscan(td, bits, nfds);
881 	mtx_lock(&sellock);
882 	if (error || td->td_retval[0])
883 		goto done;
884 	if (atv.tv_sec || atv.tv_usec) {
885 		getmicrouptime(&rtv);
886 		if (timevalcmp(&rtv, &atv, >=))
887 			goto done;
888 		ttv = atv;
889 		timevalsub(&ttv, &rtv);
890 		timo = ttv.tv_sec > 24 * 60 * 60 ?
891 		    24 * 60 * 60 * hz : tvtohz(&ttv);
892 	}
893 	/*
894 	 * An event of interest may occur while we do not hold
895 	 * sellock, so check TDF_SELECT and the number of collisions
896 	 * and rescan the file descriptors if necessary.
897 	 */
898 	mtx_lock_spin(&sched_lock);
899 	if ((td->td_flags & TDF_SELECT) == 0 || nselcoll != ncoll) {
900 		mtx_unlock_spin(&sched_lock);
901 		goto retry;
902 	}
903 	mtx_unlock_spin(&sched_lock);
904 
905 	if (timo > 0)
906 		error = cv_timedwait_sig(&selwait, &sellock, timo);
907 	else
908 		error = cv_wait_sig(&selwait, &sellock);
909 
910 	if (error == 0)
911 		goto retry;
912 
913 done:
914 	clear_selinfo_list(td);
915 	mtx_lock_spin(&sched_lock);
916 	td->td_flags &= ~TDF_SELECT;
917 	mtx_unlock_spin(&sched_lock);
918 	mtx_unlock(&sellock);
919 
920 done_nosellock:
921 	/* poll is not restarted after signals... */
922 	if (error == ERESTART)
923 		error = EINTR;
924 	if (error == EWOULDBLOCK)
925 		error = 0;
926 	if (error == 0) {
927 		error = copyout(bits, uap->fds, ni);
928 		if (error)
929 			goto out;
930 	}
931 out:
932 	if (ni > sizeof(smallbits))
933 		free(bits, M_TEMP);
934 done2:
935 	return (error);
936 }
937 
938 static int
939 pollscan(td, fds, nfd)
940 	struct thread *td;
941 	struct pollfd *fds;
942 	u_int nfd;
943 {
944 	register struct filedesc *fdp = td->td_proc->p_fd;
945 	int i;
946 	struct file *fp;
947 	int n = 0;
948 
949 	FILEDESC_LOCK(fdp);
950 	for (i = 0; i < nfd; i++, fds++) {
951 		if (fds->fd >= fdp->fd_nfiles) {
952 			fds->revents = POLLNVAL;
953 			n++;
954 		} else if (fds->fd < 0) {
955 			fds->revents = 0;
956 		} else {
957 			fp = fdp->fd_ofiles[fds->fd];
958 			if (fp == NULL) {
959 				fds->revents = POLLNVAL;
960 				n++;
961 			} else {
962 				/*
963 				 * Note: backend also returns POLLHUP and
964 				 * POLLERR if appropriate.
965 				 */
966 				fds->revents = fo_poll(fp, fds->events,
967 				    td->td_ucred, td);
968 				if (fds->revents != 0)
969 					n++;
970 			}
971 		}
972 	}
973 	FILEDESC_UNLOCK(fdp);
974 	td->td_retval[0] = n;
975 	return (0);
976 }
977 
978 /*
979  * OpenBSD poll system call.
980  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
981  */
982 #ifndef _SYS_SYSPROTO_H_
983 struct openbsd_poll_args {
984 	struct pollfd *fds;
985 	u_int	nfds;
986 	int	timeout;
987 };
988 #endif
989 /*
990  * MPSAFE
991  */
992 int
993 openbsd_poll(td, uap)
994 	register struct thread *td;
995 	register struct openbsd_poll_args *uap;
996 {
997 	return (poll(td, (struct poll_args *)uap));
998 }
999 
1000 /*
1001  * Remove the references to the thread from all of the objects
1002  * we were polling.
1003  *
1004  * This code assumes that the underlying owner of the selinfo
1005  * structure will hold sellock before it changes it, and that
1006  * it will unlink itself from our list if it goes away.
1007  */
1008 void
1009 clear_selinfo_list(td)
1010 	struct thread *td;
1011 {
1012 	struct selinfo *si;
1013 
1014 	mtx_assert(&sellock, MA_OWNED);
1015 	TAILQ_FOREACH(si, &td->td_selq, si_thrlist)
1016 		si->si_thread = NULL;
1017 	TAILQ_INIT(&td->td_selq);
1018 }
1019 
1020 /*
1021  * Record a select request.
1022  */
1023 void
1024 selrecord(selector, sip)
1025 	struct thread *selector;
1026 	struct selinfo *sip;
1027 {
1028 
1029 	mtx_lock(&sellock);
1030 	/*
1031 	 * If the selinfo's thread pointer is NULL then take ownership of it.
1032 	 *
1033 	 * If the thread pointer is not NULL and it points to another
1034 	 * thread, then we have a collision.
1035 	 *
1036 	 * If the thread pointer is not NULL and points back to us then leave
1037 	 * it alone as we've already added pointed it at us and added it to
1038 	 * our list.
1039 	 */
1040 	if (sip->si_thread == NULL) {
1041 		sip->si_thread = selector;
1042 		TAILQ_INSERT_TAIL(&selector->td_selq, sip, si_thrlist);
1043 	} else if (sip->si_thread != selector) {
1044 		sip->si_flags |= SI_COLL;
1045 	}
1046 
1047 	mtx_unlock(&sellock);
1048 }
1049 
1050 /* Wake up a selecting thread. */
1051 void
1052 selwakeup(sip)
1053 	struct selinfo *sip;
1054 {
1055 	doselwakeup(sip, -1);
1056 }
1057 
1058 /* Wake up a selecting thread, and set its priority. */
1059 void
1060 selwakeuppri(sip, pri)
1061 	struct selinfo *sip;
1062 	int pri;
1063 {
1064 	doselwakeup(sip, pri);
1065 }
1066 
1067 /*
1068  * Do a wakeup when a selectable event occurs.
1069  */
1070 static void
1071 doselwakeup(sip, pri)
1072 	struct selinfo *sip;
1073 	int pri;
1074 {
1075 	struct thread *td;
1076 
1077 	mtx_lock(&sellock);
1078 	td = sip->si_thread;
1079 	if ((sip->si_flags & SI_COLL) != 0) {
1080 		nselcoll++;
1081 		sip->si_flags &= ~SI_COLL;
1082 		cv_broadcastpri(&selwait, pri);
1083 	}
1084 	if (td == NULL) {
1085 		mtx_unlock(&sellock);
1086 		return;
1087 	}
1088 	TAILQ_REMOVE(&td->td_selq, sip, si_thrlist);
1089 	sip->si_thread = NULL;
1090 	mtx_lock_spin(&sched_lock);
1091 	td->td_flags &= ~TDF_SELECT;
1092 	mtx_unlock_spin(&sched_lock);
1093 	sleepq_remove(td, &selwait);
1094 	mtx_unlock(&sellock);
1095 }
1096 
1097 static void selectinit(void *);
1098 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, selectinit, NULL)
1099 
1100 /* ARGSUSED*/
1101 static void
1102 selectinit(dummy)
1103 	void *dummy;
1104 {
1105 	cv_init(&selwait, "select");
1106 	mtx_init(&sellock, "sellck", NULL, MTX_DEF);
1107 }
1108