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. */
162 static uma_zone_t selfd_zone;
163 static struct mtx_pool *mtxpool_select;
167 devfs_iosize_max(void)
170 return (devfs_iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
171 INT_MAX : SSIZE_MAX);
178 return (iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
179 INT_MAX : SSIZE_MAX);
183 #ifndef _SYS_SYSPROTO_H_
191 sys_read(struct thread *td, struct read_args *uap)
197 if (uap->nbyte > IOSIZE_MAX)
199 aiov.iov_base = uap->buf;
200 aiov.iov_len = uap->nbyte;
201 auio.uio_iov = &aiov;
203 auio.uio_resid = uap->nbyte;
204 auio.uio_segflg = UIO_USERSPACE;
205 error = kern_readv(td, uap->fd, &auio);
210 * Positioned read system call
212 #ifndef _SYS_SYSPROTO_H_
222 sys_pread(struct thread *td, struct pread_args *uap)
225 return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
229 kern_pread(struct thread *td, int fd, void *buf, size_t nbyte, off_t offset)
235 if (nbyte > IOSIZE_MAX)
238 aiov.iov_len = nbyte;
239 auio.uio_iov = &aiov;
241 auio.uio_resid = nbyte;
242 auio.uio_segflg = UIO_USERSPACE;
243 error = kern_preadv(td, fd, &auio, offset);
247 #if defined(COMPAT_FREEBSD6)
249 freebsd6_pread(struct thread *td, struct freebsd6_pread_args *uap)
252 return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
257 * Scatter read system call.
259 #ifndef _SYS_SYSPROTO_H_
267 sys_readv(struct thread *td, struct readv_args *uap)
272 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
275 error = kern_readv(td, uap->fd, auio);
281 kern_readv(struct thread *td, int fd, struct uio *auio)
286 error = fget_read(td, fd, &cap_read_rights, &fp);
289 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
295 * Scatter positioned read system call.
297 #ifndef _SYS_SYSPROTO_H_
306 sys_preadv(struct thread *td, struct preadv_args *uap)
311 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
314 error = kern_preadv(td, uap->fd, auio, uap->offset);
320 kern_preadv(struct thread *td, int fd, struct uio *auio, off_t offset)
325 error = fget_read(td, fd, &cap_pread_rights, &fp);
328 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
330 else if (offset < 0 &&
331 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
334 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
340 * Common code for readv and preadv that reads data in
341 * from a file using the passed in uio, offset, and flags.
344 dofileread(struct thread *td, int fd, struct file *fp, struct uio *auio,
345 off_t offset, int flags)
350 struct uio *ktruio = NULL;
355 /* Finish zero length reads right here */
356 if (auio->uio_resid == 0) {
357 td->td_retval[0] = 0;
360 auio->uio_rw = UIO_READ;
361 auio->uio_offset = offset;
364 if (KTRPOINT(td, KTR_GENIO))
365 ktruio = cloneuio(auio);
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))
373 cnt -= auio->uio_resid;
375 if (ktruio != NULL) {
376 ktruio->uio_resid = cnt;
377 ktrgenio(fd, UIO_READ, ktruio, error);
380 td->td_retval[0] = cnt;
384 #ifndef _SYS_SYSPROTO_H_
392 sys_write(struct thread *td, struct write_args *uap)
398 if (uap->nbyte > IOSIZE_MAX)
400 aiov.iov_base = (void *)(uintptr_t)uap->buf;
401 aiov.iov_len = uap->nbyte;
402 auio.uio_iov = &aiov;
404 auio.uio_resid = uap->nbyte;
405 auio.uio_segflg = UIO_USERSPACE;
406 error = kern_writev(td, uap->fd, &auio);
411 * Positioned write system call.
413 #ifndef _SYS_SYSPROTO_H_
423 sys_pwrite(struct thread *td, struct pwrite_args *uap)
426 return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
430 kern_pwrite(struct thread *td, int fd, const void *buf, size_t nbyte,
437 if (nbyte > IOSIZE_MAX)
439 aiov.iov_base = (void *)(uintptr_t)buf;
440 aiov.iov_len = nbyte;
441 auio.uio_iov = &aiov;
443 auio.uio_resid = nbyte;
444 auio.uio_segflg = UIO_USERSPACE;
445 error = kern_pwritev(td, fd, &auio, offset);
449 #if defined(COMPAT_FREEBSD6)
451 freebsd6_pwrite(struct thread *td, struct freebsd6_pwrite_args *uap)
454 return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
459 * Gather write system call.
461 #ifndef _SYS_SYSPROTO_H_
469 sys_writev(struct thread *td, struct writev_args *uap)
474 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
477 error = kern_writev(td, uap->fd, auio);
483 kern_writev(struct thread *td, int fd, struct uio *auio)
488 error = fget_write(td, fd, &cap_write_rights, &fp);
491 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
497 * Gather positioned write system call.
499 #ifndef _SYS_SYSPROTO_H_
500 struct pwritev_args {
508 sys_pwritev(struct thread *td, struct pwritev_args *uap)
513 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
516 error = kern_pwritev(td, uap->fd, auio, uap->offset);
522 kern_pwritev(struct thread *td, int fd, struct uio *auio, off_t offset)
527 error = fget_write(td, fd, &cap_pwrite_rights, &fp);
530 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
532 else if (offset < 0 &&
533 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
536 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
542 * Common code for writev and pwritev that writes data to
543 * a file using the passed in uio, offset, and flags.
546 dofilewrite(struct thread *td, int fd, struct file *fp, struct uio *auio,
547 off_t offset, int flags)
552 struct uio *ktruio = NULL;
556 auio->uio_rw = UIO_WRITE;
558 auio->uio_offset = offset;
560 if (KTRPOINT(td, KTR_GENIO))
561 ktruio = cloneuio(auio);
563 cnt = auio->uio_resid;
564 if (fp->f_type == DTYPE_VNODE &&
565 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
567 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
568 if (auio->uio_resid != cnt && (error == ERESTART ||
569 error == EINTR || error == EWOULDBLOCK))
571 /* Socket layer is responsible for issuing SIGPIPE. */
572 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
573 PROC_LOCK(td->td_proc);
574 tdsignal(td, SIGPIPE);
575 PROC_UNLOCK(td->td_proc);
578 cnt -= auio->uio_resid;
580 if (ktruio != NULL) {
581 ktruio->uio_resid = cnt;
582 ktrgenio(fd, UIO_WRITE, ktruio, error);
585 td->td_retval[0] = cnt;
590 * Truncate a file given a file descriptor.
592 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
593 * descriptor isn't writable.
596 kern_ftruncate(struct thread *td, int fd, off_t length)
604 error = fget(td, fd, &cap_ftruncate_rights, &fp);
607 AUDIT_ARG_FILE(td->td_proc, fp);
608 if (!(fp->f_flag & FWRITE)) {
612 error = fo_truncate(fp, length, td->td_ucred, td);
617 #ifndef _SYS_SYSPROTO_H_
618 struct ftruncate_args {
625 sys_ftruncate(struct thread *td, struct ftruncate_args *uap)
628 return (kern_ftruncate(td, uap->fd, uap->length));
631 #if defined(COMPAT_43)
632 #ifndef _SYS_SYSPROTO_H_
633 struct oftruncate_args {
639 oftruncate(struct thread *td, struct oftruncate_args *uap)
642 return (kern_ftruncate(td, uap->fd, uap->length));
644 #endif /* COMPAT_43 */
646 #ifndef _SYS_SYSPROTO_H_
655 sys_ioctl(struct thread *td, struct ioctl_args *uap)
657 u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
663 if (uap->com > 0xffffffff) {
665 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
666 td->td_proc->p_pid, td->td_name, uap->com);
667 uap->com &= 0xffffffff;
672 * Interpret high order word to find amount of data to be
673 * copied to/from the user's address space.
675 size = IOCPARM_LEN(com);
676 if ((size > IOCPARM_MAX) ||
677 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
678 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
679 ((com & IOC_OUT) && size == 0) ||
681 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
683 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
687 if (com & IOC_VOID) {
688 /* Integer argument. */
689 arg = (intptr_t)uap->data;
693 if (size > SYS_IOCTL_SMALL_SIZE)
694 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
699 data = (void *)&uap->data;
701 error = copyin(uap->data, data, (u_int)size);
704 } else if (com & IOC_OUT) {
706 * Zero the buffer so the user always
707 * gets back something deterministic.
712 error = kern_ioctl(td, uap->fd, com, data);
714 if (error == 0 && (com & IOC_OUT))
715 error = copyout(data, uap->data, (u_int)size);
718 if (size > SYS_IOCTL_SMALL_SIZE)
719 free(data, M_IOCTLOPS);
724 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
727 struct filedesc *fdp;
728 int error, tmp, locked;
733 fdp = td->td_proc->p_fd;
746 locked = LA_UNLOCKED;
752 if ((fp = fget_locked(fdp, fd)) == NULL) {
756 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
757 fp = NULL; /* fhold() was not called yet */
761 if (locked == LA_SLOCKED) {
762 FILEDESC_SUNLOCK(fdp);
763 locked = LA_UNLOCKED;
766 error = fget(td, fd, &cap_ioctl_rights, &fp);
772 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
779 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
782 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
785 if ((tmp = *(int *)data))
786 atomic_set_int(&fp->f_flag, FNONBLOCK);
788 atomic_clear_int(&fp->f_flag, FNONBLOCK);
792 if ((tmp = *(int *)data))
793 atomic_set_int(&fp->f_flag, FASYNC);
795 atomic_clear_int(&fp->f_flag, FASYNC);
800 error = fo_ioctl(fp, com, data, td->td_ucred, td);
804 FILEDESC_XUNLOCK(fdp);
808 FILEDESC_SUNLOCK(fdp);
812 FILEDESC_UNLOCK_ASSERT(fdp);
821 poll_no_poll(int events)
824 * Return true for read/write. If the user asked for something
825 * special, return POLLNVAL, so that clients have a way of
826 * determining reliably whether or not the extended
827 * functionality is present without hard-coding knowledge
828 * of specific filesystem implementations.
830 if (events & ~POLLSTANDARD)
833 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
837 sys_pselect(struct thread *td, struct pselect_args *uap)
840 struct timeval tv, *tvp;
844 if (uap->ts != NULL) {
845 error = copyin(uap->ts, &ts, sizeof(ts));
848 TIMESPEC_TO_TIMEVAL(&tv, &ts);
852 if (uap->sm != NULL) {
853 error = copyin(uap->sm, &set, sizeof(set));
859 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
864 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
865 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
870 error = kern_sigprocmask(td, SIG_SETMASK, uset,
871 &td->td_oldsigmask, 0);
874 td->td_pflags |= TDP_OLDMASK;
876 * Make sure that ast() is called on return to
877 * usermode and TDP_OLDMASK is cleared, restoring old
881 td->td_flags |= TDF_ASTPENDING;
884 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
888 #ifndef _SYS_SYSPROTO_H_
891 fd_set *in, *ou, *ex;
896 sys_select(struct thread *td, struct select_args *uap)
898 struct timeval tv, *tvp;
901 if (uap->tv != NULL) {
902 error = copyin(uap->tv, &tv, sizeof(tv));
909 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
914 * In the unlikely case when user specified n greater then the last
915 * open file descriptor, check that no bits are set after the last
916 * valid fd. We must return EBADF if any is set.
918 * There are applications that rely on the behaviour.
920 * nd is fd_lastfile + 1.
923 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
929 if (nd >= ndu || fd_in == NULL)
933 bits = 0; /* silence gcc */
934 for (i = nd; i < ndu; i++) {
936 #if BYTE_ORDER == LITTLE_ENDIAN
937 addr = (char *)fd_in + b;
939 addr = (char *)fd_in;
940 if (abi_nfdbits == NFDBITS) {
941 addr += rounddown(b, sizeof(fd_mask)) +
942 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
944 addr += rounddown(b, sizeof(uint32_t)) +
945 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
955 if ((bits & (1 << (i % NBBY))) != 0)
962 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
963 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
965 struct filedesc *fdp;
967 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
968 * infds with the new FD_SETSIZE of 1024, and more than enough for
969 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
972 fd_mask s_selbits[howmany(2048, NFDBITS)];
973 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
975 sbintime_t asbt, precision, rsbt;
976 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
981 fdp = td->td_proc->p_fd;
983 lf = fdp->fd_lastfile;
987 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
990 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
993 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
998 * Allocate just enough bits for the non-null fd_sets. Use the
999 * preallocated auto buffer if possible.
1001 nfdbits = roundup(nd, NFDBITS);
1002 ncpbytes = nfdbits / NBBY;
1003 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1006 nbufbytes += 2 * ncpbytes;
1008 nbufbytes += 2 * ncpbytes;
1010 nbufbytes += 2 * ncpbytes;
1011 if (nbufbytes <= sizeof s_selbits)
1012 selbits = &s_selbits[0];
1014 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1017 * Assign pointers into the bit buffers and fetch the input bits.
1018 * Put the output buffers together so that they can be bzeroed
1022 #define getbits(name, x) \
1024 if (name == NULL) { \
1028 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1030 sbp += ncpbytes / sizeof *sbp; \
1031 error = copyin(name, ibits[x], ncpubytes); \
1034 if (ncpbytes != ncpubytes) \
1035 bzero((char *)ibits[x] + ncpubytes, \
1036 ncpbytes - ncpubytes); \
1044 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1046 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1047 * we are running under 32-bit emulation. This should be more
1050 #define swizzle_fdset(bits) \
1051 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1053 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1054 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1057 #define swizzle_fdset(bits)
1060 /* Make sure the bit order makes it through an ABI transition */
1061 swizzle_fdset(ibits[0]);
1062 swizzle_fdset(ibits[1]);
1063 swizzle_fdset(ibits[2]);
1066 bzero(selbits, nbufbytes / 2);
1071 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1072 rtv.tv_usec >= 1000000) {
1076 if (!timevalisset(&rtv))
1078 else if (rtv.tv_sec <= INT32_MAX) {
1079 rsbt = tvtosbt(rtv);
1081 precision >>= tc_precexp;
1082 if (TIMESEL(&asbt, rsbt))
1083 asbt += tc_tick_sbt;
1084 if (asbt <= SBT_MAX - rsbt)
1093 /* Iterate until the timeout expires or descriptors become ready. */
1095 error = selscan(td, ibits, obits, nd);
1096 if (error || td->td_retval[0] != 0)
1098 error = seltdwait(td, asbt, precision);
1101 error = selrescan(td, ibits, obits);
1102 if (error || td->td_retval[0] != 0)
1108 /* select is not restarted after signals... */
1109 if (error == ERESTART)
1111 if (error == EWOULDBLOCK)
1114 /* swizzle bit order back, if necessary */
1115 swizzle_fdset(obits[0]);
1116 swizzle_fdset(obits[1]);
1117 swizzle_fdset(obits[2]);
1118 #undef swizzle_fdset
1120 #define putbits(name, x) \
1121 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1131 if (selbits != &s_selbits[0])
1132 free(selbits, M_SELECT);
1137 * Convert a select bit set to poll flags.
1139 * The backend always returns POLLHUP/POLLERR if appropriate and we
1140 * return this as a set bit in any set.
1142 static int select_flags[3] = {
1143 POLLRDNORM | POLLHUP | POLLERR,
1144 POLLWRNORM | POLLHUP | POLLERR,
1145 POLLRDBAND | POLLERR
1149 * Compute the fo_poll flags required for a fd given by the index and
1150 * bit position in the fd_mask array.
1153 selflags(fd_mask **ibits, int idx, fd_mask bit)
1159 for (msk = 0; msk < 3; msk++) {
1160 if (ibits[msk] == NULL)
1162 if ((ibits[msk][idx] & bit) == 0)
1164 flags |= select_flags[msk];
1170 * Set the appropriate output bits given a mask of fired events and the
1171 * input bits originally requested.
1174 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1180 for (msk = 0; msk < 3; msk++) {
1181 if ((events & select_flags[msk]) == 0)
1183 if (ibits[msk] == NULL)
1185 if ((ibits[msk][idx] & bit) == 0)
1188 * XXX Check for a duplicate set. This can occur because a
1189 * socket calls selrecord() twice for each poll() call
1190 * resulting in two selfds per real fd. selrescan() will
1191 * call selsetbits twice as a result.
1193 if ((obits[msk][idx] & bit) != 0)
1195 obits[msk][idx] |= bit;
1203 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1206 return (fget_unlocked(fdp, fd, &cap_event_rights, fpp, NULL));
1210 * Traverse the list of fds attached to this thread's seltd and check for
1214 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1216 struct filedesc *fdp;
1226 fdp = td->td_proc->p_fd;
1229 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1230 fd = (int)(uintptr_t)sfp->sf_cookie;
1232 selfdfree(stp, sfp);
1233 /* If the selinfo wasn't cleared the event didn't fire. */
1236 error = getselfd_cap(fdp, fd, &fp);
1240 bit = (fd_mask)1 << (fd % NFDBITS);
1241 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1244 n += selsetbits(ibits, obits, idx, bit, ev);
1247 td->td_retval[0] = n;
1252 * Perform the initial filedescriptor scan and register ourselves with
1256 selscan(struct thread *td, fd_mask **ibits, fd_mask **obits, int nfd)
1258 struct filedesc *fdp;
1261 int ev, flags, end, fd;
1265 fdp = td->td_proc->p_fd;
1267 for (idx = 0, fd = 0; fd < nfd; idx++) {
1268 end = imin(fd + NFDBITS, nfd);
1269 for (bit = 1; fd < end; bit <<= 1, fd++) {
1270 /* Compute the list of events we're interested in. */
1271 flags = selflags(ibits, idx, bit);
1274 error = getselfd_cap(fdp, fd, &fp);
1277 selfdalloc(td, (void *)(uintptr_t)fd);
1278 ev = fo_poll(fp, flags, td->td_ucred, td);
1281 n += selsetbits(ibits, obits, idx, bit, ev);
1285 td->td_retval[0] = n;
1290 sys_poll(struct thread *td, struct poll_args *uap)
1292 struct timespec ts, *tsp;
1294 if (uap->timeout != INFTIM) {
1295 if (uap->timeout < 0)
1297 ts.tv_sec = uap->timeout / 1000;
1298 ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1303 return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1307 kern_poll(struct thread *td, struct pollfd *ufds, u_int nfds,
1308 struct timespec *tsp, sigset_t *uset)
1310 struct pollfd *kfds;
1311 struct pollfd stackfds[32];
1312 sbintime_t sbt, precision, tmp;
1319 if (tsp->tv_sec < 0)
1321 if (tsp->tv_nsec < 0 || tsp->tv_nsec >= 1000000000)
1323 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1327 if (ts.tv_sec > INT32_MAX / 2) {
1328 over = ts.tv_sec - INT32_MAX / 2;
1334 precision >>= tc_precexp;
1335 if (TIMESEL(&sbt, tmp))
1343 * This is kinda bogus. We have fd limits, but that is not
1344 * really related to the size of the pollfd array. Make sure
1345 * we let the process use at least FD_SETSIZE entries and at
1346 * least enough for the system-wide limits. We want to be reasonably
1347 * safe, but not overly restrictive.
1349 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1351 if (nfds > nitems(stackfds))
1352 kfds = mallocarray(nfds, sizeof(*kfds), M_TEMP, M_WAITOK);
1355 error = copyin(ufds, kfds, nfds * sizeof(*kfds));
1360 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1361 &td->td_oldsigmask, 0);
1364 td->td_pflags |= TDP_OLDMASK;
1366 * Make sure that ast() is called on return to
1367 * usermode and TDP_OLDMASK is cleared, restoring old
1371 td->td_flags |= TDF_ASTPENDING;
1376 /* Iterate until the timeout expires or descriptors become ready. */
1378 error = pollscan(td, kfds, nfds);
1379 if (error || td->td_retval[0] != 0)
1381 error = seltdwait(td, sbt, precision);
1384 error = pollrescan(td);
1385 if (error || td->td_retval[0] != 0)
1391 /* poll is not restarted after signals... */
1392 if (error == ERESTART)
1394 if (error == EWOULDBLOCK)
1397 error = pollout(td, kfds, ufds, nfds);
1402 if (nfds > nitems(stackfds))
1408 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1410 struct timespec ts, *tsp;
1414 if (uap->ts != NULL) {
1415 error = copyin(uap->ts, &ts, sizeof(ts));
1421 if (uap->set != NULL) {
1422 error = copyin(uap->set, &set, sizeof(set));
1429 * fds is still a pointer to user space. kern_poll() will
1430 * take care of copyin that array to the kernel space.
1433 return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1437 pollrescan(struct thread *td)
1443 struct filedesc *fdp;
1449 fdp = td->td_proc->p_fd;
1451 FILEDESC_SLOCK(fdp);
1452 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1453 fd = (struct pollfd *)sfp->sf_cookie;
1455 selfdfree(stp, sfp);
1456 /* If the selinfo wasn't cleared the event didn't fire. */
1459 fp = fdp->fd_ofiles[fd->fd].fde_file;
1462 cap_check(cap_rights(fdp, fd->fd), &cap_event_rights) != 0)
1467 fd->revents = POLLNVAL;
1473 * Note: backend also returns POLLHUP and
1474 * POLLERR if appropriate.
1476 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1477 if (fd->revents != 0)
1480 FILEDESC_SUNLOCK(fdp);
1482 td->td_retval[0] = n;
1488 pollout(struct thread *td, struct pollfd *fds, struct pollfd *ufds, u_int nfd)
1494 for (i = 0; i < nfd; i++) {
1495 error = copyout(&fds->revents, &ufds->revents,
1496 sizeof(ufds->revents));
1499 if (fds->revents != 0)
1504 td->td_retval[0] = n;
1509 pollscan(struct thread *td, struct pollfd *fds, u_int nfd)
1511 struct filedesc *fdp = td->td_proc->p_fd;
1515 FILEDESC_SLOCK(fdp);
1516 for (i = 0; i < nfd; i++, fds++) {
1517 if (fds->fd > fdp->fd_lastfile) {
1518 fds->revents = POLLNVAL;
1520 } else if (fds->fd < 0) {
1523 fp = fdp->fd_ofiles[fds->fd].fde_file;
1526 cap_check(cap_rights(fdp, fds->fd), &cap_event_rights) != 0)
1531 fds->revents = POLLNVAL;
1535 * Note: backend also returns POLLHUP and
1536 * POLLERR if appropriate.
1538 selfdalloc(td, fds);
1539 fds->revents = fo_poll(fp, fds->events,
1542 * POSIX requires POLLOUT to be never
1543 * set simultaneously with POLLHUP.
1545 if ((fds->revents & POLLHUP) != 0)
1546 fds->revents &= ~POLLOUT;
1548 if (fds->revents != 0)
1553 FILEDESC_SUNLOCK(fdp);
1554 td->td_retval[0] = n;
1559 * XXX This was created specifically to support netncp and netsmb. This
1560 * allows the caller to specify a socket to wait for events on. It returns
1561 * 0 if any events matched and an error otherwise. There is no way to
1562 * determine which events fired.
1565 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1568 sbintime_t asbt, precision, rsbt;
1571 precision = 0; /* stupid gcc! */
1574 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1575 rtv.tv_usec >= 1000000)
1577 if (!timevalisset(&rtv))
1579 else if (rtv.tv_sec <= INT32_MAX) {
1580 rsbt = tvtosbt(rtv);
1582 precision >>= tc_precexp;
1583 if (TIMESEL(&asbt, rsbt))
1584 asbt += tc_tick_sbt;
1585 if (asbt <= SBT_MAX - rsbt)
1595 * Iterate until the timeout expires or the socket becomes ready.
1598 selfdalloc(td, NULL);
1599 error = sopoll(so, events, NULL, td);
1600 /* error here is actually the ready events. */
1603 error = seltdwait(td, asbt, precision);
1608 /* XXX Duplicates ncp/smb behavior. */
1609 if (error == ERESTART)
1615 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1616 * have two select sets, one for read and another for write.
1619 selfdalloc(struct thread *td, void *cookie)
1624 if (stp->st_free1 == NULL)
1625 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1626 stp->st_free1->sf_td = stp;
1627 stp->st_free1->sf_cookie = cookie;
1628 if (stp->st_free2 == NULL)
1629 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1630 stp->st_free2->sf_td = stp;
1631 stp->st_free2->sf_cookie = cookie;
1635 selfdfree(struct seltd *stp, struct selfd *sfp)
1637 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1638 if (sfp->sf_si != NULL) {
1639 mtx_lock(sfp->sf_mtx);
1640 if (sfp->sf_si != NULL) {
1641 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1642 refcount_release(&sfp->sf_refs);
1644 mtx_unlock(sfp->sf_mtx);
1646 if (refcount_release(&sfp->sf_refs))
1647 uma_zfree(selfd_zone, sfp);
1650 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1652 seldrain(struct selinfo *sip)
1656 * This feature is already provided by doselwakeup(), thus it is
1657 * enough to go for it.
1658 * Eventually, the context, should take care to avoid races
1659 * between thread calling select()/poll() and file descriptor
1660 * detaching, but, again, the races are just the same as
1663 doselwakeup(sip, -1);
1667 * Record a select request.
1670 selrecord(struct thread *selector, struct selinfo *sip)
1676 stp = selector->td_sel;
1678 * Don't record when doing a rescan.
1680 if (stp->st_flags & SELTD_RESCAN)
1683 * Grab one of the preallocated descriptors.
1686 if ((sfp = stp->st_free1) != NULL)
1687 stp->st_free1 = NULL;
1688 else if ((sfp = stp->st_free2) != NULL)
1689 stp->st_free2 = NULL;
1691 panic("selrecord: No free selfd on selq");
1694 mtxp = mtx_pool_find(mtxpool_select, sip);
1696 * Initialize the sfp and queue it in the thread.
1700 refcount_init(&sfp->sf_refs, 2);
1701 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1703 * Now that we've locked the sip, check for initialization.
1706 if (sip->si_mtx == NULL) {
1708 TAILQ_INIT(&sip->si_tdlist);
1711 * Add this thread to the list of selfds listening on this selinfo.
1713 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1714 mtx_unlock(sip->si_mtx);
1717 /* Wake up a selecting thread. */
1719 selwakeup(struct selinfo *sip)
1721 doselwakeup(sip, -1);
1724 /* Wake up a selecting thread, and set its priority. */
1726 selwakeuppri(struct selinfo *sip, int pri)
1728 doselwakeup(sip, pri);
1732 * Do a wakeup when a selectable event occurs.
1735 doselwakeup(struct selinfo *sip, int pri)
1741 /* If it's not initialized there can't be any waiters. */
1742 if (sip->si_mtx == NULL)
1745 * Locking the selinfo locks all selfds associated with it.
1747 mtx_lock(sip->si_mtx);
1748 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1750 * Once we remove this sfp from the list and clear the
1751 * sf_si seltdclear will know to ignore this si.
1753 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1756 mtx_lock(&stp->st_mtx);
1757 stp->st_flags |= SELTD_PENDING;
1758 cv_broadcastpri(&stp->st_wait, pri);
1759 mtx_unlock(&stp->st_mtx);
1760 if (refcount_release(&sfp->sf_refs))
1761 uma_zfree(selfd_zone, sfp);
1763 mtx_unlock(sip->si_mtx);
1767 seltdinit(struct thread *td)
1771 if ((stp = td->td_sel) != NULL)
1773 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1774 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1775 cv_init(&stp->st_wait, "select");
1778 STAILQ_INIT(&stp->st_selq);
1782 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1789 * An event of interest may occur while we do not hold the seltd
1790 * locked so check the pending flag before we sleep.
1792 mtx_lock(&stp->st_mtx);
1794 * Any further calls to selrecord will be a rescan.
1796 stp->st_flags |= SELTD_RESCAN;
1797 if (stp->st_flags & SELTD_PENDING) {
1798 mtx_unlock(&stp->st_mtx);
1802 error = EWOULDBLOCK;
1804 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1805 sbt, precision, C_ABSOLUTE);
1807 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1808 mtx_unlock(&stp->st_mtx);
1814 seltdfini(struct thread *td)
1822 uma_zfree(selfd_zone, stp->st_free1);
1824 uma_zfree(selfd_zone, stp->st_free2);
1826 cv_destroy(&stp->st_wait);
1827 mtx_destroy(&stp->st_mtx);
1828 free(stp, M_SELECT);
1832 * Remove the references to the thread from all of the objects we were
1836 seltdclear(struct thread *td)
1843 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1844 selfdfree(stp, sfp);
1848 static void selectinit(void *);
1849 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1851 selectinit(void *dummy __unused)
1854 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1855 NULL, NULL, UMA_ALIGN_PTR, 0);
1856 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1860 * Set up a syscall return value that follows the convention specified for
1861 * posix_* functions.
1864 kern_posix_error(struct thread *td, int error)
1869 td->td_errno = error;
1870 td->td_pflags |= TDP_NERRNO;
1871 td->td_retval[0] = error;