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/kernel.h>
60 #include <sys/limits.h>
61 #include <sys/malloc.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>
72 #include <sys/condvar.h>
74 #include <sys/ktrace.h>
77 #include <security/audit/audit.h>
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.
90 #define SYS_IOCTL_SMALL_SIZE 128 /* bytes */
91 #define SYS_IOCTL_SMALL_ALIGN 8 /* bytes */
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");
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.
107 CTASSERT(sizeof(register_t) >= sizeof(size_t));
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");
113 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
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 *,
123 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
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 *);
131 * One seltd per-thread allocated on demand as needed.
133 * t - protected by st_mtx
134 * k - Only accessed by curthread or read-only
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. */
145 #define SELTD_PENDING 0x0001 /* We have pending events. */
146 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
149 * One selfd allocated per-thread per-file-descriptor.
150 * f - protected by sf_mtx
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. */
161 MALLOC_DEFINE(M_SELFD, "selfd", "selfd");
162 static struct mtx_pool *mtxpool_select;
166 devfs_iosize_max(void)
169 return (devfs_iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
170 INT_MAX : SSIZE_MAX);
177 return (iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
178 INT_MAX : SSIZE_MAX);
182 #ifndef _SYS_SYSPROTO_H_
190 sys_read(struct thread *td, struct read_args *uap)
196 if (uap->nbyte > IOSIZE_MAX)
198 aiov.iov_base = uap->buf;
199 aiov.iov_len = uap->nbyte;
200 auio.uio_iov = &aiov;
202 auio.uio_resid = uap->nbyte;
203 auio.uio_segflg = UIO_USERSPACE;
204 error = kern_readv(td, uap->fd, &auio);
209 * Positioned read system call
211 #ifndef _SYS_SYSPROTO_H_
221 sys_pread(struct thread *td, struct pread_args *uap)
224 return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
228 kern_pread(struct thread *td, int fd, void *buf, size_t nbyte, off_t offset)
234 if (nbyte > IOSIZE_MAX)
237 aiov.iov_len = nbyte;
238 auio.uio_iov = &aiov;
240 auio.uio_resid = nbyte;
241 auio.uio_segflg = UIO_USERSPACE;
242 error = kern_preadv(td, fd, &auio, offset);
246 #if defined(COMPAT_FREEBSD6)
248 freebsd6_pread(struct thread *td, struct freebsd6_pread_args *uap)
251 return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
256 * Scatter read system call.
258 #ifndef _SYS_SYSPROTO_H_
266 sys_readv(struct thread *td, struct readv_args *uap)
271 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
274 error = kern_readv(td, uap->fd, auio);
280 kern_readv(struct thread *td, int fd, struct uio *auio)
285 error = fget_read(td, fd, &cap_read_rights, &fp);
288 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
294 * Scatter positioned read system call.
296 #ifndef _SYS_SYSPROTO_H_
305 sys_preadv(struct thread *td, struct preadv_args *uap)
310 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
313 error = kern_preadv(td, uap->fd, auio, uap->offset);
319 kern_preadv(struct thread *td, int fd, struct uio *auio, off_t offset)
324 error = fget_read(td, fd, &cap_pread_rights, &fp);
327 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
329 else if (offset < 0 &&
330 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
333 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
339 * Common code for readv and preadv that reads data in
340 * from a file using the passed in uio, offset, and flags.
343 dofileread(struct thread *td, int fd, struct file *fp, struct uio *auio,
344 off_t offset, int flags)
349 struct uio *ktruio = NULL;
354 /* Finish zero length reads right here */
355 if (auio->uio_resid == 0) {
356 td->td_retval[0] = 0;
359 auio->uio_rw = UIO_READ;
360 auio->uio_offset = offset;
363 if (KTRPOINT(td, KTR_GENIO))
364 ktruio = cloneuio(auio);
366 cnt = auio->uio_resid;
367 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
368 if (auio->uio_resid != cnt && (error == ERESTART ||
369 error == EINTR || error == EWOULDBLOCK))
372 cnt -= auio->uio_resid;
374 if (ktruio != NULL) {
375 ktruio->uio_resid = cnt;
376 ktrgenio(fd, UIO_READ, ktruio, error);
379 td->td_retval[0] = cnt;
383 #ifndef _SYS_SYSPROTO_H_
391 sys_write(struct thread *td, struct write_args *uap)
397 if (uap->nbyte > IOSIZE_MAX)
399 aiov.iov_base = (void *)(uintptr_t)uap->buf;
400 aiov.iov_len = uap->nbyte;
401 auio.uio_iov = &aiov;
403 auio.uio_resid = uap->nbyte;
404 auio.uio_segflg = UIO_USERSPACE;
405 error = kern_writev(td, uap->fd, &auio);
410 * Positioned write system call.
412 #ifndef _SYS_SYSPROTO_H_
422 sys_pwrite(struct thread *td, struct pwrite_args *uap)
425 return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
429 kern_pwrite(struct thread *td, int fd, const void *buf, size_t nbyte,
436 if (nbyte > IOSIZE_MAX)
438 aiov.iov_base = (void *)(uintptr_t)buf;
439 aiov.iov_len = nbyte;
440 auio.uio_iov = &aiov;
442 auio.uio_resid = nbyte;
443 auio.uio_segflg = UIO_USERSPACE;
444 error = kern_pwritev(td, fd, &auio, offset);
448 #if defined(COMPAT_FREEBSD6)
450 freebsd6_pwrite(struct thread *td, struct freebsd6_pwrite_args *uap)
453 return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
458 * Gather write system call.
460 #ifndef _SYS_SYSPROTO_H_
468 sys_writev(struct thread *td, struct writev_args *uap)
473 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
476 error = kern_writev(td, uap->fd, auio);
482 kern_writev(struct thread *td, int fd, struct uio *auio)
487 error = fget_write(td, fd, &cap_write_rights, &fp);
490 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
496 * Gather positioned write system call.
498 #ifndef _SYS_SYSPROTO_H_
499 struct pwritev_args {
507 sys_pwritev(struct thread *td, struct pwritev_args *uap)
512 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
515 error = kern_pwritev(td, uap->fd, auio, uap->offset);
521 kern_pwritev(struct thread *td, int fd, struct uio *auio, off_t offset)
526 error = fget_write(td, fd, &cap_pwrite_rights, &fp);
529 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
531 else if (offset < 0 &&
532 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
535 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
541 * Common code for writev and pwritev that writes data to
542 * a file using the passed in uio, offset, and flags.
545 dofilewrite(struct thread *td, int fd, struct file *fp, struct uio *auio,
546 off_t offset, int flags)
551 struct uio *ktruio = NULL;
555 auio->uio_rw = UIO_WRITE;
557 auio->uio_offset = offset;
559 if (KTRPOINT(td, KTR_GENIO))
560 ktruio = cloneuio(auio);
562 cnt = auio->uio_resid;
563 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
564 if (auio->uio_resid != cnt && (error == ERESTART ||
565 error == EINTR || error == EWOULDBLOCK))
567 /* Socket layer is responsible for issuing SIGPIPE. */
568 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
569 PROC_LOCK(td->td_proc);
570 tdsignal(td, SIGPIPE);
571 PROC_UNLOCK(td->td_proc);
574 cnt -= auio->uio_resid;
576 if (ktruio != NULL) {
577 ktruio->uio_resid = cnt;
578 ktrgenio(fd, UIO_WRITE, ktruio, error);
581 td->td_retval[0] = cnt;
586 * Truncate a file given a file descriptor.
588 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
589 * descriptor isn't writable.
592 kern_ftruncate(struct thread *td, int fd, off_t length)
600 error = fget(td, fd, &cap_ftruncate_rights, &fp);
603 AUDIT_ARG_FILE(td->td_proc, fp);
604 if (!(fp->f_flag & FWRITE)) {
608 error = fo_truncate(fp, length, td->td_ucred, td);
613 #ifndef _SYS_SYSPROTO_H_
614 struct ftruncate_args {
621 sys_ftruncate(struct thread *td, struct ftruncate_args *uap)
624 return (kern_ftruncate(td, uap->fd, uap->length));
627 #if defined(COMPAT_43)
628 #ifndef _SYS_SYSPROTO_H_
629 struct oftruncate_args {
635 oftruncate(struct thread *td, struct oftruncate_args *uap)
638 return (kern_ftruncate(td, uap->fd, uap->length));
640 #endif /* COMPAT_43 */
642 #ifndef _SYS_SYSPROTO_H_
651 sys_ioctl(struct thread *td, struct ioctl_args *uap)
653 u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
660 if (uap->com > 0xffffffff) {
662 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
663 td->td_proc->p_pid, td->td_name, uap->com);
666 com = (uint32_t)uap->com;
669 * Interpret high order word to find amount of data to be
670 * copied to/from the user's address space.
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) ||
678 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
680 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
684 if (com & IOC_VOID) {
685 /* Integer argument. */
686 arg = (intptr_t)uap->data;
690 if (size > SYS_IOCTL_SMALL_SIZE)
691 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
696 data = (void *)&uap->data;
698 error = copyin(uap->data, data, (u_int)size);
701 } else if (com & IOC_OUT) {
703 * Zero the buffer so the user always
704 * gets back something deterministic.
709 error = kern_ioctl(td, uap->fd, com, data);
711 if (error == 0 && (com & IOC_OUT))
712 error = copyout(data, uap->data, (u_int)size);
715 if (size > SYS_IOCTL_SMALL_SIZE)
716 free(data, M_IOCTLOPS);
721 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
724 struct filedesc *fdp;
725 int error, tmp, locked;
730 fdp = td->td_proc->p_fd;
743 locked = LA_UNLOCKED;
749 if ((fp = fget_locked(fdp, fd)) == NULL) {
753 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
754 fp = NULL; /* fhold() was not called yet */
762 if (locked == LA_SLOCKED) {
763 FILEDESC_SUNLOCK(fdp);
764 locked = LA_UNLOCKED;
767 error = fget(td, fd, &cap_ioctl_rights, &fp);
773 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
780 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
783 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
786 if ((tmp = *(int *)data))
787 atomic_set_int(&fp->f_flag, FNONBLOCK);
789 atomic_clear_int(&fp->f_flag, FNONBLOCK);
793 if ((tmp = *(int *)data))
794 atomic_set_int(&fp->f_flag, FASYNC);
796 atomic_clear_int(&fp->f_flag, FASYNC);
801 error = fo_ioctl(fp, com, data, td->td_ucred, td);
805 FILEDESC_XUNLOCK(fdp);
809 FILEDESC_SUNLOCK(fdp);
813 FILEDESC_UNLOCK_ASSERT(fdp);
822 sys_posix_fallocate(struct thread *td, struct posix_fallocate_args *uap)
826 error = kern_posix_fallocate(td, uap->fd, uap->offset, uap->len);
827 return (kern_posix_error(td, error));
831 kern_posix_fallocate(struct thread *td, int fd, off_t offset, off_t len)
837 if (offset < 0 || len <= 0)
839 /* Check for wrap. */
840 if (offset > OFF_MAX - len)
843 error = fget(td, fd, &cap_pwrite_rights, &fp);
846 AUDIT_ARG_FILE(td->td_proc, fp);
847 if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
851 if ((fp->f_flag & FWRITE) == 0) {
856 error = fo_fallocate(fp, offset, len, td);
863 poll_no_poll(int events)
866 * Return true for read/write. If the user asked for something
867 * special, return POLLNVAL, so that clients have a way of
868 * determining reliably whether or not the extended
869 * functionality is present without hard-coding knowledge
870 * of specific filesystem implementations.
872 if (events & ~POLLSTANDARD)
875 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
879 sys_pselect(struct thread *td, struct pselect_args *uap)
882 struct timeval tv, *tvp;
886 if (uap->ts != NULL) {
887 error = copyin(uap->ts, &ts, sizeof(ts));
890 TIMESPEC_TO_TIMEVAL(&tv, &ts);
894 if (uap->sm != NULL) {
895 error = copyin(uap->sm, &set, sizeof(set));
901 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
906 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
907 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
912 error = kern_sigprocmask(td, SIG_SETMASK, uset,
913 &td->td_oldsigmask, 0);
916 td->td_pflags |= TDP_OLDMASK;
918 * Make sure that ast() is called on return to
919 * usermode and TDP_OLDMASK is cleared, restoring old
923 td->td_flags |= TDF_ASTPENDING;
926 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
930 #ifndef _SYS_SYSPROTO_H_
933 fd_set *in, *ou, *ex;
938 sys_select(struct thread *td, struct select_args *uap)
940 struct timeval tv, *tvp;
943 if (uap->tv != NULL) {
944 error = copyin(uap->tv, &tv, sizeof(tv));
951 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
956 * In the unlikely case when user specified n greater then the last
957 * open file descriptor, check that no bits are set after the last
958 * valid fd. We must return EBADF if any is set.
960 * There are applications that rely on the behaviour.
965 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
971 if (nd >= ndu || fd_in == NULL)
975 bits = 0; /* silence gcc */
976 for (i = nd; i < ndu; i++) {
978 #if BYTE_ORDER == LITTLE_ENDIAN
979 addr = (char *)fd_in + b;
981 addr = (char *)fd_in;
982 if (abi_nfdbits == NFDBITS) {
983 addr += rounddown(b, sizeof(fd_mask)) +
984 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
986 addr += rounddown(b, sizeof(uint32_t)) +
987 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
997 if ((bits & (1 << (i % NBBY))) != 0)
1004 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
1005 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
1007 struct filedesc *fdp;
1009 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
1010 * infds with the new FD_SETSIZE of 1024, and more than enough for
1011 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
1014 fd_mask s_selbits[howmany(2048, NFDBITS)];
1015 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
1017 sbintime_t asbt, precision, rsbt;
1018 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
1023 fdp = td->td_proc->p_fd;
1025 lf = fdp->fd_nfiles;
1029 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1032 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1035 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1040 * Allocate just enough bits for the non-null fd_sets. Use the
1041 * preallocated auto buffer if possible.
1043 nfdbits = roundup(nd, NFDBITS);
1044 ncpbytes = nfdbits / NBBY;
1045 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1048 nbufbytes += 2 * ncpbytes;
1050 nbufbytes += 2 * ncpbytes;
1052 nbufbytes += 2 * ncpbytes;
1053 if (nbufbytes <= sizeof s_selbits)
1054 selbits = &s_selbits[0];
1056 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1059 * Assign pointers into the bit buffers and fetch the input bits.
1060 * Put the output buffers together so that they can be bzeroed
1064 #define getbits(name, x) \
1066 if (name == NULL) { \
1070 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1072 sbp += ncpbytes / sizeof *sbp; \
1073 error = copyin(name, ibits[x], ncpubytes); \
1076 if (ncpbytes != ncpubytes) \
1077 bzero((char *)ibits[x] + ncpubytes, \
1078 ncpbytes - ncpubytes); \
1086 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1088 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1089 * we are running under 32-bit emulation. This should be more
1092 #define swizzle_fdset(bits) \
1093 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1095 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1096 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1099 #define swizzle_fdset(bits)
1102 /* Make sure the bit order makes it through an ABI transition */
1103 swizzle_fdset(ibits[0]);
1104 swizzle_fdset(ibits[1]);
1105 swizzle_fdset(ibits[2]);
1108 bzero(selbits, nbufbytes / 2);
1113 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1114 rtv.tv_usec >= 1000000) {
1118 if (!timevalisset(&rtv))
1120 else if (rtv.tv_sec <= INT32_MAX) {
1121 rsbt = tvtosbt(rtv);
1123 precision >>= tc_precexp;
1124 if (TIMESEL(&asbt, rsbt))
1125 asbt += tc_tick_sbt;
1126 if (asbt <= SBT_MAX - rsbt)
1135 /* Iterate until the timeout expires or descriptors become ready. */
1137 error = selscan(td, ibits, obits, nd);
1138 if (error || td->td_retval[0] != 0)
1140 error = seltdwait(td, asbt, precision);
1143 error = selrescan(td, ibits, obits);
1144 if (error || td->td_retval[0] != 0)
1150 /* select is not restarted after signals... */
1151 if (error == ERESTART)
1153 if (error == EWOULDBLOCK)
1156 /* swizzle bit order back, if necessary */
1157 swizzle_fdset(obits[0]);
1158 swizzle_fdset(obits[1]);
1159 swizzle_fdset(obits[2]);
1160 #undef swizzle_fdset
1162 #define putbits(name, x) \
1163 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1173 if (selbits != &s_selbits[0])
1174 free(selbits, M_SELECT);
1179 * Convert a select bit set to poll flags.
1181 * The backend always returns POLLHUP/POLLERR if appropriate and we
1182 * return this as a set bit in any set.
1184 static int select_flags[3] = {
1185 POLLRDNORM | POLLHUP | POLLERR,
1186 POLLWRNORM | POLLHUP | POLLERR,
1187 POLLRDBAND | POLLERR
1191 * Compute the fo_poll flags required for a fd given by the index and
1192 * bit position in the fd_mask array.
1195 selflags(fd_mask **ibits, int idx, fd_mask bit)
1201 for (msk = 0; msk < 3; msk++) {
1202 if (ibits[msk] == NULL)
1204 if ((ibits[msk][idx] & bit) == 0)
1206 flags |= select_flags[msk];
1212 * Set the appropriate output bits given a mask of fired events and the
1213 * input bits originally requested.
1216 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1222 for (msk = 0; msk < 3; msk++) {
1223 if ((events & select_flags[msk]) == 0)
1225 if (ibits[msk] == NULL)
1227 if ((ibits[msk][idx] & bit) == 0)
1230 * XXX Check for a duplicate set. This can occur because a
1231 * socket calls selrecord() twice for each poll() call
1232 * resulting in two selfds per real fd. selrescan() will
1233 * call selsetbits twice as a result.
1235 if ((obits[msk][idx] & bit) != 0)
1237 obits[msk][idx] |= bit;
1245 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1248 return (fget_unlocked(fdp, fd, &cap_event_rights, fpp));
1252 * Traverse the list of fds attached to this thread's seltd and check for
1256 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1258 struct filedesc *fdp;
1268 fdp = td->td_proc->p_fd;
1271 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1272 fd = (int)(uintptr_t)sfp->sf_cookie;
1274 selfdfree(stp, sfp);
1275 /* If the selinfo wasn't cleared the event didn't fire. */
1278 error = getselfd_cap(fdp, fd, &fp);
1282 bit = (fd_mask)1 << (fd % NFDBITS);
1283 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1286 n += selsetbits(ibits, obits, idx, bit, ev);
1289 td->td_retval[0] = n;
1294 * Perform the initial filedescriptor scan and register ourselves with
1298 selscan(struct thread *td, fd_mask **ibits, fd_mask **obits, int nfd)
1300 struct filedesc *fdp;
1303 int ev, flags, end, fd;
1307 fdp = td->td_proc->p_fd;
1309 for (idx = 0, fd = 0; fd < nfd; idx++) {
1310 end = imin(fd + NFDBITS, nfd);
1311 for (bit = 1; fd < end; bit <<= 1, fd++) {
1312 /* Compute the list of events we're interested in. */
1313 flags = selflags(ibits, idx, bit);
1316 error = getselfd_cap(fdp, fd, &fp);
1319 selfdalloc(td, (void *)(uintptr_t)fd);
1320 ev = fo_poll(fp, flags, td->td_ucred, td);
1323 n += selsetbits(ibits, obits, idx, bit, ev);
1327 td->td_retval[0] = n;
1332 sys_poll(struct thread *td, struct poll_args *uap)
1334 struct timespec ts, *tsp;
1336 if (uap->timeout != INFTIM) {
1337 if (uap->timeout < 0)
1339 ts.tv_sec = uap->timeout / 1000;
1340 ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1345 return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1349 kern_poll(struct thread *td, struct pollfd *ufds, u_int nfds,
1350 struct timespec *tsp, sigset_t *uset)
1352 struct pollfd *kfds;
1353 struct pollfd stackfds[32];
1354 sbintime_t sbt, precision, tmp;
1361 if (tsp->tv_sec < 0)
1363 if (tsp->tv_nsec < 0 || tsp->tv_nsec >= 1000000000)
1365 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1369 if (ts.tv_sec > INT32_MAX / 2) {
1370 over = ts.tv_sec - INT32_MAX / 2;
1376 precision >>= tc_precexp;
1377 if (TIMESEL(&sbt, tmp))
1385 * This is kinda bogus. We have fd limits, but that is not
1386 * really related to the size of the pollfd array. Make sure
1387 * we let the process use at least FD_SETSIZE entries and at
1388 * least enough for the system-wide limits. We want to be reasonably
1389 * safe, but not overly restrictive.
1391 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1393 if (nfds > nitems(stackfds))
1394 kfds = mallocarray(nfds, sizeof(*kfds), M_TEMP, M_WAITOK);
1397 error = copyin(ufds, kfds, nfds * sizeof(*kfds));
1402 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1403 &td->td_oldsigmask, 0);
1406 td->td_pflags |= TDP_OLDMASK;
1408 * Make sure that ast() is called on return to
1409 * usermode and TDP_OLDMASK is cleared, restoring old
1413 td->td_flags |= TDF_ASTPENDING;
1418 /* Iterate until the timeout expires or descriptors become ready. */
1420 error = pollscan(td, kfds, nfds);
1421 if (error || td->td_retval[0] != 0)
1423 error = seltdwait(td, sbt, precision);
1426 error = pollrescan(td);
1427 if (error || td->td_retval[0] != 0)
1433 /* poll is not restarted after signals... */
1434 if (error == ERESTART)
1436 if (error == EWOULDBLOCK)
1439 error = pollout(td, kfds, ufds, nfds);
1444 if (nfds > nitems(stackfds))
1450 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1452 struct timespec ts, *tsp;
1456 if (uap->ts != NULL) {
1457 error = copyin(uap->ts, &ts, sizeof(ts));
1463 if (uap->set != NULL) {
1464 error = copyin(uap->set, &set, sizeof(set));
1471 * fds is still a pointer to user space. kern_poll() will
1472 * take care of copyin that array to the kernel space.
1475 return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1480 poll_fget(struct filedesc *fdp, int fd, struct file **fpp)
1482 const struct filedescent *fde;
1483 const struct fdescenttbl *fdt;
1484 const cap_rights_t *haverights;
1488 if (__predict_false(fd >= fdp->fd_nfiles))
1491 fdt = fdp->fd_files;
1492 fde = &fdt->fdt_ofiles[fd];
1494 if (__predict_false(fp == NULL))
1496 haverights = cap_rights_fde_inline(fde);
1497 error = cap_check_inline(haverights, &cap_event_rights);
1498 if (__predict_false(error != 0))
1505 poll_fget(struct filedesc *fdp, int fd, struct file **fpp)
1509 if (__predict_false(fd >= fdp->fd_nfiles))
1512 fp = fdp->fd_ofiles[fd].fde_file;
1513 if (__predict_false(fp == NULL))
1522 pollrescan(struct thread *td)
1528 struct filedesc *fdp;
1534 fdp = td->td_proc->p_fd;
1536 FILEDESC_SLOCK(fdp);
1537 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1538 fd = (struct pollfd *)sfp->sf_cookie;
1540 selfdfree(stp, sfp);
1541 /* If the selinfo wasn't cleared the event didn't fire. */
1544 if (poll_fget(fdp, fd->fd, &fp) != 0) {
1545 fd->revents = POLLNVAL;
1550 * Note: backend also returns POLLHUP and
1551 * POLLERR if appropriate.
1553 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1554 if (fd->revents != 0)
1557 FILEDESC_SUNLOCK(fdp);
1559 td->td_retval[0] = n;
1564 pollout(struct thread *td, struct pollfd *fds, struct pollfd *ufds, u_int nfd)
1570 for (i = 0; i < nfd; i++) {
1571 error = copyout(&fds->revents, &ufds->revents,
1572 sizeof(ufds->revents));
1575 if (fds->revents != 0)
1580 td->td_retval[0] = n;
1585 pollscan(struct thread *td, struct pollfd *fds, u_int nfd)
1587 struct filedesc *fdp;
1592 fdp = td->td_proc->p_fd;
1593 FILEDESC_SLOCK(fdp);
1594 for (i = 0; i < nfd; i++, fds++) {
1599 if (poll_fget(fdp, fds->fd, &fp) != 0) {
1600 fds->revents = POLLNVAL;
1605 * Note: backend also returns POLLHUP and
1606 * POLLERR if appropriate.
1608 selfdalloc(td, fds);
1609 fds->revents = fo_poll(fp, fds->events,
1612 * POSIX requires POLLOUT to be never
1613 * set simultaneously with POLLHUP.
1615 if ((fds->revents & POLLHUP) != 0)
1616 fds->revents &= ~POLLOUT;
1618 if (fds->revents != 0)
1621 FILEDESC_SUNLOCK(fdp);
1622 td->td_retval[0] = n;
1627 * XXX This was created specifically to support netncp and netsmb. This
1628 * allows the caller to specify a socket to wait for events on. It returns
1629 * 0 if any events matched and an error otherwise. There is no way to
1630 * determine which events fired.
1633 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1636 sbintime_t asbt, precision, rsbt;
1639 precision = 0; /* stupid gcc! */
1642 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1643 rtv.tv_usec >= 1000000)
1645 if (!timevalisset(&rtv))
1647 else if (rtv.tv_sec <= INT32_MAX) {
1648 rsbt = tvtosbt(rtv);
1650 precision >>= tc_precexp;
1651 if (TIMESEL(&asbt, rsbt))
1652 asbt += tc_tick_sbt;
1653 if (asbt <= SBT_MAX - rsbt)
1663 * Iterate until the timeout expires or the socket becomes ready.
1666 selfdalloc(td, NULL);
1667 error = sopoll(so, events, NULL, td);
1668 /* error here is actually the ready events. */
1671 error = seltdwait(td, asbt, precision);
1676 /* XXX Duplicates ncp/smb behavior. */
1677 if (error == ERESTART)
1683 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1684 * have two select sets, one for read and another for write.
1687 selfdalloc(struct thread *td, void *cookie)
1692 if (stp->st_free1 == NULL)
1693 stp->st_free1 = malloc(sizeof(*stp->st_free1), M_SELFD, M_WAITOK|M_ZERO);
1694 stp->st_free1->sf_td = stp;
1695 stp->st_free1->sf_cookie = cookie;
1696 if (stp->st_free2 == NULL)
1697 stp->st_free2 = malloc(sizeof(*stp->st_free2), M_SELFD, M_WAITOK|M_ZERO);
1698 stp->st_free2->sf_td = stp;
1699 stp->st_free2->sf_cookie = cookie;
1703 selfdfree(struct seltd *stp, struct selfd *sfp)
1705 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1707 * Paired with doselwakeup.
1709 if (atomic_load_acq_ptr((uintptr_t *)&sfp->sf_si) != (uintptr_t)NULL) {
1710 mtx_lock(sfp->sf_mtx);
1711 if (sfp->sf_si != NULL) {
1712 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1714 mtx_unlock(sfp->sf_mtx);
1719 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1721 seldrain(struct selinfo *sip)
1725 * This feature is already provided by doselwakeup(), thus it is
1726 * enough to go for it.
1727 * Eventually, the context, should take care to avoid races
1728 * between thread calling select()/poll() and file descriptor
1729 * detaching, but, again, the races are just the same as
1732 doselwakeup(sip, -1);
1736 * Record a select request.
1739 selrecord(struct thread *selector, struct selinfo *sip)
1745 stp = selector->td_sel;
1747 * Don't record when doing a rescan.
1749 if (stp->st_flags & SELTD_RESCAN)
1752 * Grab one of the preallocated descriptors.
1755 if ((sfp = stp->st_free1) != NULL)
1756 stp->st_free1 = NULL;
1757 else if ((sfp = stp->st_free2) != NULL)
1758 stp->st_free2 = NULL;
1760 panic("selrecord: No free selfd on selq");
1763 mtxp = mtx_pool_find(mtxpool_select, sip);
1765 * Initialize the sfp and queue it in the thread.
1769 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1771 * Now that we've locked the sip, check for initialization.
1774 if (sip->si_mtx == NULL) {
1776 TAILQ_INIT(&sip->si_tdlist);
1779 * Add this thread to the list of selfds listening on this selinfo.
1781 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1782 mtx_unlock(sip->si_mtx);
1785 /* Wake up a selecting thread. */
1787 selwakeup(struct selinfo *sip)
1789 doselwakeup(sip, -1);
1792 /* Wake up a selecting thread, and set its priority. */
1794 selwakeuppri(struct selinfo *sip, int pri)
1796 doselwakeup(sip, pri);
1800 * Do a wakeup when a selectable event occurs.
1803 doselwakeup(struct selinfo *sip, int pri)
1809 /* If it's not initialized there can't be any waiters. */
1810 if (sip->si_mtx == NULL)
1813 * Locking the selinfo locks all selfds associated with it.
1815 mtx_lock(sip->si_mtx);
1816 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1818 * Once we remove this sfp from the list and clear the
1819 * sf_si seltdclear will know to ignore this si.
1821 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1824 * Paired with selfdfree.
1826 atomic_store_rel_ptr((uintptr_t *)&sfp->sf_si, (uintptr_t)NULL);
1827 mtx_lock(&stp->st_mtx);
1828 stp->st_flags |= SELTD_PENDING;
1829 cv_broadcastpri(&stp->st_wait, pri);
1830 mtx_unlock(&stp->st_mtx);
1832 mtx_unlock(sip->si_mtx);
1836 seltdinit(struct thread *td)
1840 if ((stp = td->td_sel) != NULL)
1842 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1843 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1844 cv_init(&stp->st_wait, "select");
1847 STAILQ_INIT(&stp->st_selq);
1851 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1858 * An event of interest may occur while we do not hold the seltd
1859 * locked so check the pending flag before we sleep.
1861 mtx_lock(&stp->st_mtx);
1863 * Any further calls to selrecord will be a rescan.
1865 stp->st_flags |= SELTD_RESCAN;
1866 if (stp->st_flags & SELTD_PENDING) {
1867 mtx_unlock(&stp->st_mtx);
1871 error = EWOULDBLOCK;
1873 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1874 sbt, precision, C_ABSOLUTE);
1876 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1877 mtx_unlock(&stp->st_mtx);
1883 seltdfini(struct thread *td)
1891 free(stp->st_free1, M_SELFD);
1893 free(stp->st_free2, M_SELFD);
1895 cv_destroy(&stp->st_wait);
1896 mtx_destroy(&stp->st_mtx);
1897 free(stp, M_SELECT);
1901 * Remove the references to the thread from all of the objects we were
1905 seltdclear(struct thread *td)
1912 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1913 selfdfree(stp, sfp);
1917 static void selectinit(void *);
1918 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1920 selectinit(void *dummy __unused)
1923 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1927 * Set up a syscall return value that follows the convention specified for
1928 * posix_* functions.
1931 kern_posix_error(struct thread *td, int error)
1936 td->td_errno = error;
1937 td->td_pflags |= TDP_NERRNO;
1938 td->td_retval[0] = error;