xref: /freebsd/sys/kern/sys_generic.c (revision 955c8cbb4960e6cf3602de144b1b9154a5092968)
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_capsicum.h"
41 #include "opt_compat.h"
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/capability.h>
48 #include <sys/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/fcntl.h>
51 #include <sys/file.h>
52 #include <sys/proc.h>
53 #include <sys/signalvar.h>
54 #include <sys/socketvar.h>
55 #include <sys/uio.h>
56 #include <sys/kernel.h>
57 #include <sys/ktr.h>
58 #include <sys/limits.h>
59 #include <sys/malloc.h>
60 #include <sys/poll.h>
61 #include <sys/resourcevar.h>
62 #include <sys/selinfo.h>
63 #include <sys/sleepqueue.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/vnode.h>
68 #include <sys/bio.h>
69 #include <sys/buf.h>
70 #include <sys/condvar.h>
71 #ifdef KTRACE
72 #include <sys/ktrace.h>
73 #endif
74 
75 #include <security/audit/audit.h>
76 
77 int iosize_max_clamp = 1;
78 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
79     &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
80 /*
81  * Assert that the return value of read(2) and write(2) syscalls fits
82  * into a register.  If not, an architecture will need to provide the
83  * usermode wrappers to reconstruct the result.
84  */
85 CTASSERT(sizeof(register_t) >= sizeof(size_t));
86 
87 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
88 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
89 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
90 
91 static int	pollout(struct thread *, struct pollfd *, struct pollfd *,
92 		    u_int);
93 static int	pollscan(struct thread *, struct pollfd *, u_int);
94 static int	pollrescan(struct thread *);
95 static int	selscan(struct thread *, fd_mask **, fd_mask **, int);
96 static int	selrescan(struct thread *, fd_mask **, fd_mask **);
97 static void	selfdalloc(struct thread *, void *);
98 static void	selfdfree(struct seltd *, struct selfd *);
99 static int	dofileread(struct thread *, int, struct file *, struct uio *,
100 		    off_t, int);
101 static int	dofilewrite(struct thread *, int, struct file *, struct uio *,
102 		    off_t, int);
103 static void	doselwakeup(struct selinfo *, int);
104 static void	seltdinit(struct thread *);
105 static int	seltdwait(struct thread *, int);
106 static void	seltdclear(struct thread *);
107 
108 /*
109  * One seltd per-thread allocated on demand as needed.
110  *
111  *	t - protected by st_mtx
112  * 	k - Only accessed by curthread or read-only
113  */
114 struct seltd {
115 	STAILQ_HEAD(, selfd)	st_selq;	/* (k) List of selfds. */
116 	struct selfd		*st_free1;	/* (k) free fd for read set. */
117 	struct selfd		*st_free2;	/* (k) free fd for write set. */
118 	struct mtx		st_mtx;		/* Protects struct seltd */
119 	struct cv		st_wait;	/* (t) Wait channel. */
120 	int			st_flags;	/* (t) SELTD_ flags. */
121 };
122 
123 #define	SELTD_PENDING	0x0001			/* We have pending events. */
124 #define	SELTD_RESCAN	0x0002			/* Doing a rescan. */
125 
126 /*
127  * One selfd allocated per-thread per-file-descriptor.
128  *	f - protected by sf_mtx
129  */
130 struct selfd {
131 	STAILQ_ENTRY(selfd)	sf_link;	/* (k) fds owned by this td. */
132 	TAILQ_ENTRY(selfd)	sf_threads;	/* (f) fds on this selinfo. */
133 	struct selinfo		*sf_si;		/* (f) selinfo when linked. */
134 	struct mtx		*sf_mtx;	/* Pointer to selinfo mtx. */
135 	struct seltd		*sf_td;		/* (k) owning seltd. */
136 	void			*sf_cookie;	/* (k) fd or pollfd. */
137 };
138 
139 static uma_zone_t selfd_zone;
140 static struct mtx_pool *mtxpool_select;
141 
142 #ifndef _SYS_SYSPROTO_H_
143 struct read_args {
144 	int	fd;
145 	void	*buf;
146 	size_t	nbyte;
147 };
148 #endif
149 int
150 sys_read(td, uap)
151 	struct thread *td;
152 	struct read_args *uap;
153 {
154 	struct uio auio;
155 	struct iovec aiov;
156 	int error;
157 
158 	if (uap->nbyte > IOSIZE_MAX)
159 		return (EINVAL);
160 	aiov.iov_base = uap->buf;
161 	aiov.iov_len = uap->nbyte;
162 	auio.uio_iov = &aiov;
163 	auio.uio_iovcnt = 1;
164 	auio.uio_resid = uap->nbyte;
165 	auio.uio_segflg = UIO_USERSPACE;
166 	error = kern_readv(td, uap->fd, &auio);
167 	return(error);
168 }
169 
170 /*
171  * Positioned read system call
172  */
173 #ifndef _SYS_SYSPROTO_H_
174 struct pread_args {
175 	int	fd;
176 	void	*buf;
177 	size_t	nbyte;
178 	int	pad;
179 	off_t	offset;
180 };
181 #endif
182 int
183 sys_pread(td, uap)
184 	struct thread *td;
185 	struct pread_args *uap;
186 {
187 	struct uio auio;
188 	struct iovec aiov;
189 	int error;
190 
191 	if (uap->nbyte > IOSIZE_MAX)
192 		return (EINVAL);
193 	aiov.iov_base = uap->buf;
194 	aiov.iov_len = uap->nbyte;
195 	auio.uio_iov = &aiov;
196 	auio.uio_iovcnt = 1;
197 	auio.uio_resid = uap->nbyte;
198 	auio.uio_segflg = UIO_USERSPACE;
199 	error = kern_preadv(td, uap->fd, &auio, uap->offset);
200 	return(error);
201 }
202 
203 int
204 freebsd6_pread(td, uap)
205 	struct thread *td;
206 	struct freebsd6_pread_args *uap;
207 {
208 	struct pread_args oargs;
209 
210 	oargs.fd = uap->fd;
211 	oargs.buf = uap->buf;
212 	oargs.nbyte = uap->nbyte;
213 	oargs.offset = uap->offset;
214 	return (sys_pread(td, &oargs));
215 }
216 
217 /*
218  * Scatter read system call.
219  */
220 #ifndef _SYS_SYSPROTO_H_
221 struct readv_args {
222 	int	fd;
223 	struct	iovec *iovp;
224 	u_int	iovcnt;
225 };
226 #endif
227 int
228 sys_readv(struct thread *td, struct readv_args *uap)
229 {
230 	struct uio *auio;
231 	int error;
232 
233 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
234 	if (error)
235 		return (error);
236 	error = kern_readv(td, uap->fd, auio);
237 	free(auio, M_IOV);
238 	return (error);
239 }
240 
241 int
242 kern_readv(struct thread *td, int fd, struct uio *auio)
243 {
244 	struct file *fp;
245 	int error;
246 
247 	error = fget_read(td, fd, CAP_READ | CAP_SEEK, &fp);
248 	if (error)
249 		return (error);
250 	error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
251 	fdrop(fp, td);
252 	return (error);
253 }
254 
255 /*
256  * Scatter positioned read system call.
257  */
258 #ifndef _SYS_SYSPROTO_H_
259 struct preadv_args {
260 	int	fd;
261 	struct	iovec *iovp;
262 	u_int	iovcnt;
263 	off_t	offset;
264 };
265 #endif
266 int
267 sys_preadv(struct thread *td, struct preadv_args *uap)
268 {
269 	struct uio *auio;
270 	int error;
271 
272 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
273 	if (error)
274 		return (error);
275 	error = kern_preadv(td, uap->fd, auio, uap->offset);
276 	free(auio, M_IOV);
277 	return (error);
278 }
279 
280 int
281 kern_preadv(td, fd, auio, offset)
282 	struct thread *td;
283 	int fd;
284 	struct uio *auio;
285 	off_t offset;
286 {
287 	struct file *fp;
288 	int error;
289 
290 	error = fget_read(td, fd, CAP_READ, &fp);
291 	if (error)
292 		return (error);
293 	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
294 		error = ESPIPE;
295 	else if (offset < 0 && fp->f_vnode->v_type != VCHR)
296 		error = EINVAL;
297 	else
298 		error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
299 	fdrop(fp, td);
300 	return (error);
301 }
302 
303 /*
304  * Common code for readv and preadv that reads data in
305  * from a file using the passed in uio, offset, and flags.
306  */
307 static int
308 dofileread(td, fd, fp, auio, offset, flags)
309 	struct thread *td;
310 	int fd;
311 	struct file *fp;
312 	struct uio *auio;
313 	off_t offset;
314 	int flags;
315 {
316 	ssize_t cnt;
317 	int error;
318 #ifdef KTRACE
319 	struct uio *ktruio = NULL;
320 #endif
321 
322 	/* Finish zero length reads right here */
323 	if (auio->uio_resid == 0) {
324 		td->td_retval[0] = 0;
325 		return(0);
326 	}
327 	auio->uio_rw = UIO_READ;
328 	auio->uio_offset = offset;
329 	auio->uio_td = td;
330 #ifdef KTRACE
331 	if (KTRPOINT(td, KTR_GENIO))
332 		ktruio = cloneuio(auio);
333 #endif
334 	cnt = auio->uio_resid;
335 	if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
336 		if (auio->uio_resid != cnt && (error == ERESTART ||
337 		    error == EINTR || error == EWOULDBLOCK))
338 			error = 0;
339 	}
340 	cnt -= auio->uio_resid;
341 #ifdef KTRACE
342 	if (ktruio != NULL) {
343 		ktruio->uio_resid = cnt;
344 		ktrgenio(fd, UIO_READ, ktruio, error);
345 	}
346 #endif
347 	td->td_retval[0] = cnt;
348 	return (error);
349 }
350 
351 #ifndef _SYS_SYSPROTO_H_
352 struct write_args {
353 	int	fd;
354 	const void *buf;
355 	size_t	nbyte;
356 };
357 #endif
358 int
359 sys_write(td, uap)
360 	struct thread *td;
361 	struct write_args *uap;
362 {
363 	struct uio auio;
364 	struct iovec aiov;
365 	int error;
366 
367 	if (uap->nbyte > IOSIZE_MAX)
368 		return (EINVAL);
369 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
370 	aiov.iov_len = uap->nbyte;
371 	auio.uio_iov = &aiov;
372 	auio.uio_iovcnt = 1;
373 	auio.uio_resid = uap->nbyte;
374 	auio.uio_segflg = UIO_USERSPACE;
375 	error = kern_writev(td, uap->fd, &auio);
376 	return(error);
377 }
378 
379 /*
380  * Positioned write system call.
381  */
382 #ifndef _SYS_SYSPROTO_H_
383 struct pwrite_args {
384 	int	fd;
385 	const void *buf;
386 	size_t	nbyte;
387 	int	pad;
388 	off_t	offset;
389 };
390 #endif
391 int
392 sys_pwrite(td, uap)
393 	struct thread *td;
394 	struct pwrite_args *uap;
395 {
396 	struct uio auio;
397 	struct iovec aiov;
398 	int error;
399 
400 	if (uap->nbyte > IOSIZE_MAX)
401 		return (EINVAL);
402 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
403 	aiov.iov_len = uap->nbyte;
404 	auio.uio_iov = &aiov;
405 	auio.uio_iovcnt = 1;
406 	auio.uio_resid = uap->nbyte;
407 	auio.uio_segflg = UIO_USERSPACE;
408 	error = kern_pwritev(td, uap->fd, &auio, uap->offset);
409 	return(error);
410 }
411 
412 int
413 freebsd6_pwrite(td, uap)
414 	struct thread *td;
415 	struct freebsd6_pwrite_args *uap;
416 {
417 	struct pwrite_args oargs;
418 
419 	oargs.fd = uap->fd;
420 	oargs.buf = uap->buf;
421 	oargs.nbyte = uap->nbyte;
422 	oargs.offset = uap->offset;
423 	return (sys_pwrite(td, &oargs));
424 }
425 
426 /*
427  * Gather write system call.
428  */
429 #ifndef _SYS_SYSPROTO_H_
430 struct writev_args {
431 	int	fd;
432 	struct	iovec *iovp;
433 	u_int	iovcnt;
434 };
435 #endif
436 int
437 sys_writev(struct thread *td, struct writev_args *uap)
438 {
439 	struct uio *auio;
440 	int error;
441 
442 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
443 	if (error)
444 		return (error);
445 	error = kern_writev(td, uap->fd, auio);
446 	free(auio, M_IOV);
447 	return (error);
448 }
449 
450 int
451 kern_writev(struct thread *td, int fd, struct uio *auio)
452 {
453 	struct file *fp;
454 	int error;
455 
456 	error = fget_write(td, fd, CAP_WRITE | CAP_SEEK, &fp);
457 	if (error)
458 		return (error);
459 	error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
460 	fdrop(fp, td);
461 	return (error);
462 }
463 
464 /*
465  * Gather positioned write system call.
466  */
467 #ifndef _SYS_SYSPROTO_H_
468 struct pwritev_args {
469 	int	fd;
470 	struct	iovec *iovp;
471 	u_int	iovcnt;
472 	off_t	offset;
473 };
474 #endif
475 int
476 sys_pwritev(struct thread *td, struct pwritev_args *uap)
477 {
478 	struct uio *auio;
479 	int error;
480 
481 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
482 	if (error)
483 		return (error);
484 	error = kern_pwritev(td, uap->fd, auio, uap->offset);
485 	free(auio, M_IOV);
486 	return (error);
487 }
488 
489 int
490 kern_pwritev(td, fd, auio, offset)
491 	struct thread *td;
492 	struct uio *auio;
493 	int fd;
494 	off_t offset;
495 {
496 	struct file *fp;
497 	int error;
498 
499 	error = fget_write(td, fd, CAP_WRITE, &fp);
500 	if (error)
501 		return (error);
502 	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
503 		error = ESPIPE;
504 	else if (offset < 0 && fp->f_vnode->v_type != VCHR)
505 		error = EINVAL;
506 	else
507 		error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
508 	fdrop(fp, td);
509 	return (error);
510 }
511 
512 /*
513  * Common code for writev and pwritev that writes data to
514  * a file using the passed in uio, offset, and flags.
515  */
516 static int
517 dofilewrite(td, fd, fp, auio, offset, flags)
518 	struct thread *td;
519 	int fd;
520 	struct file *fp;
521 	struct uio *auio;
522 	off_t offset;
523 	int flags;
524 {
525 	ssize_t cnt;
526 	int error;
527 #ifdef KTRACE
528 	struct uio *ktruio = NULL;
529 #endif
530 
531 	auio->uio_rw = UIO_WRITE;
532 	auio->uio_td = td;
533 	auio->uio_offset = offset;
534 #ifdef KTRACE
535 	if (KTRPOINT(td, KTR_GENIO))
536 		ktruio = cloneuio(auio);
537 #endif
538 	cnt = auio->uio_resid;
539 	if (fp->f_type == DTYPE_VNODE &&
540 	    (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
541 		bwillwrite();
542 	if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
543 		if (auio->uio_resid != cnt && (error == ERESTART ||
544 		    error == EINTR || error == EWOULDBLOCK))
545 			error = 0;
546 		/* Socket layer is responsible for issuing SIGPIPE. */
547 		if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
548 			PROC_LOCK(td->td_proc);
549 			tdsignal(td, SIGPIPE);
550 			PROC_UNLOCK(td->td_proc);
551 		}
552 	}
553 	cnt -= auio->uio_resid;
554 #ifdef KTRACE
555 	if (ktruio != NULL) {
556 		ktruio->uio_resid = cnt;
557 		ktrgenio(fd, UIO_WRITE, ktruio, error);
558 	}
559 #endif
560 	td->td_retval[0] = cnt;
561 	return (error);
562 }
563 
564 /*
565  * Truncate a file given a file descriptor.
566  *
567  * Can't use fget_write() here, since must return EINVAL and not EBADF if the
568  * descriptor isn't writable.
569  */
570 int
571 kern_ftruncate(td, fd, length)
572 	struct thread *td;
573 	int fd;
574 	off_t length;
575 {
576 	struct file *fp;
577 	int error;
578 
579 	AUDIT_ARG_FD(fd);
580 	if (length < 0)
581 		return (EINVAL);
582 	error = fget(td, fd, CAP_FTRUNCATE, &fp);
583 	if (error)
584 		return (error);
585 	AUDIT_ARG_FILE(td->td_proc, fp);
586 	if (!(fp->f_flag & FWRITE)) {
587 		fdrop(fp, td);
588 		return (EINVAL);
589 	}
590 	error = fo_truncate(fp, length, td->td_ucred, td);
591 	fdrop(fp, td);
592 	return (error);
593 }
594 
595 #ifndef _SYS_SYSPROTO_H_
596 struct ftruncate_args {
597 	int	fd;
598 	int	pad;
599 	off_t	length;
600 };
601 #endif
602 int
603 sys_ftruncate(td, uap)
604 	struct thread *td;
605 	struct ftruncate_args *uap;
606 {
607 
608 	return (kern_ftruncate(td, uap->fd, uap->length));
609 }
610 
611 #if defined(COMPAT_43)
612 #ifndef _SYS_SYSPROTO_H_
613 struct oftruncate_args {
614 	int	fd;
615 	long	length;
616 };
617 #endif
618 int
619 oftruncate(td, uap)
620 	struct thread *td;
621 	struct oftruncate_args *uap;
622 {
623 
624 	return (kern_ftruncate(td, uap->fd, uap->length));
625 }
626 #endif /* COMPAT_43 */
627 
628 #ifndef _SYS_SYSPROTO_H_
629 struct ioctl_args {
630 	int	fd;
631 	u_long	com;
632 	caddr_t	data;
633 };
634 #endif
635 /* ARGSUSED */
636 int
637 sys_ioctl(struct thread *td, struct ioctl_args *uap)
638 {
639 	u_long com;
640 	int arg, error;
641 	u_int size;
642 	caddr_t data;
643 
644 	if (uap->com > 0xffffffff) {
645 		printf(
646 		    "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
647 		    td->td_proc->p_pid, td->td_name, uap->com);
648 		uap->com &= 0xffffffff;
649 	}
650 	com = uap->com;
651 
652 	/*
653 	 * Interpret high order word to find amount of data to be
654 	 * copied to/from the user's address space.
655 	 */
656 	size = IOCPARM_LEN(com);
657 	if ((size > IOCPARM_MAX) ||
658 	    ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
659 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
660 	    ((com & IOC_OUT) && size == 0) ||
661 #else
662 	    ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
663 #endif
664 	    ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
665 		return (ENOTTY);
666 
667 	if (size > 0) {
668 		if (com & IOC_VOID) {
669 			/* Integer argument. */
670 			arg = (intptr_t)uap->data;
671 			data = (void *)&arg;
672 			size = 0;
673 		} else
674 			data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
675 	} else
676 		data = (void *)&uap->data;
677 	if (com & IOC_IN) {
678 		error = copyin(uap->data, data, (u_int)size);
679 		if (error) {
680 			if (size > 0)
681 				free(data, M_IOCTLOPS);
682 			return (error);
683 		}
684 	} else if (com & IOC_OUT) {
685 		/*
686 		 * Zero the buffer so the user always
687 		 * gets back something deterministic.
688 		 */
689 		bzero(data, size);
690 	}
691 
692 	error = kern_ioctl(td, uap->fd, com, data);
693 
694 	if (error == 0 && (com & IOC_OUT))
695 		error = copyout(data, uap->data, (u_int)size);
696 
697 	if (size > 0)
698 		free(data, M_IOCTLOPS);
699 	return (error);
700 }
701 
702 int
703 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
704 {
705 	struct file *fp;
706 	struct filedesc *fdp;
707 	int error;
708 	int tmp;
709 
710 	AUDIT_ARG_FD(fd);
711 	AUDIT_ARG_CMD(com);
712 	if ((error = fget(td, fd, CAP_IOCTL, &fp)) != 0)
713 		return (error);
714 	if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
715 		fdrop(fp, td);
716 		return (EBADF);
717 	}
718 	fdp = td->td_proc->p_fd;
719 	switch (com) {
720 	case FIONCLEX:
721 		FILEDESC_XLOCK(fdp);
722 		fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
723 		FILEDESC_XUNLOCK(fdp);
724 		goto out;
725 	case FIOCLEX:
726 		FILEDESC_XLOCK(fdp);
727 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
728 		FILEDESC_XUNLOCK(fdp);
729 		goto out;
730 	case FIONBIO:
731 		if ((tmp = *(int *)data))
732 			atomic_set_int(&fp->f_flag, FNONBLOCK);
733 		else
734 			atomic_clear_int(&fp->f_flag, FNONBLOCK);
735 		data = (void *)&tmp;
736 		break;
737 	case FIOASYNC:
738 		if ((tmp = *(int *)data))
739 			atomic_set_int(&fp->f_flag, FASYNC);
740 		else
741 			atomic_clear_int(&fp->f_flag, FASYNC);
742 		data = (void *)&tmp;
743 		break;
744 	}
745 
746 	error = fo_ioctl(fp, com, data, td->td_ucred, td);
747 out:
748 	fdrop(fp, td);
749 	return (error);
750 }
751 
752 int
753 poll_no_poll(int events)
754 {
755 	/*
756 	 * Return true for read/write.  If the user asked for something
757 	 * special, return POLLNVAL, so that clients have a way of
758 	 * determining reliably whether or not the extended
759 	 * functionality is present without hard-coding knowledge
760 	 * of specific filesystem implementations.
761 	 */
762 	if (events & ~POLLSTANDARD)
763 		return (POLLNVAL);
764 
765 	return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
766 }
767 
768 int
769 sys_pselect(struct thread *td, struct pselect_args *uap)
770 {
771 	struct timespec ts;
772 	struct timeval tv, *tvp;
773 	sigset_t set, *uset;
774 	int error;
775 
776 	if (uap->ts != NULL) {
777 		error = copyin(uap->ts, &ts, sizeof(ts));
778 		if (error != 0)
779 		    return (error);
780 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
781 		tvp = &tv;
782 	} else
783 		tvp = NULL;
784 	if (uap->sm != NULL) {
785 		error = copyin(uap->sm, &set, sizeof(set));
786 		if (error != 0)
787 			return (error);
788 		uset = &set;
789 	} else
790 		uset = NULL;
791 	return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
792 	    uset, NFDBITS));
793 }
794 
795 int
796 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
797     struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
798 {
799 	int error;
800 
801 	if (uset != NULL) {
802 		error = kern_sigprocmask(td, SIG_SETMASK, uset,
803 		    &td->td_oldsigmask, 0);
804 		if (error != 0)
805 			return (error);
806 		td->td_pflags |= TDP_OLDMASK;
807 		/*
808 		 * Make sure that ast() is called on return to
809 		 * usermode and TDP_OLDMASK is cleared, restoring old
810 		 * sigmask.
811 		 */
812 		thread_lock(td);
813 		td->td_flags |= TDF_ASTPENDING;
814 		thread_unlock(td);
815 	}
816 	error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
817 	return (error);
818 }
819 
820 #ifndef _SYS_SYSPROTO_H_
821 struct select_args {
822 	int	nd;
823 	fd_set	*in, *ou, *ex;
824 	struct	timeval *tv;
825 };
826 #endif
827 int
828 sys_select(struct thread *td, struct select_args *uap)
829 {
830 	struct timeval tv, *tvp;
831 	int error;
832 
833 	if (uap->tv != NULL) {
834 		error = copyin(uap->tv, &tv, sizeof(tv));
835 		if (error)
836 			return (error);
837 		tvp = &tv;
838 	} else
839 		tvp = NULL;
840 
841 	return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
842 	    NFDBITS));
843 }
844 
845 /*
846  * In the unlikely case when user specified n greater then the last
847  * open file descriptor, check that no bits are set after the last
848  * valid fd.  We must return EBADF if any is set.
849  *
850  * There are applications that rely on the behaviour.
851  *
852  * nd is fd_lastfile + 1.
853  */
854 static int
855 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
856 {
857 	char *addr, *oaddr;
858 	int b, i, res;
859 	uint8_t bits;
860 
861 	if (nd >= ndu || fd_in == NULL)
862 		return (0);
863 
864 	oaddr = NULL;
865 	bits = 0; /* silence gcc */
866 	for (i = nd; i < ndu; i++) {
867 		b = i / NBBY;
868 #if BYTE_ORDER == LITTLE_ENDIAN
869 		addr = (char *)fd_in + b;
870 #else
871 		addr = (char *)fd_in;
872 		if (abi_nfdbits == NFDBITS) {
873 			addr += rounddown(b, sizeof(fd_mask)) +
874 			    sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
875 		} else {
876 			addr += rounddown(b, sizeof(uint32_t)) +
877 			    sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
878 		}
879 #endif
880 		if (addr != oaddr) {
881 			res = fubyte(addr);
882 			if (res == -1)
883 				return (EFAULT);
884 			oaddr = addr;
885 			bits = res;
886 		}
887 		if ((bits & (1 << (i % NBBY))) != 0)
888 			return (EBADF);
889 	}
890 	return (0);
891 }
892 
893 int
894 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
895     fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
896 {
897 	struct filedesc *fdp;
898 	/*
899 	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
900 	 * infds with the new FD_SETSIZE of 1024, and more than enough for
901 	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
902 	 * of 256.
903 	 */
904 	fd_mask s_selbits[howmany(2048, NFDBITS)];
905 	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
906 	struct timeval atv, rtv, ttv;
907 	int error, lf, ndu, timo;
908 	u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
909 
910 	if (nd < 0)
911 		return (EINVAL);
912 	fdp = td->td_proc->p_fd;
913 	ndu = nd;
914 	lf = fdp->fd_lastfile;
915 	if (nd > lf + 1)
916 		nd = lf + 1;
917 
918 	error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
919 	if (error != 0)
920 		return (error);
921 	error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
922 	if (error != 0)
923 		return (error);
924 	error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
925 	if (error != 0)
926 		return (error);
927 
928 	/*
929 	 * Allocate just enough bits for the non-null fd_sets.  Use the
930 	 * preallocated auto buffer if possible.
931 	 */
932 	nfdbits = roundup(nd, NFDBITS);
933 	ncpbytes = nfdbits / NBBY;
934 	ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
935 	nbufbytes = 0;
936 	if (fd_in != NULL)
937 		nbufbytes += 2 * ncpbytes;
938 	if (fd_ou != NULL)
939 		nbufbytes += 2 * ncpbytes;
940 	if (fd_ex != NULL)
941 		nbufbytes += 2 * ncpbytes;
942 	if (nbufbytes <= sizeof s_selbits)
943 		selbits = &s_selbits[0];
944 	else
945 		selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
946 
947 	/*
948 	 * Assign pointers into the bit buffers and fetch the input bits.
949 	 * Put the output buffers together so that they can be bzeroed
950 	 * together.
951 	 */
952 	sbp = selbits;
953 #define	getbits(name, x) \
954 	do {								\
955 		if (name == NULL) {					\
956 			ibits[x] = NULL;				\
957 			obits[x] = NULL;				\
958 		} else {						\
959 			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
960 			obits[x] = sbp;					\
961 			sbp += ncpbytes / sizeof *sbp;			\
962 			error = copyin(name, ibits[x], ncpubytes);	\
963 			if (error != 0)					\
964 				goto done;				\
965 			bzero((char *)ibits[x] + ncpubytes,		\
966 			    ncpbytes - ncpubytes);			\
967 		}							\
968 	} while (0)
969 	getbits(fd_in, 0);
970 	getbits(fd_ou, 1);
971 	getbits(fd_ex, 2);
972 #undef	getbits
973 
974 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
975 	/*
976 	 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
977 	 * we are running under 32-bit emulation. This should be more
978 	 * generic.
979 	 */
980 #define swizzle_fdset(bits)						\
981 	if (abi_nfdbits != NFDBITS && bits != NULL) {			\
982 		int i;							\
983 		for (i = 0; i < ncpbytes / sizeof *sbp; i++)		\
984 			bits[i] = (bits[i] >> 32) | (bits[i] << 32);	\
985 	}
986 #else
987 #define swizzle_fdset(bits)
988 #endif
989 
990 	/* Make sure the bit order makes it through an ABI transition */
991 	swizzle_fdset(ibits[0]);
992 	swizzle_fdset(ibits[1]);
993 	swizzle_fdset(ibits[2]);
994 
995 	if (nbufbytes != 0)
996 		bzero(selbits, nbufbytes / 2);
997 
998 	if (tvp != NULL) {
999 		atv = *tvp;
1000 		if (itimerfix(&atv)) {
1001 			error = EINVAL;
1002 			goto done;
1003 		}
1004 		getmicrouptime(&rtv);
1005 		timevaladd(&atv, &rtv);
1006 	} else {
1007 		atv.tv_sec = 0;
1008 		atv.tv_usec = 0;
1009 	}
1010 	timo = 0;
1011 	seltdinit(td);
1012 	/* Iterate until the timeout expires or descriptors become ready. */
1013 	for (;;) {
1014 		error = selscan(td, ibits, obits, nd);
1015 		if (error || td->td_retval[0] != 0)
1016 			break;
1017 		if (atv.tv_sec || atv.tv_usec) {
1018 			getmicrouptime(&rtv);
1019 			if (timevalcmp(&rtv, &atv, >=))
1020 				break;
1021 			ttv = atv;
1022 			timevalsub(&ttv, &rtv);
1023 			timo = ttv.tv_sec > 24 * 60 * 60 ?
1024 			    24 * 60 * 60 * hz : tvtohz(&ttv);
1025 		}
1026 		error = seltdwait(td, timo);
1027 		if (error)
1028 			break;
1029 		error = selrescan(td, ibits, obits);
1030 		if (error || td->td_retval[0] != 0)
1031 			break;
1032 	}
1033 	seltdclear(td);
1034 
1035 done:
1036 	/* select is not restarted after signals... */
1037 	if (error == ERESTART)
1038 		error = EINTR;
1039 	if (error == EWOULDBLOCK)
1040 		error = 0;
1041 
1042 	/* swizzle bit order back, if necessary */
1043 	swizzle_fdset(obits[0]);
1044 	swizzle_fdset(obits[1]);
1045 	swizzle_fdset(obits[2]);
1046 #undef swizzle_fdset
1047 
1048 #define	putbits(name, x) \
1049 	if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1050 		error = error2;
1051 	if (error == 0) {
1052 		int error2;
1053 
1054 		putbits(fd_in, 0);
1055 		putbits(fd_ou, 1);
1056 		putbits(fd_ex, 2);
1057 #undef putbits
1058 	}
1059 	if (selbits != &s_selbits[0])
1060 		free(selbits, M_SELECT);
1061 
1062 	return (error);
1063 }
1064 /*
1065  * Convert a select bit set to poll flags.
1066  *
1067  * The backend always returns POLLHUP/POLLERR if appropriate and we
1068  * return this as a set bit in any set.
1069  */
1070 static int select_flags[3] = {
1071     POLLRDNORM | POLLHUP | POLLERR,
1072     POLLWRNORM | POLLHUP | POLLERR,
1073     POLLRDBAND | POLLERR
1074 };
1075 
1076 /*
1077  * Compute the fo_poll flags required for a fd given by the index and
1078  * bit position in the fd_mask array.
1079  */
1080 static __inline int
1081 selflags(fd_mask **ibits, int idx, fd_mask bit)
1082 {
1083 	int flags;
1084 	int msk;
1085 
1086 	flags = 0;
1087 	for (msk = 0; msk < 3; msk++) {
1088 		if (ibits[msk] == NULL)
1089 			continue;
1090 		if ((ibits[msk][idx] & bit) == 0)
1091 			continue;
1092 		flags |= select_flags[msk];
1093 	}
1094 	return (flags);
1095 }
1096 
1097 /*
1098  * Set the appropriate output bits given a mask of fired events and the
1099  * input bits originally requested.
1100  */
1101 static __inline int
1102 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1103 {
1104 	int msk;
1105 	int n;
1106 
1107 	n = 0;
1108 	for (msk = 0; msk < 3; msk++) {
1109 		if ((events & select_flags[msk]) == 0)
1110 			continue;
1111 		if (ibits[msk] == NULL)
1112 			continue;
1113 		if ((ibits[msk][idx] & bit) == 0)
1114 			continue;
1115 		/*
1116 		 * XXX Check for a duplicate set.  This can occur because a
1117 		 * socket calls selrecord() twice for each poll() call
1118 		 * resulting in two selfds per real fd.  selrescan() will
1119 		 * call selsetbits twice as a result.
1120 		 */
1121 		if ((obits[msk][idx] & bit) != 0)
1122 			continue;
1123 		obits[msk][idx] |= bit;
1124 		n++;
1125 	}
1126 
1127 	return (n);
1128 }
1129 
1130 static __inline int
1131 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1132 {
1133 	struct file *fp;
1134 #ifdef CAPABILITIES
1135 	struct file *fp_fromcap;
1136 	int error;
1137 #endif
1138 
1139 	if ((fp = fget_unlocked(fdp, fd)) == NULL)
1140 		return (EBADF);
1141 #ifdef CAPABILITIES
1142 	/*
1143 	 * If the file descriptor is for a capability, test rights and use
1144 	 * the file descriptor references by the capability.
1145 	 */
1146 	error = cap_funwrap(fp, CAP_POLL_EVENT, &fp_fromcap);
1147 	if (error) {
1148 		fdrop(fp, curthread);
1149 		return (error);
1150 	}
1151 	if (fp != fp_fromcap) {
1152 		fhold(fp_fromcap);
1153 		fdrop(fp, curthread);
1154 		fp = fp_fromcap;
1155 	}
1156 #endif /* CAPABILITIES */
1157 	*fpp = fp;
1158 	return (0);
1159 }
1160 
1161 /*
1162  * Traverse the list of fds attached to this thread's seltd and check for
1163  * completion.
1164  */
1165 static int
1166 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1167 {
1168 	struct filedesc *fdp;
1169 	struct selinfo *si;
1170 	struct seltd *stp;
1171 	struct selfd *sfp;
1172 	struct selfd *sfn;
1173 	struct file *fp;
1174 	fd_mask bit;
1175 	int fd, ev, n, idx;
1176 	int error;
1177 
1178 	fdp = td->td_proc->p_fd;
1179 	stp = td->td_sel;
1180 	n = 0;
1181 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1182 		fd = (int)(uintptr_t)sfp->sf_cookie;
1183 		si = sfp->sf_si;
1184 		selfdfree(stp, sfp);
1185 		/* If the selinfo wasn't cleared the event didn't fire. */
1186 		if (si != NULL)
1187 			continue;
1188 		error = getselfd_cap(fdp, fd, &fp);
1189 		if (error)
1190 			return (error);
1191 		idx = fd / NFDBITS;
1192 		bit = (fd_mask)1 << (fd % NFDBITS);
1193 		ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1194 		fdrop(fp, td);
1195 		if (ev != 0)
1196 			n += selsetbits(ibits, obits, idx, bit, ev);
1197 	}
1198 	stp->st_flags = 0;
1199 	td->td_retval[0] = n;
1200 	return (0);
1201 }
1202 
1203 /*
1204  * Perform the initial filedescriptor scan and register ourselves with
1205  * each selinfo.
1206  */
1207 static int
1208 selscan(td, ibits, obits, nfd)
1209 	struct thread *td;
1210 	fd_mask **ibits, **obits;
1211 	int nfd;
1212 {
1213 	struct filedesc *fdp;
1214 	struct file *fp;
1215 	fd_mask bit;
1216 	int ev, flags, end, fd;
1217 	int n, idx;
1218 	int error;
1219 
1220 	fdp = td->td_proc->p_fd;
1221 	n = 0;
1222 	for (idx = 0, fd = 0; fd < nfd; idx++) {
1223 		end = imin(fd + NFDBITS, nfd);
1224 		for (bit = 1; fd < end; bit <<= 1, fd++) {
1225 			/* Compute the list of events we're interested in. */
1226 			flags = selflags(ibits, idx, bit);
1227 			if (flags == 0)
1228 				continue;
1229 			error = getselfd_cap(fdp, fd, &fp);
1230 			if (error)
1231 				return (error);
1232 			selfdalloc(td, (void *)(uintptr_t)fd);
1233 			ev = fo_poll(fp, flags, td->td_ucred, td);
1234 			fdrop(fp, td);
1235 			if (ev != 0)
1236 				n += selsetbits(ibits, obits, idx, bit, ev);
1237 		}
1238 	}
1239 
1240 	td->td_retval[0] = n;
1241 	return (0);
1242 }
1243 
1244 #ifndef _SYS_SYSPROTO_H_
1245 struct poll_args {
1246 	struct pollfd *fds;
1247 	u_int	nfds;
1248 	int	timeout;
1249 };
1250 #endif
1251 int
1252 sys_poll(td, uap)
1253 	struct thread *td;
1254 	struct poll_args *uap;
1255 {
1256 	struct pollfd *bits;
1257 	struct pollfd smallbits[32];
1258 	struct timeval atv, rtv, ttv;
1259 	int error, timo;
1260 	u_int nfds;
1261 	size_t ni;
1262 
1263 	nfds = uap->nfds;
1264 	if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1265 		return (EINVAL);
1266 	ni = nfds * sizeof(struct pollfd);
1267 	if (ni > sizeof(smallbits))
1268 		bits = malloc(ni, M_TEMP, M_WAITOK);
1269 	else
1270 		bits = smallbits;
1271 	error = copyin(uap->fds, bits, ni);
1272 	if (error)
1273 		goto done;
1274 	if (uap->timeout != INFTIM) {
1275 		atv.tv_sec = uap->timeout / 1000;
1276 		atv.tv_usec = (uap->timeout % 1000) * 1000;
1277 		if (itimerfix(&atv)) {
1278 			error = EINVAL;
1279 			goto done;
1280 		}
1281 		getmicrouptime(&rtv);
1282 		timevaladd(&atv, &rtv);
1283 	} else {
1284 		atv.tv_sec = 0;
1285 		atv.tv_usec = 0;
1286 	}
1287 	timo = 0;
1288 	seltdinit(td);
1289 	/* Iterate until the timeout expires or descriptors become ready. */
1290 	for (;;) {
1291 		error = pollscan(td, bits, nfds);
1292 		if (error || td->td_retval[0] != 0)
1293 			break;
1294 		if (atv.tv_sec || atv.tv_usec) {
1295 			getmicrouptime(&rtv);
1296 			if (timevalcmp(&rtv, &atv, >=))
1297 				break;
1298 			ttv = atv;
1299 			timevalsub(&ttv, &rtv);
1300 			timo = ttv.tv_sec > 24 * 60 * 60 ?
1301 			    24 * 60 * 60 * hz : tvtohz(&ttv);
1302 		}
1303 		error = seltdwait(td, timo);
1304 		if (error)
1305 			break;
1306 		error = pollrescan(td);
1307 		if (error || td->td_retval[0] != 0)
1308 			break;
1309 	}
1310 	seltdclear(td);
1311 
1312 done:
1313 	/* poll is not restarted after signals... */
1314 	if (error == ERESTART)
1315 		error = EINTR;
1316 	if (error == EWOULDBLOCK)
1317 		error = 0;
1318 	if (error == 0) {
1319 		error = pollout(td, bits, uap->fds, nfds);
1320 		if (error)
1321 			goto out;
1322 	}
1323 out:
1324 	if (ni > sizeof(smallbits))
1325 		free(bits, M_TEMP);
1326 	return (error);
1327 }
1328 
1329 static int
1330 pollrescan(struct thread *td)
1331 {
1332 	struct seltd *stp;
1333 	struct selfd *sfp;
1334 	struct selfd *sfn;
1335 	struct selinfo *si;
1336 	struct filedesc *fdp;
1337 	struct file *fp;
1338 	struct pollfd *fd;
1339 	int n;
1340 
1341 	n = 0;
1342 	fdp = td->td_proc->p_fd;
1343 	stp = td->td_sel;
1344 	FILEDESC_SLOCK(fdp);
1345 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1346 		fd = (struct pollfd *)sfp->sf_cookie;
1347 		si = sfp->sf_si;
1348 		selfdfree(stp, sfp);
1349 		/* If the selinfo wasn't cleared the event didn't fire. */
1350 		if (si != NULL)
1351 			continue;
1352 		fp = fdp->fd_ofiles[fd->fd];
1353 #ifdef CAPABILITIES
1354 		if ((fp == NULL)
1355 		    || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1356 #else
1357 		if (fp == NULL) {
1358 #endif
1359 			fd->revents = POLLNVAL;
1360 			n++;
1361 			continue;
1362 		}
1363 
1364 		/*
1365 		 * Note: backend also returns POLLHUP and
1366 		 * POLLERR if appropriate.
1367 		 */
1368 		fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1369 		if (fd->revents != 0)
1370 			n++;
1371 	}
1372 	FILEDESC_SUNLOCK(fdp);
1373 	stp->st_flags = 0;
1374 	td->td_retval[0] = n;
1375 	return (0);
1376 }
1377 
1378 
1379 static int
1380 pollout(td, fds, ufds, nfd)
1381 	struct thread *td;
1382 	struct pollfd *fds;
1383 	struct pollfd *ufds;
1384 	u_int nfd;
1385 {
1386 	int error = 0;
1387 	u_int i = 0;
1388 	u_int n = 0;
1389 
1390 	for (i = 0; i < nfd; i++) {
1391 		error = copyout(&fds->revents, &ufds->revents,
1392 		    sizeof(ufds->revents));
1393 		if (error)
1394 			return (error);
1395 		if (fds->revents != 0)
1396 			n++;
1397 		fds++;
1398 		ufds++;
1399 	}
1400 	td->td_retval[0] = n;
1401 	return (0);
1402 }
1403 
1404 static int
1405 pollscan(td, fds, nfd)
1406 	struct thread *td;
1407 	struct pollfd *fds;
1408 	u_int nfd;
1409 {
1410 	struct filedesc *fdp = td->td_proc->p_fd;
1411 	int i;
1412 	struct file *fp;
1413 	int n = 0;
1414 
1415 	FILEDESC_SLOCK(fdp);
1416 	for (i = 0; i < nfd; i++, fds++) {
1417 		if (fds->fd >= fdp->fd_nfiles) {
1418 			fds->revents = POLLNVAL;
1419 			n++;
1420 		} else if (fds->fd < 0) {
1421 			fds->revents = 0;
1422 		} else {
1423 			fp = fdp->fd_ofiles[fds->fd];
1424 #ifdef CAPABILITIES
1425 			if ((fp == NULL)
1426 			    || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1427 #else
1428 			if (fp == NULL) {
1429 #endif
1430 				fds->revents = POLLNVAL;
1431 				n++;
1432 			} else {
1433 				/*
1434 				 * Note: backend also returns POLLHUP and
1435 				 * POLLERR if appropriate.
1436 				 */
1437 				selfdalloc(td, fds);
1438 				fds->revents = fo_poll(fp, fds->events,
1439 				    td->td_ucred, td);
1440 				/*
1441 				 * POSIX requires POLLOUT to be never
1442 				 * set simultaneously with POLLHUP.
1443 				 */
1444 				if ((fds->revents & POLLHUP) != 0)
1445 					fds->revents &= ~POLLOUT;
1446 
1447 				if (fds->revents != 0)
1448 					n++;
1449 			}
1450 		}
1451 	}
1452 	FILEDESC_SUNLOCK(fdp);
1453 	td->td_retval[0] = n;
1454 	return (0);
1455 }
1456 
1457 /*
1458  * OpenBSD poll system call.
1459  *
1460  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1461  */
1462 #ifndef _SYS_SYSPROTO_H_
1463 struct openbsd_poll_args {
1464 	struct pollfd *fds;
1465 	u_int	nfds;
1466 	int	timeout;
1467 };
1468 #endif
1469 int
1470 sys_openbsd_poll(td, uap)
1471 	register struct thread *td;
1472 	register struct openbsd_poll_args *uap;
1473 {
1474 	return (sys_poll(td, (struct poll_args *)uap));
1475 }
1476 
1477 /*
1478  * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1479  * have two select sets, one for read and another for write.
1480  */
1481 static void
1482 selfdalloc(struct thread *td, void *cookie)
1483 {
1484 	struct seltd *stp;
1485 
1486 	stp = td->td_sel;
1487 	if (stp->st_free1 == NULL)
1488 		stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1489 	stp->st_free1->sf_td = stp;
1490 	stp->st_free1->sf_cookie = cookie;
1491 	if (stp->st_free2 == NULL)
1492 		stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1493 	stp->st_free2->sf_td = stp;
1494 	stp->st_free2->sf_cookie = cookie;
1495 }
1496 
1497 static void
1498 selfdfree(struct seltd *stp, struct selfd *sfp)
1499 {
1500 	STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1501 	mtx_lock(sfp->sf_mtx);
1502 	if (sfp->sf_si)
1503 		TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1504 	mtx_unlock(sfp->sf_mtx);
1505 	uma_zfree(selfd_zone, sfp);
1506 }
1507 
1508 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1509 void
1510 seldrain(sip)
1511         struct selinfo *sip;
1512 {
1513 
1514 	/*
1515 	 * This feature is already provided by doselwakeup(), thus it is
1516 	 * enough to go for it.
1517 	 * Eventually, the context, should take care to avoid races
1518 	 * between thread calling select()/poll() and file descriptor
1519 	 * detaching, but, again, the races are just the same as
1520 	 * selwakeup().
1521 	 */
1522         doselwakeup(sip, -1);
1523 }
1524 
1525 /*
1526  * Record a select request.
1527  */
1528 void
1529 selrecord(selector, sip)
1530 	struct thread *selector;
1531 	struct selinfo *sip;
1532 {
1533 	struct selfd *sfp;
1534 	struct seltd *stp;
1535 	struct mtx *mtxp;
1536 
1537 	stp = selector->td_sel;
1538 	/*
1539 	 * Don't record when doing a rescan.
1540 	 */
1541 	if (stp->st_flags & SELTD_RESCAN)
1542 		return;
1543 	/*
1544 	 * Grab one of the preallocated descriptors.
1545 	 */
1546 	sfp = NULL;
1547 	if ((sfp = stp->st_free1) != NULL)
1548 		stp->st_free1 = NULL;
1549 	else if ((sfp = stp->st_free2) != NULL)
1550 		stp->st_free2 = NULL;
1551 	else
1552 		panic("selrecord: No free selfd on selq");
1553 	mtxp = sip->si_mtx;
1554 	if (mtxp == NULL)
1555 		mtxp = mtx_pool_find(mtxpool_select, sip);
1556 	/*
1557 	 * Initialize the sfp and queue it in the thread.
1558 	 */
1559 	sfp->sf_si = sip;
1560 	sfp->sf_mtx = mtxp;
1561 	STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1562 	/*
1563 	 * Now that we've locked the sip, check for initialization.
1564 	 */
1565 	mtx_lock(mtxp);
1566 	if (sip->si_mtx == NULL) {
1567 		sip->si_mtx = mtxp;
1568 		TAILQ_INIT(&sip->si_tdlist);
1569 	}
1570 	/*
1571 	 * Add this thread to the list of selfds listening on this selinfo.
1572 	 */
1573 	TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1574 	mtx_unlock(sip->si_mtx);
1575 }
1576 
1577 /* Wake up a selecting thread. */
1578 void
1579 selwakeup(sip)
1580 	struct selinfo *sip;
1581 {
1582 	doselwakeup(sip, -1);
1583 }
1584 
1585 /* Wake up a selecting thread, and set its priority. */
1586 void
1587 selwakeuppri(sip, pri)
1588 	struct selinfo *sip;
1589 	int pri;
1590 {
1591 	doselwakeup(sip, pri);
1592 }
1593 
1594 /*
1595  * Do a wakeup when a selectable event occurs.
1596  */
1597 static void
1598 doselwakeup(sip, pri)
1599 	struct selinfo *sip;
1600 	int pri;
1601 {
1602 	struct selfd *sfp;
1603 	struct selfd *sfn;
1604 	struct seltd *stp;
1605 
1606 	/* If it's not initialized there can't be any waiters. */
1607 	if (sip->si_mtx == NULL)
1608 		return;
1609 	/*
1610 	 * Locking the selinfo locks all selfds associated with it.
1611 	 */
1612 	mtx_lock(sip->si_mtx);
1613 	TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1614 		/*
1615 		 * Once we remove this sfp from the list and clear the
1616 		 * sf_si seltdclear will know to ignore this si.
1617 		 */
1618 		TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1619 		sfp->sf_si = NULL;
1620 		stp = sfp->sf_td;
1621 		mtx_lock(&stp->st_mtx);
1622 		stp->st_flags |= SELTD_PENDING;
1623 		cv_broadcastpri(&stp->st_wait, pri);
1624 		mtx_unlock(&stp->st_mtx);
1625 	}
1626 	mtx_unlock(sip->si_mtx);
1627 }
1628 
1629 static void
1630 seltdinit(struct thread *td)
1631 {
1632 	struct seltd *stp;
1633 
1634 	if ((stp = td->td_sel) != NULL)
1635 		goto out;
1636 	td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1637 	mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1638 	cv_init(&stp->st_wait, "select");
1639 out:
1640 	stp->st_flags = 0;
1641 	STAILQ_INIT(&stp->st_selq);
1642 }
1643 
1644 static int
1645 seltdwait(struct thread *td, int timo)
1646 {
1647 	struct seltd *stp;
1648 	int error;
1649 
1650 	stp = td->td_sel;
1651 	/*
1652 	 * An event of interest may occur while we do not hold the seltd
1653 	 * locked so check the pending flag before we sleep.
1654 	 */
1655 	mtx_lock(&stp->st_mtx);
1656 	/*
1657 	 * Any further calls to selrecord will be a rescan.
1658 	 */
1659 	stp->st_flags |= SELTD_RESCAN;
1660 	if (stp->st_flags & SELTD_PENDING) {
1661 		mtx_unlock(&stp->st_mtx);
1662 		return (0);
1663 	}
1664 	if (timo > 0)
1665 		error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1666 	else
1667 		error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1668 	mtx_unlock(&stp->st_mtx);
1669 
1670 	return (error);
1671 }
1672 
1673 void
1674 seltdfini(struct thread *td)
1675 {
1676 	struct seltd *stp;
1677 
1678 	stp = td->td_sel;
1679 	if (stp == NULL)
1680 		return;
1681 	if (stp->st_free1)
1682 		uma_zfree(selfd_zone, stp->st_free1);
1683 	if (stp->st_free2)
1684 		uma_zfree(selfd_zone, stp->st_free2);
1685 	td->td_sel = NULL;
1686 	free(stp, M_SELECT);
1687 }
1688 
1689 /*
1690  * Remove the references to the thread from all of the objects we were
1691  * polling.
1692  */
1693 static void
1694 seltdclear(struct thread *td)
1695 {
1696 	struct seltd *stp;
1697 	struct selfd *sfp;
1698 	struct selfd *sfn;
1699 
1700 	stp = td->td_sel;
1701 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1702 		selfdfree(stp, sfp);
1703 	stp->st_flags = 0;
1704 }
1705 
1706 static void selectinit(void *);
1707 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1708 static void
1709 selectinit(void *dummy __unused)
1710 {
1711 
1712 	selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1713 	    NULL, NULL, UMA_ALIGN_PTR, 0);
1714 	mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1715 }
1716