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