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