2 * SPDX-License-Identifier: BSD-3-Clause
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.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
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.
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
36 * @(#)sys_generic.c 8.5 (Berkeley) 1/21/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include "opt_capsicum.h"
43 #include "opt_ktrace.h"
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>
55 #include <sys/signalvar.h>
56 #include <sys/socketvar.h>
58 #include <sys/eventfd.h>
59 #include <sys/kernel.h>
61 #include <sys/limits.h>
62 #include <sys/malloc.h>
64 #include <sys/resourcevar.h>
65 #include <sys/selinfo.h>
66 #include <sys/sleepqueue.h>
67 #include <sys/specialfd.h>
68 #include <sys/syscallsubr.h>
69 #include <sys/sysctl.h>
70 #include <sys/sysent.h>
71 #include <sys/vnode.h>
74 #include <sys/condvar.h>
76 #include <sys/ktrace.h>
79 #include <security/audit/audit.h>
82 * The following macro defines how many bytes will be allocated from
83 * the stack instead of memory allocated when passing the IOCTL data
84 * structures from userspace and to the kernel. Some IOCTLs having
85 * small data structures are used very frequently and this small
86 * buffer on the stack gives a significant speedup improvement for
87 * those requests. The value of this define should be greater or equal
88 * to 64 bytes and should also be power of two. The data structure is
89 * currently hard-aligned to a 8-byte boundary on the stack. This
90 * should currently be sufficient for all supported platforms.
92 #define SYS_IOCTL_SMALL_SIZE 128 /* bytes */
93 #define SYS_IOCTL_SMALL_ALIGN 8 /* bytes */
96 static int iosize_max_clamp = 0;
97 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
98 &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
99 static int devfs_iosize_max_clamp = 1;
100 SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
101 &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
105 * Assert that the return value of read(2) and write(2) syscalls fits
106 * into a register. If not, an architecture will need to provide the
107 * usermode wrappers to reconstruct the result.
109 CTASSERT(sizeof(register_t) >= sizeof(size_t));
111 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
112 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
113 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
115 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
117 static int pollscan(struct thread *, struct pollfd *, u_int);
118 static int pollrescan(struct thread *);
119 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
120 static int selrescan(struct thread *, fd_mask **, fd_mask **);
121 static void selfdalloc(struct thread *, void *);
122 static void selfdfree(struct seltd *, struct selfd *);
123 static int dofileread(struct thread *, int, struct file *, struct uio *,
125 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
127 static void doselwakeup(struct selinfo *, int);
128 static void seltdinit(struct thread *);
129 static int seltdwait(struct thread *, sbintime_t, sbintime_t);
130 static void seltdclear(struct thread *);
133 * One seltd per-thread allocated on demand as needed.
135 * t - protected by st_mtx
136 * k - Only accessed by curthread or read-only
139 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
140 struct selfd *st_free1; /* (k) free fd for read set. */
141 struct selfd *st_free2; /* (k) free fd for write set. */
142 struct mtx st_mtx; /* Protects struct seltd */
143 struct cv st_wait; /* (t) Wait channel. */
144 int st_flags; /* (t) SELTD_ flags. */
147 #define SELTD_PENDING 0x0001 /* We have pending events. */
148 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
151 * One selfd allocated per-thread per-file-descriptor.
152 * f - protected by sf_mtx
155 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
156 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
157 struct selinfo *sf_si; /* (f) selinfo when linked. */
158 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
159 struct seltd *sf_td; /* (k) owning seltd. */
160 void *sf_cookie; /* (k) fd or pollfd. */
163 MALLOC_DEFINE(M_SELFD, "selfd", "selfd");
164 static struct mtx_pool *mtxpool_select;
168 devfs_iosize_max(void)
171 return (devfs_iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
172 INT_MAX : SSIZE_MAX);
179 return (iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
180 INT_MAX : SSIZE_MAX);
184 #ifndef _SYS_SYSPROTO_H_
192 sys_read(struct thread *td, struct read_args *uap)
198 if (uap->nbyte > IOSIZE_MAX)
200 aiov.iov_base = uap->buf;
201 aiov.iov_len = uap->nbyte;
202 auio.uio_iov = &aiov;
204 auio.uio_resid = uap->nbyte;
205 auio.uio_segflg = UIO_USERSPACE;
206 error = kern_readv(td, uap->fd, &auio);
211 * Positioned read system call
213 #ifndef _SYS_SYSPROTO_H_
223 sys_pread(struct thread *td, struct pread_args *uap)
226 return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
230 kern_pread(struct thread *td, int fd, void *buf, size_t nbyte, off_t offset)
236 if (nbyte > IOSIZE_MAX)
239 aiov.iov_len = nbyte;
240 auio.uio_iov = &aiov;
242 auio.uio_resid = nbyte;
243 auio.uio_segflg = UIO_USERSPACE;
244 error = kern_preadv(td, fd, &auio, offset);
248 #if defined(COMPAT_FREEBSD6)
250 freebsd6_pread(struct thread *td, struct freebsd6_pread_args *uap)
253 return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
258 * Scatter read system call.
260 #ifndef _SYS_SYSPROTO_H_
268 sys_readv(struct thread *td, struct readv_args *uap)
273 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
276 error = kern_readv(td, uap->fd, auio);
282 kern_readv(struct thread *td, int fd, struct uio *auio)
287 error = fget_read(td, fd, &cap_read_rights, &fp);
290 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
296 * Scatter positioned read system call.
298 #ifndef _SYS_SYSPROTO_H_
307 sys_preadv(struct thread *td, struct preadv_args *uap)
312 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
315 error = kern_preadv(td, uap->fd, auio, uap->offset);
321 kern_preadv(struct thread *td, int fd, struct uio *auio, off_t offset)
326 error = fget_read(td, fd, &cap_pread_rights, &fp);
329 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
331 else if (offset < 0 &&
332 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
335 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
341 * Common code for readv and preadv that reads data in
342 * from a file using the passed in uio, offset, and flags.
345 dofileread(struct thread *td, int fd, struct file *fp, struct uio *auio,
346 off_t offset, int flags)
351 struct uio *ktruio = NULL;
356 /* Finish zero length reads right here */
357 if (auio->uio_resid == 0) {
358 td->td_retval[0] = 0;
361 auio->uio_rw = UIO_READ;
362 auio->uio_offset = offset;
365 if (KTRPOINT(td, KTR_GENIO))
366 ktruio = cloneuio(auio);
368 cnt = auio->uio_resid;
369 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
370 if (auio->uio_resid != cnt && (error == ERESTART ||
371 error == EINTR || error == EWOULDBLOCK))
374 cnt -= auio->uio_resid;
376 if (ktruio != NULL) {
377 ktruio->uio_resid = cnt;
378 ktrgenio(fd, UIO_READ, ktruio, error);
381 td->td_retval[0] = cnt;
385 #ifndef _SYS_SYSPROTO_H_
393 sys_write(struct thread *td, struct write_args *uap)
399 if (uap->nbyte > IOSIZE_MAX)
401 aiov.iov_base = (void *)(uintptr_t)uap->buf;
402 aiov.iov_len = uap->nbyte;
403 auio.uio_iov = &aiov;
405 auio.uio_resid = uap->nbyte;
406 auio.uio_segflg = UIO_USERSPACE;
407 error = kern_writev(td, uap->fd, &auio);
412 * Positioned write system call.
414 #ifndef _SYS_SYSPROTO_H_
424 sys_pwrite(struct thread *td, struct pwrite_args *uap)
427 return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
431 kern_pwrite(struct thread *td, int fd, const void *buf, size_t nbyte,
438 if (nbyte > IOSIZE_MAX)
440 aiov.iov_base = (void *)(uintptr_t)buf;
441 aiov.iov_len = nbyte;
442 auio.uio_iov = &aiov;
444 auio.uio_resid = nbyte;
445 auio.uio_segflg = UIO_USERSPACE;
446 error = kern_pwritev(td, fd, &auio, offset);
450 #if defined(COMPAT_FREEBSD6)
452 freebsd6_pwrite(struct thread *td, struct freebsd6_pwrite_args *uap)
455 return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
460 * Gather write system call.
462 #ifndef _SYS_SYSPROTO_H_
470 sys_writev(struct thread *td, struct writev_args *uap)
475 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
478 error = kern_writev(td, uap->fd, auio);
484 kern_writev(struct thread *td, int fd, struct uio *auio)
489 error = fget_write(td, fd, &cap_write_rights, &fp);
492 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
498 * Gather positioned write system call.
500 #ifndef _SYS_SYSPROTO_H_
501 struct pwritev_args {
509 sys_pwritev(struct thread *td, struct pwritev_args *uap)
514 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
517 error = kern_pwritev(td, uap->fd, auio, uap->offset);
523 kern_pwritev(struct thread *td, int fd, struct uio *auio, off_t offset)
528 error = fget_write(td, fd, &cap_pwrite_rights, &fp);
531 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
533 else if (offset < 0 &&
534 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
537 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
543 * Common code for writev and pwritev that writes data to
544 * a file using the passed in uio, offset, and flags.
547 dofilewrite(struct thread *td, int fd, struct file *fp, struct uio *auio,
548 off_t offset, int flags)
553 struct uio *ktruio = NULL;
557 auio->uio_rw = UIO_WRITE;
559 auio->uio_offset = offset;
561 if (KTRPOINT(td, KTR_GENIO))
562 ktruio = cloneuio(auio);
564 cnt = auio->uio_resid;
565 error = fo_write(fp, auio, td->td_ucred, flags, td);
567 * Socket layer is responsible for special error handling,
570 if (error != 0 && fp->f_type != DTYPE_SOCKET) {
571 if (auio->uio_resid != cnt && (error == ERESTART ||
572 error == EINTR || error == EWOULDBLOCK))
574 if (error == EPIPE) {
575 PROC_LOCK(td->td_proc);
576 tdsignal(td, SIGPIPE);
577 PROC_UNLOCK(td->td_proc);
580 cnt -= auio->uio_resid;
582 if (ktruio != NULL) {
583 ktruio->uio_resid = cnt;
584 ktrgenio(fd, UIO_WRITE, ktruio, error);
587 td->td_retval[0] = cnt;
592 * Truncate a file given a file descriptor.
594 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
595 * descriptor isn't writable.
598 kern_ftruncate(struct thread *td, int fd, off_t length)
606 error = fget(td, fd, &cap_ftruncate_rights, &fp);
609 AUDIT_ARG_FILE(td->td_proc, fp);
610 if (!(fp->f_flag & FWRITE)) {
614 error = fo_truncate(fp, length, td->td_ucred, td);
619 #ifndef _SYS_SYSPROTO_H_
620 struct ftruncate_args {
627 sys_ftruncate(struct thread *td, struct ftruncate_args *uap)
630 return (kern_ftruncate(td, uap->fd, uap->length));
633 #if defined(COMPAT_43)
634 #ifndef _SYS_SYSPROTO_H_
635 struct oftruncate_args {
641 oftruncate(struct thread *td, struct oftruncate_args *uap)
644 return (kern_ftruncate(td, uap->fd, uap->length));
646 #endif /* COMPAT_43 */
648 #ifndef _SYS_SYSPROTO_H_
657 sys_ioctl(struct thread *td, struct ioctl_args *uap)
659 u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
666 if (uap->com > 0xffffffff) {
668 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
669 td->td_proc->p_pid, td->td_name, uap->com);
672 com = (uint32_t)uap->com;
675 * Interpret high order word to find amount of data to be
676 * copied to/from the user's address space.
678 size = IOCPARM_LEN(com);
679 if ((size > IOCPARM_MAX) ||
680 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
681 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
682 ((com & IOC_OUT) && size == 0) ||
684 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
686 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
690 if (com & IOC_VOID) {
691 /* Integer argument. */
692 arg = (intptr_t)uap->data;
696 if (size > SYS_IOCTL_SMALL_SIZE)
697 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
702 data = (void *)&uap->data;
704 error = copyin(uap->data, data, (u_int)size);
707 } else if (com & IOC_OUT) {
709 * Zero the buffer so the user always
710 * gets back something deterministic.
715 error = kern_ioctl(td, uap->fd, com, data);
717 if (error == 0 && (com & IOC_OUT))
718 error = copyout(data, uap->data, (u_int)size);
721 if (size > SYS_IOCTL_SMALL_SIZE)
722 free(data, M_IOCTLOPS);
727 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
730 struct filedesc *fdp;
731 int error, tmp, locked;
736 fdp = td->td_proc->p_fd;
749 locked = LA_UNLOCKED;
755 if ((fp = fget_noref(fdp, fd)) == NULL) {
759 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
760 fp = NULL; /* fhold() was not called yet */
768 if (locked == LA_SLOCKED) {
769 FILEDESC_SUNLOCK(fdp);
770 locked = LA_UNLOCKED;
773 error = fget(td, fd, &cap_ioctl_rights, &fp);
779 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
786 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
789 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
792 if ((tmp = *(int *)data))
793 atomic_set_int(&fp->f_flag, FNONBLOCK);
795 atomic_clear_int(&fp->f_flag, FNONBLOCK);
799 if ((tmp = *(int *)data))
800 atomic_set_int(&fp->f_flag, FASYNC);
802 atomic_clear_int(&fp->f_flag, FASYNC);
807 error = fo_ioctl(fp, com, data, td->td_ucred, td);
811 FILEDESC_XUNLOCK(fdp);
815 FILEDESC_SUNLOCK(fdp);
819 FILEDESC_UNLOCK_ASSERT(fdp);
828 sys_posix_fallocate(struct thread *td, struct posix_fallocate_args *uap)
832 error = kern_posix_fallocate(td, uap->fd, uap->offset, uap->len);
833 return (kern_posix_error(td, error));
837 kern_posix_fallocate(struct thread *td, int fd, off_t offset, off_t len)
843 if (offset < 0 || len <= 0)
845 /* Check for wrap. */
846 if (offset > OFF_MAX - len)
849 error = fget(td, fd, &cap_pwrite_rights, &fp);
852 AUDIT_ARG_FILE(td->td_proc, fp);
853 if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
857 if ((fp->f_flag & FWRITE) == 0) {
862 error = fo_fallocate(fp, offset, len, td);
869 sys_fspacectl(struct thread *td, struct fspacectl_args *uap)
871 struct spacectl_range rqsr, rmsr;
874 error = copyin(uap->rqsr, &rqsr, sizeof(rqsr));
878 error = kern_fspacectl(td, uap->fd, uap->cmd, &rqsr, uap->flags,
880 if (uap->rmsr != NULL) {
881 cerror = copyout(&rmsr, uap->rmsr, sizeof(rmsr));
889 kern_fspacectl(struct thread *td, int fd, int cmd,
890 const struct spacectl_range *rqsr, int flags, struct spacectl_range *rmsrp)
893 struct spacectl_range rmsr;
898 AUDIT_ARG_FFLAGS(flags);
906 if (cmd != SPACECTL_DEALLOC ||
907 rqsr->r_offset < 0 || rqsr->r_len <= 0 ||
908 rqsr->r_offset > OFF_MAX - rqsr->r_len ||
909 (flags & ~SPACECTL_F_SUPPORTED) != 0)
912 error = fget_write(td, fd, &cap_pwrite_rights, &fp);
915 AUDIT_ARG_FILE(td->td_proc, fp);
916 if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
920 if ((fp->f_flag & FWRITE) == 0) {
925 error = fo_fspacectl(fp, cmd, &rmsr.r_offset, &rmsr.r_len, flags,
927 /* fspacectl is not restarted after signals if the file is modified. */
928 if (rmsr.r_len != rqsr->r_len && (error == ERESTART ||
929 error == EINTR || error == EWOULDBLOCK))
939 kern_specialfd(struct thread *td, int type, void *arg)
942 struct specialfd_eventfd *ae;
943 int error, fd, fflags;
946 error = falloc_noinstall(td, &fp);
951 case SPECIALFD_EVENTFD:
953 if ((ae->flags & EFD_CLOEXEC) != 0)
955 error = eventfd_create_file(td, fp, ae->initval, ae->flags);
963 error = finstall(td, fp, &fd, fflags, NULL);
966 td->td_retval[0] = fd;
971 sys___specialfd(struct thread *td, struct __specialfd_args *args)
973 struct specialfd_eventfd ae;
976 switch (args->type) {
977 case SPECIALFD_EVENTFD:
978 if (args->len != sizeof(struct specialfd_eventfd)) {
982 error = copyin(args->req, &ae, sizeof(ae));
985 if ((ae.flags & ~(EFD_CLOEXEC | EFD_NONBLOCK |
986 EFD_SEMAPHORE)) != 0) {
990 error = kern_specialfd(td, args->type, &ae);
1000 poll_no_poll(int events)
1003 * Return true for read/write. If the user asked for something
1004 * special, return POLLNVAL, so that clients have a way of
1005 * determining reliably whether or not the extended
1006 * functionality is present without hard-coding knowledge
1007 * of specific filesystem implementations.
1009 if (events & ~POLLSTANDARD)
1012 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
1016 sys_pselect(struct thread *td, struct pselect_args *uap)
1019 struct timeval tv, *tvp;
1020 sigset_t set, *uset;
1023 if (uap->ts != NULL) {
1024 error = copyin(uap->ts, &ts, sizeof(ts));
1027 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1031 if (uap->sm != NULL) {
1032 error = copyin(uap->sm, &set, sizeof(set));
1038 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
1043 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
1044 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
1049 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1050 &td->td_oldsigmask, 0);
1053 td->td_pflags |= TDP_OLDMASK;
1055 * Make sure that ast() is called on return to
1056 * usermode and TDP_OLDMASK is cleared, restoring old
1059 ast_sched(td, TDA_SIGSUSPEND);
1061 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
1065 #ifndef _SYS_SYSPROTO_H_
1066 struct select_args {
1068 fd_set *in, *ou, *ex;
1073 sys_select(struct thread *td, struct select_args *uap)
1075 struct timeval tv, *tvp;
1078 if (uap->tv != NULL) {
1079 error = copyin(uap->tv, &tv, sizeof(tv));
1086 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
1091 * In the unlikely case when user specified n greater then the last
1092 * open file descriptor, check that no bits are set after the last
1093 * valid fd. We must return EBADF if any is set.
1095 * There are applications that rely on the behaviour.
1100 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
1106 if (nd >= ndu || fd_in == NULL)
1110 bits = 0; /* silence gcc */
1111 for (i = nd; i < ndu; i++) {
1113 #if BYTE_ORDER == LITTLE_ENDIAN
1114 addr = (char *)fd_in + b;
1116 addr = (char *)fd_in;
1117 if (abi_nfdbits == NFDBITS) {
1118 addr += rounddown(b, sizeof(fd_mask)) +
1119 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
1121 addr += rounddown(b, sizeof(uint32_t)) +
1122 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
1125 if (addr != oaddr) {
1132 if ((bits & (1 << (i % NBBY))) != 0)
1139 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
1140 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
1142 struct filedesc *fdp;
1144 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
1145 * infds with the new FD_SETSIZE of 1024, and more than enough for
1146 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
1149 fd_mask s_selbits[howmany(2048, NFDBITS)];
1150 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
1152 sbintime_t asbt, precision, rsbt;
1153 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
1158 fdp = td->td_proc->p_fd;
1160 lf = fdp->fd_nfiles;
1164 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1167 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1170 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1175 * Allocate just enough bits for the non-null fd_sets. Use the
1176 * preallocated auto buffer if possible.
1178 nfdbits = roundup(nd, NFDBITS);
1179 ncpbytes = nfdbits / NBBY;
1180 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1183 nbufbytes += 2 * ncpbytes;
1185 nbufbytes += 2 * ncpbytes;
1187 nbufbytes += 2 * ncpbytes;
1188 if (nbufbytes <= sizeof s_selbits)
1189 selbits = &s_selbits[0];
1191 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1194 * Assign pointers into the bit buffers and fetch the input bits.
1195 * Put the output buffers together so that they can be bzeroed
1199 #define getbits(name, x) \
1201 if (name == NULL) { \
1205 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1207 sbp += ncpbytes / sizeof *sbp; \
1208 error = copyin(name, ibits[x], ncpubytes); \
1211 if (ncpbytes != ncpubytes) \
1212 bzero((char *)ibits[x] + ncpubytes, \
1213 ncpbytes - ncpubytes); \
1221 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1223 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1224 * we are running under 32-bit emulation. This should be more
1227 #define swizzle_fdset(bits) \
1228 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1230 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1231 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1234 #define swizzle_fdset(bits)
1237 /* Make sure the bit order makes it through an ABI transition */
1238 swizzle_fdset(ibits[0]);
1239 swizzle_fdset(ibits[1]);
1240 swizzle_fdset(ibits[2]);
1243 bzero(selbits, nbufbytes / 2);
1248 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1249 rtv.tv_usec >= 1000000) {
1253 if (!timevalisset(&rtv))
1255 else if (rtv.tv_sec <= INT32_MAX) {
1256 rsbt = tvtosbt(rtv);
1258 precision >>= tc_precexp;
1259 if (TIMESEL(&asbt, rsbt))
1260 asbt += tc_tick_sbt;
1261 if (asbt <= SBT_MAX - rsbt)
1270 /* Iterate until the timeout expires or descriptors become ready. */
1272 error = selscan(td, ibits, obits, nd);
1273 if (error || td->td_retval[0] != 0)
1275 error = seltdwait(td, asbt, precision);
1278 error = selrescan(td, ibits, obits);
1279 if (error || td->td_retval[0] != 0)
1285 /* select is not restarted after signals... */
1286 if (error == ERESTART)
1288 if (error == EWOULDBLOCK)
1291 /* swizzle bit order back, if necessary */
1292 swizzle_fdset(obits[0]);
1293 swizzle_fdset(obits[1]);
1294 swizzle_fdset(obits[2]);
1295 #undef swizzle_fdset
1297 #define putbits(name, x) \
1298 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1308 if (selbits != &s_selbits[0])
1309 free(selbits, M_SELECT);
1314 * Convert a select bit set to poll flags.
1316 * The backend always returns POLLHUP/POLLERR if appropriate and we
1317 * return this as a set bit in any set.
1319 static const int select_flags[3] = {
1320 POLLRDNORM | POLLHUP | POLLERR,
1321 POLLWRNORM | POLLHUP | POLLERR,
1322 POLLRDBAND | POLLERR
1326 * Compute the fo_poll flags required for a fd given by the index and
1327 * bit position in the fd_mask array.
1330 selflags(fd_mask **ibits, int idx, fd_mask bit)
1336 for (msk = 0; msk < 3; msk++) {
1337 if (ibits[msk] == NULL)
1339 if ((ibits[msk][idx] & bit) == 0)
1341 flags |= select_flags[msk];
1347 * Set the appropriate output bits given a mask of fired events and the
1348 * input bits originally requested.
1351 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1357 for (msk = 0; msk < 3; msk++) {
1358 if ((events & select_flags[msk]) == 0)
1360 if (ibits[msk] == NULL)
1362 if ((ibits[msk][idx] & bit) == 0)
1365 * XXX Check for a duplicate set. This can occur because a
1366 * socket calls selrecord() twice for each poll() call
1367 * resulting in two selfds per real fd. selrescan() will
1368 * call selsetbits twice as a result.
1370 if ((obits[msk][idx] & bit) != 0)
1372 obits[msk][idx] |= bit;
1380 * Traverse the list of fds attached to this thread's seltd and check for
1384 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1386 struct filedesc *fdp;
1397 fdp = td->td_proc->p_fd;
1400 only_user = FILEDESC_IS_ONLY_USER(fdp);
1401 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1402 fd = (int)(uintptr_t)sfp->sf_cookie;
1404 selfdfree(stp, sfp);
1405 /* If the selinfo wasn't cleared the event didn't fire. */
1409 error = fget_only_user(fdp, fd, &cap_event_rights, &fp);
1411 error = fget_unlocked(td, fd, &cap_event_rights, &fp);
1412 if (__predict_false(error != 0))
1415 bit = (fd_mask)1 << (fd % NFDBITS);
1416 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1418 fput_only_user(fdp, fp);
1422 n += selsetbits(ibits, obits, idx, bit, ev);
1425 td->td_retval[0] = n;
1430 * Perform the initial filedescriptor scan and register ourselves with
1434 selscan(struct thread *td, fd_mask **ibits, fd_mask **obits, int nfd)
1436 struct filedesc *fdp;
1439 int ev, flags, end, fd;
1444 fdp = td->td_proc->p_fd;
1446 only_user = FILEDESC_IS_ONLY_USER(fdp);
1447 for (idx = 0, fd = 0; fd < nfd; idx++) {
1448 end = imin(fd + NFDBITS, nfd);
1449 for (bit = 1; fd < end; bit <<= 1, fd++) {
1450 /* Compute the list of events we're interested in. */
1451 flags = selflags(ibits, idx, bit);
1455 error = fget_only_user(fdp, fd, &cap_event_rights, &fp);
1457 error = fget_unlocked(td, fd, &cap_event_rights, &fp);
1458 if (__predict_false(error != 0))
1460 selfdalloc(td, (void *)(uintptr_t)fd);
1461 ev = fo_poll(fp, flags, td->td_ucred, td);
1463 fput_only_user(fdp, fp);
1467 n += selsetbits(ibits, obits, idx, bit, ev);
1471 td->td_retval[0] = n;
1476 sys_poll(struct thread *td, struct poll_args *uap)
1478 struct timespec ts, *tsp;
1480 if (uap->timeout != INFTIM) {
1481 if (uap->timeout < 0)
1483 ts.tv_sec = uap->timeout / 1000;
1484 ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1489 return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1493 * kfds points to an array in the kernel.
1496 kern_poll_kfds(struct thread *td, struct pollfd *kfds, u_int nfds,
1497 struct timespec *tsp, sigset_t *uset)
1499 sbintime_t sbt, precision, tmp;
1506 if (!timespecvalid_interval(tsp))
1508 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1512 if (ts.tv_sec > INT32_MAX / 2) {
1513 over = ts.tv_sec - INT32_MAX / 2;
1519 precision >>= tc_precexp;
1520 if (TIMESEL(&sbt, tmp))
1528 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1529 &td->td_oldsigmask, 0);
1532 td->td_pflags |= TDP_OLDMASK;
1534 * Make sure that ast() is called on return to
1535 * usermode and TDP_OLDMASK is cleared, restoring old
1538 ast_sched(td, TDA_SIGSUSPEND);
1542 /* Iterate until the timeout expires or descriptors become ready. */
1544 error = pollscan(td, kfds, nfds);
1545 if (error || td->td_retval[0] != 0)
1547 error = seltdwait(td, sbt, precision);
1550 error = pollrescan(td);
1551 if (error || td->td_retval[0] != 0)
1556 /* poll is not restarted after signals... */
1557 if (error == ERESTART)
1559 if (error == EWOULDBLOCK)
1565 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1567 struct timespec ts, *tsp;
1571 if (uap->ts != NULL) {
1572 error = copyin(uap->ts, &ts, sizeof(ts));
1578 if (uap->set != NULL) {
1579 error = copyin(uap->set, &set, sizeof(set));
1585 return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1589 * ufds points to an array in user space.
1592 kern_poll(struct thread *td, struct pollfd *ufds, u_int nfds,
1593 struct timespec *tsp, sigset_t *set)
1595 struct pollfd *kfds;
1596 struct pollfd stackfds[32];
1599 if (kern_poll_maxfds(nfds))
1601 if (nfds > nitems(stackfds))
1602 kfds = mallocarray(nfds, sizeof(*kfds), M_TEMP, M_WAITOK);
1605 error = copyin(ufds, kfds, nfds * sizeof(*kfds));
1609 error = kern_poll_kfds(td, kfds, nfds, tsp, set);
1611 error = pollout(td, kfds, ufds, nfds);
1614 if (nfds > nitems(stackfds))
1620 kern_poll_maxfds(u_int nfds)
1624 * This is kinda bogus. We have fd limits, but that is not
1625 * really related to the size of the pollfd array. Make sure
1626 * we let the process use at least FD_SETSIZE entries and at
1627 * least enough for the system-wide limits. We want to be reasonably
1628 * safe, but not overly restrictive.
1630 return (nfds > maxfilesperproc && nfds > FD_SETSIZE);
1634 pollrescan(struct thread *td)
1640 struct filedesc *fdp;
1647 fdp = td->td_proc->p_fd;
1649 only_user = FILEDESC_IS_ONLY_USER(fdp);
1650 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1651 fd = (struct pollfd *)sfp->sf_cookie;
1653 selfdfree(stp, sfp);
1654 /* If the selinfo wasn't cleared the event didn't fire. */
1658 error = fget_only_user(fdp, fd->fd, &cap_event_rights, &fp);
1660 error = fget_unlocked(td, fd->fd, &cap_event_rights, &fp);
1661 if (__predict_false(error != 0)) {
1662 fd->revents = POLLNVAL;
1667 * Note: backend also returns POLLHUP and
1668 * POLLERR if appropriate.
1670 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1672 fput_only_user(fdp, fp);
1675 if (fd->revents != 0)
1679 td->td_retval[0] = n;
1684 pollout(struct thread *td, struct pollfd *fds, struct pollfd *ufds, u_int nfd)
1690 for (i = 0; i < nfd; i++) {
1691 error = copyout(&fds->revents, &ufds->revents,
1692 sizeof(ufds->revents));
1695 if (fds->revents != 0)
1700 td->td_retval[0] = n;
1705 pollscan(struct thread *td, struct pollfd *fds, u_int nfd)
1707 struct filedesc *fdp;
1713 fdp = td->td_proc->p_fd;
1714 only_user = FILEDESC_IS_ONLY_USER(fdp);
1715 for (i = 0; i < nfd; i++, fds++) {
1721 error = fget_only_user(fdp, fds->fd, &cap_event_rights, &fp);
1723 error = fget_unlocked(td, fds->fd, &cap_event_rights, &fp);
1724 if (__predict_false(error != 0)) {
1725 fds->revents = POLLNVAL;
1730 * Note: backend also returns POLLHUP and
1731 * POLLERR if appropriate.
1733 selfdalloc(td, fds);
1734 fds->revents = fo_poll(fp, fds->events,
1737 fput_only_user(fdp, fp);
1741 * POSIX requires POLLOUT to be never
1742 * set simultaneously with POLLHUP.
1744 if ((fds->revents & POLLHUP) != 0)
1745 fds->revents &= ~POLLOUT;
1747 if (fds->revents != 0)
1750 td->td_retval[0] = n;
1755 * XXX This was created specifically to support netncp and netsmb. This
1756 * allows the caller to specify a socket to wait for events on. It returns
1757 * 0 if any events matched and an error otherwise. There is no way to
1758 * determine which events fired.
1761 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1764 sbintime_t asbt, precision, rsbt;
1767 precision = 0; /* stupid gcc! */
1770 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1771 rtv.tv_usec >= 1000000)
1773 if (!timevalisset(&rtv))
1775 else if (rtv.tv_sec <= INT32_MAX) {
1776 rsbt = tvtosbt(rtv);
1778 precision >>= tc_precexp;
1779 if (TIMESEL(&asbt, rsbt))
1780 asbt += tc_tick_sbt;
1781 if (asbt <= SBT_MAX - rsbt)
1791 * Iterate until the timeout expires or the socket becomes ready.
1794 selfdalloc(td, NULL);
1795 if (sopoll(so, events, NULL, td) != 0) {
1799 error = seltdwait(td, asbt, precision);
1804 /* XXX Duplicates ncp/smb behavior. */
1805 if (error == ERESTART)
1811 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1812 * have two select sets, one for read and another for write.
1815 selfdalloc(struct thread *td, void *cookie)
1820 if (stp->st_free1 == NULL)
1821 stp->st_free1 = malloc(sizeof(*stp->st_free1), M_SELFD, M_WAITOK|M_ZERO);
1822 stp->st_free1->sf_td = stp;
1823 stp->st_free1->sf_cookie = cookie;
1824 if (stp->st_free2 == NULL)
1825 stp->st_free2 = malloc(sizeof(*stp->st_free2), M_SELFD, M_WAITOK|M_ZERO);
1826 stp->st_free2->sf_td = stp;
1827 stp->st_free2->sf_cookie = cookie;
1831 selfdfree(struct seltd *stp, struct selfd *sfp)
1833 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1835 * Paired with doselwakeup.
1837 if (atomic_load_acq_ptr((uintptr_t *)&sfp->sf_si) != (uintptr_t)NULL) {
1838 mtx_lock(sfp->sf_mtx);
1839 if (sfp->sf_si != NULL) {
1840 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1842 mtx_unlock(sfp->sf_mtx);
1847 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1849 seldrain(struct selinfo *sip)
1853 * This feature is already provided by doselwakeup(), thus it is
1854 * enough to go for it.
1855 * Eventually, the context, should take care to avoid races
1856 * between thread calling select()/poll() and file descriptor
1857 * detaching, but, again, the races are just the same as
1860 doselwakeup(sip, -1);
1864 * Record a select request.
1867 selrecord(struct thread *selector, struct selinfo *sip)
1873 stp = selector->td_sel;
1875 * Don't record when doing a rescan.
1877 if (stp->st_flags & SELTD_RESCAN)
1880 * Grab one of the preallocated descriptors.
1883 if ((sfp = stp->st_free1) != NULL)
1884 stp->st_free1 = NULL;
1885 else if ((sfp = stp->st_free2) != NULL)
1886 stp->st_free2 = NULL;
1888 panic("selrecord: No free selfd on selq");
1891 mtxp = mtx_pool_find(mtxpool_select, sip);
1893 * Initialize the sfp and queue it in the thread.
1897 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1899 * Now that we've locked the sip, check for initialization.
1902 if (sip->si_mtx == NULL) {
1904 TAILQ_INIT(&sip->si_tdlist);
1907 * Add this thread to the list of selfds listening on this selinfo.
1909 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1910 mtx_unlock(sip->si_mtx);
1913 /* Wake up a selecting thread. */
1915 selwakeup(struct selinfo *sip)
1917 doselwakeup(sip, -1);
1920 /* Wake up a selecting thread, and set its priority. */
1922 selwakeuppri(struct selinfo *sip, int pri)
1924 doselwakeup(sip, pri);
1928 * Do a wakeup when a selectable event occurs.
1931 doselwakeup(struct selinfo *sip, int pri)
1937 /* If it's not initialized there can't be any waiters. */
1938 if (sip->si_mtx == NULL)
1941 * Locking the selinfo locks all selfds associated with it.
1943 mtx_lock(sip->si_mtx);
1944 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1946 * Once we remove this sfp from the list and clear the
1947 * sf_si seltdclear will know to ignore this si.
1949 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1951 mtx_lock(&stp->st_mtx);
1952 stp->st_flags |= SELTD_PENDING;
1953 cv_broadcastpri(&stp->st_wait, pri);
1954 mtx_unlock(&stp->st_mtx);
1956 * Paired with selfdfree.
1958 * Storing this only after the wakeup provides an invariant that
1959 * stp is not used after selfdfree returns.
1961 atomic_store_rel_ptr((uintptr_t *)&sfp->sf_si, (uintptr_t)NULL);
1963 mtx_unlock(sip->si_mtx);
1967 seltdinit(struct thread *td)
1973 MPASS(stp->st_flags == 0);
1974 MPASS(STAILQ_EMPTY(&stp->st_selq));
1977 stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1978 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1979 cv_init(&stp->st_wait, "select");
1981 STAILQ_INIT(&stp->st_selq);
1986 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1993 * An event of interest may occur while we do not hold the seltd
1994 * locked so check the pending flag before we sleep.
1996 mtx_lock(&stp->st_mtx);
1998 * Any further calls to selrecord will be a rescan.
2000 stp->st_flags |= SELTD_RESCAN;
2001 if (stp->st_flags & SELTD_PENDING) {
2002 mtx_unlock(&stp->st_mtx);
2006 error = EWOULDBLOCK;
2008 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
2009 sbt, precision, C_ABSOLUTE);
2011 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
2012 mtx_unlock(&stp->st_mtx);
2018 seltdfini(struct thread *td)
2025 MPASS(stp->st_flags == 0);
2026 MPASS(STAILQ_EMPTY(&stp->st_selq));
2028 free(stp->st_free1, M_SELFD);
2030 free(stp->st_free2, M_SELFD);
2032 cv_destroy(&stp->st_wait);
2033 mtx_destroy(&stp->st_mtx);
2034 free(stp, M_SELECT);
2038 * Remove the references to the thread from all of the objects we were
2042 seltdclear(struct thread *td)
2049 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
2050 selfdfree(stp, sfp);
2054 static void selectinit(void *);
2055 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
2057 selectinit(void *dummy __unused)
2060 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
2064 * Set up a syscall return value that follows the convention specified for
2065 * posix_* functions.
2068 kern_posix_error(struct thread *td, int error)
2073 td->td_errno = error;
2074 td->td_pflags |= TDP_NERRNO;
2075 td->td_retval[0] = error;