2 * Copyright (c) 1982, 1986, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)sys_generic.c 8.5 (Berkeley) 1/21/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_capsicum.h"
41 #include "opt_compat.h"
42 #include "opt_ktrace.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/capsicum.h>
48 #include <sys/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/fcntl.h>
54 #include <sys/signalvar.h>
55 #include <sys/socketvar.h>
57 #include <sys/kernel.h>
59 #include <sys/limits.h>
60 #include <sys/malloc.h>
62 #include <sys/resourcevar.h>
63 #include <sys/selinfo.h>
64 #include <sys/sleepqueue.h>
65 #include <sys/syscallsubr.h>
66 #include <sys/sysctl.h>
67 #include <sys/sysent.h>
68 #include <sys/vnode.h>
71 #include <sys/condvar.h>
73 #include <sys/ktrace.h>
76 #include <security/audit/audit.h>
79 * The following macro defines how many bytes will be allocated from
80 * the stack instead of memory allocated when passing the IOCTL data
81 * structures from userspace and to the kernel. Some IOCTLs having
82 * small data structures are used very frequently and this small
83 * buffer on the stack gives a significant speedup improvement for
84 * those requests. The value of this define should be greater or equal
85 * to 64 bytes and should also be power of two. The data structure is
86 * currently hard-aligned to a 8-byte boundary on the stack. This
87 * should currently be sufficient for all supported platforms.
89 #define SYS_IOCTL_SMALL_SIZE 128 /* bytes */
90 #define SYS_IOCTL_SMALL_ALIGN 8 /* bytes */
92 int iosize_max_clamp = 1;
93 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
94 &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
95 int devfs_iosize_max_clamp = 1;
96 SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
97 &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
100 * Assert that the return value of read(2) and write(2) syscalls fits
101 * into a register. If not, an architecture will need to provide the
102 * usermode wrappers to reconstruct the result.
104 CTASSERT(sizeof(register_t) >= sizeof(size_t));
106 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
107 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
108 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
110 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
112 static int pollscan(struct thread *, struct pollfd *, u_int);
113 static int pollrescan(struct thread *);
114 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
115 static int selrescan(struct thread *, fd_mask **, fd_mask **);
116 static void selfdalloc(struct thread *, void *);
117 static void selfdfree(struct seltd *, struct selfd *);
118 static int dofileread(struct thread *, int, struct file *, struct uio *,
120 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
122 static void doselwakeup(struct selinfo *, int);
123 static void seltdinit(struct thread *);
124 static int seltdwait(struct thread *, sbintime_t, sbintime_t);
125 static void seltdclear(struct thread *);
128 * One seltd per-thread allocated on demand as needed.
130 * t - protected by st_mtx
131 * k - Only accessed by curthread or read-only
134 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
135 struct selfd *st_free1; /* (k) free fd for read set. */
136 struct selfd *st_free2; /* (k) free fd for write set. */
137 struct mtx st_mtx; /* Protects struct seltd */
138 struct cv st_wait; /* (t) Wait channel. */
139 int st_flags; /* (t) SELTD_ flags. */
142 #define SELTD_PENDING 0x0001 /* We have pending events. */
143 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
146 * One selfd allocated per-thread per-file-descriptor.
147 * f - protected by sf_mtx
150 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
151 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
152 struct selinfo *sf_si; /* (f) selinfo when linked. */
153 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
154 struct seltd *sf_td; /* (k) owning seltd. */
155 void *sf_cookie; /* (k) fd or pollfd. */
158 static uma_zone_t selfd_zone;
159 static struct mtx_pool *mtxpool_select;
161 #ifndef _SYS_SYSPROTO_H_
171 struct read_args *uap;
177 if (uap->nbyte > IOSIZE_MAX)
179 aiov.iov_base = uap->buf;
180 aiov.iov_len = uap->nbyte;
181 auio.uio_iov = &aiov;
183 auio.uio_resid = uap->nbyte;
184 auio.uio_segflg = UIO_USERSPACE;
185 error = kern_readv(td, uap->fd, &auio);
190 * Positioned read system call
192 #ifndef _SYS_SYSPROTO_H_
204 struct pread_args *uap;
210 if (uap->nbyte > IOSIZE_MAX)
212 aiov.iov_base = uap->buf;
213 aiov.iov_len = uap->nbyte;
214 auio.uio_iov = &aiov;
216 auio.uio_resid = uap->nbyte;
217 auio.uio_segflg = UIO_USERSPACE;
218 error = kern_preadv(td, uap->fd, &auio, uap->offset);
223 freebsd6_pread(td, uap)
225 struct freebsd6_pread_args *uap;
227 struct pread_args oargs;
230 oargs.buf = uap->buf;
231 oargs.nbyte = uap->nbyte;
232 oargs.offset = uap->offset;
233 return (sys_pread(td, &oargs));
237 * Scatter read system call.
239 #ifndef _SYS_SYSPROTO_H_
247 sys_readv(struct thread *td, struct readv_args *uap)
252 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
255 error = kern_readv(td, uap->fd, auio);
261 kern_readv(struct thread *td, int fd, struct uio *auio)
267 error = fget_read(td, fd, cap_rights_init(&rights, CAP_READ), &fp);
270 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
276 * Scatter positioned read system call.
278 #ifndef _SYS_SYSPROTO_H_
287 sys_preadv(struct thread *td, struct preadv_args *uap)
292 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
295 error = kern_preadv(td, uap->fd, auio, uap->offset);
301 kern_preadv(td, fd, auio, offset)
311 error = fget_read(td, fd, cap_rights_init(&rights, CAP_PREAD), &fp);
314 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
316 else if (offset < 0 &&
317 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
320 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
326 * Common code for readv and preadv that reads data in
327 * from a file using the passed in uio, offset, and flags.
330 dofileread(td, fd, fp, auio, offset, flags)
341 struct uio *ktruio = NULL;
344 /* Finish zero length reads right here */
345 if (auio->uio_resid == 0) {
346 td->td_retval[0] = 0;
349 auio->uio_rw = UIO_READ;
350 auio->uio_offset = offset;
353 if (KTRPOINT(td, KTR_GENIO))
354 ktruio = cloneuio(auio);
356 cnt = auio->uio_resid;
357 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
358 if (auio->uio_resid != cnt && (error == ERESTART ||
359 error == EINTR || error == EWOULDBLOCK))
362 cnt -= auio->uio_resid;
364 if (ktruio != NULL) {
365 ktruio->uio_resid = cnt;
366 ktrgenio(fd, UIO_READ, ktruio, error);
369 td->td_retval[0] = cnt;
373 #ifndef _SYS_SYSPROTO_H_
383 struct write_args *uap;
389 if (uap->nbyte > IOSIZE_MAX)
391 aiov.iov_base = (void *)(uintptr_t)uap->buf;
392 aiov.iov_len = uap->nbyte;
393 auio.uio_iov = &aiov;
395 auio.uio_resid = uap->nbyte;
396 auio.uio_segflg = UIO_USERSPACE;
397 error = kern_writev(td, uap->fd, &auio);
402 * Positioned write system call.
404 #ifndef _SYS_SYSPROTO_H_
416 struct pwrite_args *uap;
422 if (uap->nbyte > IOSIZE_MAX)
424 aiov.iov_base = (void *)(uintptr_t)uap->buf;
425 aiov.iov_len = uap->nbyte;
426 auio.uio_iov = &aiov;
428 auio.uio_resid = uap->nbyte;
429 auio.uio_segflg = UIO_USERSPACE;
430 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
435 freebsd6_pwrite(td, uap)
437 struct freebsd6_pwrite_args *uap;
439 struct pwrite_args oargs;
442 oargs.buf = uap->buf;
443 oargs.nbyte = uap->nbyte;
444 oargs.offset = uap->offset;
445 return (sys_pwrite(td, &oargs));
449 * Gather write system call.
451 #ifndef _SYS_SYSPROTO_H_
459 sys_writev(struct thread *td, struct writev_args *uap)
464 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
467 error = kern_writev(td, uap->fd, auio);
473 kern_writev(struct thread *td, int fd, struct uio *auio)
479 error = fget_write(td, fd, cap_rights_init(&rights, CAP_WRITE), &fp);
482 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
488 * Gather positioned write system call.
490 #ifndef _SYS_SYSPROTO_H_
491 struct pwritev_args {
499 sys_pwritev(struct thread *td, struct pwritev_args *uap)
504 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
507 error = kern_pwritev(td, uap->fd, auio, uap->offset);
513 kern_pwritev(td, fd, auio, offset)
523 error = fget_write(td, fd, cap_rights_init(&rights, CAP_PWRITE), &fp);
526 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
528 else if (offset < 0 &&
529 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
532 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
538 * Common code for writev and pwritev that writes data to
539 * a file using the passed in uio, offset, and flags.
542 dofilewrite(td, fd, fp, auio, offset, flags)
553 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(td, fd, length)
608 error = fget(td, fd, cap_rights_init(&rights, CAP_FTRUNCATE), &fp);
611 AUDIT_ARG_FILE(td->td_proc, fp);
612 if (!(fp->f_flag & FWRITE)) {
616 error = fo_truncate(fp, length, td->td_ucred, td);
621 #ifndef _SYS_SYSPROTO_H_
622 struct ftruncate_args {
629 sys_ftruncate(td, uap)
631 struct ftruncate_args *uap;
634 return (kern_ftruncate(td, uap->fd, uap->length));
637 #if defined(COMPAT_43)
638 #ifndef _SYS_SYSPROTO_H_
639 struct oftruncate_args {
647 struct oftruncate_args *uap;
650 return (kern_ftruncate(td, uap->fd, uap->length));
652 #endif /* COMPAT_43 */
654 #ifndef _SYS_SYSPROTO_H_
663 sys_ioctl(struct thread *td, struct ioctl_args *uap)
665 u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
671 if (uap->com > 0xffffffff) {
673 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
674 td->td_proc->p_pid, td->td_name, uap->com);
675 uap->com &= 0xffffffff;
680 * Interpret high order word to find amount of data to be
681 * copied to/from the user's address space.
683 size = IOCPARM_LEN(com);
684 if ((size > IOCPARM_MAX) ||
685 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
686 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
687 ((com & IOC_OUT) && size == 0) ||
689 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
691 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
695 if (com & IOC_VOID) {
696 /* Integer argument. */
697 arg = (intptr_t)uap->data;
701 if (size > SYS_IOCTL_SMALL_SIZE)
702 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
707 data = (void *)&uap->data;
709 error = copyin(uap->data, data, (u_int)size);
712 } else if (com & IOC_OUT) {
714 * Zero the buffer so the user always
715 * gets back something deterministic.
720 error = kern_ioctl(td, uap->fd, com, data);
722 if (error == 0 && (com & IOC_OUT))
723 error = copyout(data, uap->data, (u_int)size);
726 if (size > SYS_IOCTL_SMALL_SIZE)
727 free(data, M_IOCTLOPS);
732 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
735 struct filedesc *fdp;
739 int error, tmp, locked;
744 fdp = td->td_proc->p_fd;
757 locked = LA_UNLOCKED;
763 if ((fp = fget_locked(fdp, fd)) == NULL) {
767 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
768 fp = NULL; /* fhold() was not called yet */
772 if (locked == LA_SLOCKED) {
773 FILEDESC_SUNLOCK(fdp);
774 locked = LA_UNLOCKED;
777 error = fget(td, fd, cap_rights_init(&rights, CAP_IOCTL), &fp);
783 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
790 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
793 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
796 if ((tmp = *(int *)data))
797 atomic_set_int(&fp->f_flag, FNONBLOCK);
799 atomic_clear_int(&fp->f_flag, FNONBLOCK);
803 if ((tmp = *(int *)data))
804 atomic_set_int(&fp->f_flag, FASYNC);
806 atomic_clear_int(&fp->f_flag, FASYNC);
811 error = fo_ioctl(fp, com, data, td->td_ucred, td);
815 FILEDESC_XUNLOCK(fdp);
819 FILEDESC_SUNLOCK(fdp);
823 FILEDESC_UNLOCK_ASSERT(fdp);
832 poll_no_poll(int events)
835 * Return true for read/write. If the user asked for something
836 * special, return POLLNVAL, so that clients have a way of
837 * determining reliably whether or not the extended
838 * functionality is present without hard-coding knowledge
839 * of specific filesystem implementations.
841 if (events & ~POLLSTANDARD)
844 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
848 sys_pselect(struct thread *td, struct pselect_args *uap)
851 struct timeval tv, *tvp;
855 if (uap->ts != NULL) {
856 error = copyin(uap->ts, &ts, sizeof(ts));
859 TIMESPEC_TO_TIMEVAL(&tv, &ts);
863 if (uap->sm != NULL) {
864 error = copyin(uap->sm, &set, sizeof(set));
870 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
875 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
876 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
881 error = kern_sigprocmask(td, SIG_SETMASK, uset,
882 &td->td_oldsigmask, 0);
885 td->td_pflags |= TDP_OLDMASK;
887 * Make sure that ast() is called on return to
888 * usermode and TDP_OLDMASK is cleared, restoring old
892 td->td_flags |= TDF_ASTPENDING;
895 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
899 #ifndef _SYS_SYSPROTO_H_
902 fd_set *in, *ou, *ex;
907 sys_select(struct thread *td, struct select_args *uap)
909 struct timeval tv, *tvp;
912 if (uap->tv != NULL) {
913 error = copyin(uap->tv, &tv, sizeof(tv));
920 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
925 * In the unlikely case when user specified n greater then the last
926 * open file descriptor, check that no bits are set after the last
927 * valid fd. We must return EBADF if any is set.
929 * There are applications that rely on the behaviour.
931 * nd is fd_lastfile + 1.
934 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
940 if (nd >= ndu || fd_in == NULL)
944 bits = 0; /* silence gcc */
945 for (i = nd; i < ndu; i++) {
947 #if BYTE_ORDER == LITTLE_ENDIAN
948 addr = (char *)fd_in + b;
950 addr = (char *)fd_in;
951 if (abi_nfdbits == NFDBITS) {
952 addr += rounddown(b, sizeof(fd_mask)) +
953 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
955 addr += rounddown(b, sizeof(uint32_t)) +
956 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
966 if ((bits & (1 << (i % NBBY))) != 0)
973 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
974 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
976 struct filedesc *fdp;
978 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
979 * infds with the new FD_SETSIZE of 1024, and more than enough for
980 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
983 fd_mask s_selbits[howmany(2048, NFDBITS)];
984 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
986 sbintime_t asbt, precision, rsbt;
987 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
992 fdp = td->td_proc->p_fd;
994 lf = fdp->fd_lastfile;
998 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1001 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1004 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1009 * Allocate just enough bits for the non-null fd_sets. Use the
1010 * preallocated auto buffer if possible.
1012 nfdbits = roundup(nd, NFDBITS);
1013 ncpbytes = nfdbits / NBBY;
1014 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1017 nbufbytes += 2 * ncpbytes;
1019 nbufbytes += 2 * ncpbytes;
1021 nbufbytes += 2 * ncpbytes;
1022 if (nbufbytes <= sizeof s_selbits)
1023 selbits = &s_selbits[0];
1025 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1028 * Assign pointers into the bit buffers and fetch the input bits.
1029 * Put the output buffers together so that they can be bzeroed
1033 #define getbits(name, x) \
1035 if (name == NULL) { \
1039 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1041 sbp += ncpbytes / sizeof *sbp; \
1042 error = copyin(name, ibits[x], ncpubytes); \
1045 bzero((char *)ibits[x] + ncpubytes, \
1046 ncpbytes - ncpubytes); \
1054 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1056 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1057 * we are running under 32-bit emulation. This should be more
1060 #define swizzle_fdset(bits) \
1061 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1063 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1064 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1067 #define swizzle_fdset(bits)
1070 /* Make sure the bit order makes it through an ABI transition */
1071 swizzle_fdset(ibits[0]);
1072 swizzle_fdset(ibits[1]);
1073 swizzle_fdset(ibits[2]);
1076 bzero(selbits, nbufbytes / 2);
1081 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1082 rtv.tv_usec >= 1000000) {
1086 if (!timevalisset(&rtv))
1088 else if (rtv.tv_sec <= INT32_MAX) {
1089 rsbt = tvtosbt(rtv);
1091 precision >>= tc_precexp;
1092 if (TIMESEL(&asbt, rsbt))
1093 asbt += tc_tick_sbt;
1094 if (asbt <= SBT_MAX - rsbt)
1103 /* Iterate until the timeout expires or descriptors become ready. */
1105 error = selscan(td, ibits, obits, nd);
1106 if (error || td->td_retval[0] != 0)
1108 error = seltdwait(td, asbt, precision);
1111 error = selrescan(td, ibits, obits);
1112 if (error || td->td_retval[0] != 0)
1118 /* select is not restarted after signals... */
1119 if (error == ERESTART)
1121 if (error == EWOULDBLOCK)
1124 /* swizzle bit order back, if necessary */
1125 swizzle_fdset(obits[0]);
1126 swizzle_fdset(obits[1]);
1127 swizzle_fdset(obits[2]);
1128 #undef swizzle_fdset
1130 #define putbits(name, x) \
1131 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1141 if (selbits != &s_selbits[0])
1142 free(selbits, M_SELECT);
1147 * Convert a select bit set to poll flags.
1149 * The backend always returns POLLHUP/POLLERR if appropriate and we
1150 * return this as a set bit in any set.
1152 static int select_flags[3] = {
1153 POLLRDNORM | POLLHUP | POLLERR,
1154 POLLWRNORM | POLLHUP | POLLERR,
1155 POLLRDBAND | POLLERR
1159 * Compute the fo_poll flags required for a fd given by the index and
1160 * bit position in the fd_mask array.
1163 selflags(fd_mask **ibits, int idx, fd_mask bit)
1169 for (msk = 0; msk < 3; msk++) {
1170 if (ibits[msk] == NULL)
1172 if ((ibits[msk][idx] & bit) == 0)
1174 flags |= select_flags[msk];
1180 * Set the appropriate output bits given a mask of fired events and the
1181 * input bits originally requested.
1184 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1190 for (msk = 0; msk < 3; msk++) {
1191 if ((events & select_flags[msk]) == 0)
1193 if (ibits[msk] == NULL)
1195 if ((ibits[msk][idx] & bit) == 0)
1198 * XXX Check for a duplicate set. This can occur because a
1199 * socket calls selrecord() twice for each poll() call
1200 * resulting in two selfds per real fd. selrescan() will
1201 * call selsetbits twice as a result.
1203 if ((obits[msk][idx] & bit) != 0)
1205 obits[msk][idx] |= bit;
1213 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1215 cap_rights_t rights;
1217 cap_rights_init(&rights, CAP_EVENT);
1219 return (fget_unlocked(fdp, fd, &rights, 0, fpp, NULL));
1223 * Traverse the list of fds attached to this thread's seltd and check for
1227 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1229 struct filedesc *fdp;
1239 fdp = td->td_proc->p_fd;
1242 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1243 fd = (int)(uintptr_t)sfp->sf_cookie;
1245 selfdfree(stp, sfp);
1246 /* If the selinfo wasn't cleared the event didn't fire. */
1249 error = getselfd_cap(fdp, fd, &fp);
1253 bit = (fd_mask)1 << (fd % NFDBITS);
1254 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1257 n += selsetbits(ibits, obits, idx, bit, ev);
1260 td->td_retval[0] = n;
1265 * Perform the initial filedescriptor scan and register ourselves with
1269 selscan(td, ibits, obits, nfd)
1271 fd_mask **ibits, **obits;
1274 struct filedesc *fdp;
1277 int ev, flags, end, fd;
1281 fdp = td->td_proc->p_fd;
1283 for (idx = 0, fd = 0; fd < nfd; idx++) {
1284 end = imin(fd + NFDBITS, nfd);
1285 for (bit = 1; fd < end; bit <<= 1, fd++) {
1286 /* Compute the list of events we're interested in. */
1287 flags = selflags(ibits, idx, bit);
1290 error = getselfd_cap(fdp, fd, &fp);
1293 selfdalloc(td, (void *)(uintptr_t)fd);
1294 ev = fo_poll(fp, flags, td->td_ucred, td);
1297 n += selsetbits(ibits, obits, idx, bit, ev);
1301 td->td_retval[0] = n;
1306 sys_poll(struct thread *td, struct poll_args *uap)
1308 struct timespec ts, *tsp;
1310 if (uap->timeout != INFTIM) {
1311 if (uap->timeout < 0)
1313 ts.tv_sec = uap->timeout / 1000;
1314 ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1319 return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1323 kern_poll(struct thread *td, struct pollfd *fds, u_int nfds,
1324 struct timespec *tsp, sigset_t *uset)
1326 struct pollfd *bits;
1327 struct pollfd smallbits[32];
1328 sbintime_t sbt, precision, tmp;
1336 if (tsp->tv_sec < 0)
1338 if (tsp->tv_nsec < 0 || tsp->tv_nsec >= 1000000000)
1340 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1344 if (ts.tv_sec > INT32_MAX / 2) {
1345 over = ts.tv_sec - INT32_MAX / 2;
1351 precision >>= tc_precexp;
1352 if (TIMESEL(&sbt, tmp))
1359 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1361 ni = nfds * sizeof(struct pollfd);
1362 if (ni > sizeof(smallbits))
1363 bits = malloc(ni, M_TEMP, M_WAITOK);
1366 error = copyin(fds, bits, ni);
1371 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1372 &td->td_oldsigmask, 0);
1375 td->td_pflags |= TDP_OLDMASK;
1377 * Make sure that ast() is called on return to
1378 * usermode and TDP_OLDMASK is cleared, restoring old
1382 td->td_flags |= TDF_ASTPENDING;
1387 /* Iterate until the timeout expires or descriptors become ready. */
1389 error = pollscan(td, bits, nfds);
1390 if (error || td->td_retval[0] != 0)
1392 error = seltdwait(td, sbt, precision);
1395 error = pollrescan(td);
1396 if (error || td->td_retval[0] != 0)
1402 /* poll is not restarted after signals... */
1403 if (error == ERESTART)
1405 if (error == EWOULDBLOCK)
1408 error = pollout(td, bits, fds, nfds);
1413 if (ni > sizeof(smallbits))
1419 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1421 struct timespec ts, *tsp;
1425 if (uap->ts != NULL) {
1426 error = copyin(uap->ts, &ts, sizeof(ts));
1432 if (uap->set != NULL) {
1433 error = copyin(uap->set, &set, sizeof(set));
1440 * fds is still a pointer to user space. kern_poll() will
1441 * take care of copyin that array to the kernel space.
1444 return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1448 pollrescan(struct thread *td)
1454 struct filedesc *fdp;
1458 cap_rights_t rights;
1463 fdp = td->td_proc->p_fd;
1465 FILEDESC_SLOCK(fdp);
1466 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1467 fd = (struct pollfd *)sfp->sf_cookie;
1469 selfdfree(stp, sfp);
1470 /* If the selinfo wasn't cleared the event didn't fire. */
1473 fp = fdp->fd_ofiles[fd->fd].fde_file;
1476 cap_check(cap_rights(fdp, fd->fd),
1477 cap_rights_init(&rights, CAP_EVENT)) != 0)
1482 fd->revents = POLLNVAL;
1488 * Note: backend also returns POLLHUP and
1489 * POLLERR if appropriate.
1491 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1492 if (fd->revents != 0)
1495 FILEDESC_SUNLOCK(fdp);
1497 td->td_retval[0] = n;
1503 pollout(td, fds, ufds, nfd)
1506 struct pollfd *ufds;
1513 for (i = 0; i < nfd; i++) {
1514 error = copyout(&fds->revents, &ufds->revents,
1515 sizeof(ufds->revents));
1518 if (fds->revents != 0)
1523 td->td_retval[0] = n;
1528 pollscan(td, fds, nfd)
1533 struct filedesc *fdp = td->td_proc->p_fd;
1536 cap_rights_t rights;
1540 FILEDESC_SLOCK(fdp);
1541 for (i = 0; i < nfd; i++, fds++) {
1542 if (fds->fd > fdp->fd_lastfile) {
1543 fds->revents = POLLNVAL;
1545 } else if (fds->fd < 0) {
1548 fp = fdp->fd_ofiles[fds->fd].fde_file;
1551 cap_check(cap_rights(fdp, fds->fd),
1552 cap_rights_init(&rights, CAP_EVENT)) != 0)
1557 fds->revents = POLLNVAL;
1561 * Note: backend also returns POLLHUP and
1562 * POLLERR if appropriate.
1564 selfdalloc(td, fds);
1565 fds->revents = fo_poll(fp, fds->events,
1568 * POSIX requires POLLOUT to be never
1569 * set simultaneously with POLLHUP.
1571 if ((fds->revents & POLLHUP) != 0)
1572 fds->revents &= ~POLLOUT;
1574 if (fds->revents != 0)
1579 FILEDESC_SUNLOCK(fdp);
1580 td->td_retval[0] = n;
1585 * OpenBSD poll system call.
1587 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1589 #ifndef _SYS_SYSPROTO_H_
1590 struct openbsd_poll_args {
1597 sys_openbsd_poll(td, uap)
1598 register struct thread *td;
1599 register struct openbsd_poll_args *uap;
1601 return (sys_poll(td, (struct poll_args *)uap));
1605 * XXX This was created specifically to support netncp and netsmb. This
1606 * allows the caller to specify a socket to wait for events on. It returns
1607 * 0 if any events matched and an error otherwise. There is no way to
1608 * determine which events fired.
1611 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1614 sbintime_t asbt, precision, rsbt;
1617 precision = 0; /* stupid gcc! */
1620 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1621 rtv.tv_usec >= 1000000)
1623 if (!timevalisset(&rtv))
1625 else if (rtv.tv_sec <= INT32_MAX) {
1626 rsbt = tvtosbt(rtv);
1628 precision >>= tc_precexp;
1629 if (TIMESEL(&asbt, rsbt))
1630 asbt += tc_tick_sbt;
1631 if (asbt <= SBT_MAX - rsbt)
1641 * Iterate until the timeout expires or the socket becomes ready.
1644 selfdalloc(td, NULL);
1645 error = sopoll(so, events, NULL, td);
1646 /* error here is actually the ready events. */
1649 error = seltdwait(td, asbt, precision);
1654 /* XXX Duplicates ncp/smb behavior. */
1655 if (error == ERESTART)
1661 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1662 * have two select sets, one for read and another for write.
1665 selfdalloc(struct thread *td, void *cookie)
1670 if (stp->st_free1 == NULL)
1671 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1672 stp->st_free1->sf_td = stp;
1673 stp->st_free1->sf_cookie = cookie;
1674 if (stp->st_free2 == NULL)
1675 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1676 stp->st_free2->sf_td = stp;
1677 stp->st_free2->sf_cookie = cookie;
1681 selfdfree(struct seltd *stp, struct selfd *sfp)
1683 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1684 mtx_lock(sfp->sf_mtx);
1686 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1687 mtx_unlock(sfp->sf_mtx);
1688 uma_zfree(selfd_zone, sfp);
1691 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1694 struct selinfo *sip;
1698 * This feature is already provided by doselwakeup(), thus it is
1699 * enough to go for it.
1700 * Eventually, the context, should take care to avoid races
1701 * between thread calling select()/poll() and file descriptor
1702 * detaching, but, again, the races are just the same as
1705 doselwakeup(sip, -1);
1709 * Record a select request.
1712 selrecord(selector, sip)
1713 struct thread *selector;
1714 struct selinfo *sip;
1720 stp = selector->td_sel;
1722 * Don't record when doing a rescan.
1724 if (stp->st_flags & SELTD_RESCAN)
1727 * Grab one of the preallocated descriptors.
1730 if ((sfp = stp->st_free1) != NULL)
1731 stp->st_free1 = NULL;
1732 else if ((sfp = stp->st_free2) != NULL)
1733 stp->st_free2 = NULL;
1735 panic("selrecord: No free selfd on selq");
1738 mtxp = mtx_pool_find(mtxpool_select, sip);
1740 * Initialize the sfp and queue it in the thread.
1744 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1746 * Now that we've locked the sip, check for initialization.
1749 if (sip->si_mtx == NULL) {
1751 TAILQ_INIT(&sip->si_tdlist);
1754 * Add this thread to the list of selfds listening on this selinfo.
1756 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1757 mtx_unlock(sip->si_mtx);
1760 /* Wake up a selecting thread. */
1763 struct selinfo *sip;
1765 doselwakeup(sip, -1);
1768 /* Wake up a selecting thread, and set its priority. */
1770 selwakeuppri(sip, pri)
1771 struct selinfo *sip;
1774 doselwakeup(sip, pri);
1778 * Do a wakeup when a selectable event occurs.
1781 doselwakeup(sip, pri)
1782 struct selinfo *sip;
1789 /* If it's not initialized there can't be any waiters. */
1790 if (sip->si_mtx == NULL)
1793 * Locking the selinfo locks all selfds associated with it.
1795 mtx_lock(sip->si_mtx);
1796 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1798 * Once we remove this sfp from the list and clear the
1799 * sf_si seltdclear will know to ignore this si.
1801 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1804 mtx_lock(&stp->st_mtx);
1805 stp->st_flags |= SELTD_PENDING;
1806 cv_broadcastpri(&stp->st_wait, pri);
1807 mtx_unlock(&stp->st_mtx);
1809 mtx_unlock(sip->si_mtx);
1813 seltdinit(struct thread *td)
1817 if ((stp = td->td_sel) != NULL)
1819 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1820 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1821 cv_init(&stp->st_wait, "select");
1824 STAILQ_INIT(&stp->st_selq);
1828 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1835 * An event of interest may occur while we do not hold the seltd
1836 * locked so check the pending flag before we sleep.
1838 mtx_lock(&stp->st_mtx);
1840 * Any further calls to selrecord will be a rescan.
1842 stp->st_flags |= SELTD_RESCAN;
1843 if (stp->st_flags & SELTD_PENDING) {
1844 mtx_unlock(&stp->st_mtx);
1848 error = EWOULDBLOCK;
1850 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1851 sbt, precision, C_ABSOLUTE);
1853 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1854 mtx_unlock(&stp->st_mtx);
1860 seltdfini(struct thread *td)
1868 uma_zfree(selfd_zone, stp->st_free1);
1870 uma_zfree(selfd_zone, stp->st_free2);
1872 free(stp, M_SELECT);
1876 * Remove the references to the thread from all of the objects we were
1880 seltdclear(struct thread *td)
1887 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1888 selfdfree(stp, sfp);
1892 static void selectinit(void *);
1893 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1895 selectinit(void *dummy __unused)
1898 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1899 NULL, NULL, UMA_ALIGN_PTR, 0);
1900 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);