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 = 0;
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. */
159 static uma_zone_t selfd_zone;
160 static struct mtx_pool *mtxpool_select;
162 #ifndef _SYS_SYSPROTO_H_
172 struct read_args *uap;
178 if (uap->nbyte > IOSIZE_MAX)
180 aiov.iov_base = uap->buf;
181 aiov.iov_len = uap->nbyte;
182 auio.uio_iov = &aiov;
184 auio.uio_resid = uap->nbyte;
185 auio.uio_segflg = UIO_USERSPACE;
186 error = kern_readv(td, uap->fd, &auio);
191 * Positioned read system call
193 #ifndef _SYS_SYSPROTO_H_
205 struct pread_args *uap;
211 if (uap->nbyte > IOSIZE_MAX)
213 aiov.iov_base = uap->buf;
214 aiov.iov_len = uap->nbyte;
215 auio.uio_iov = &aiov;
217 auio.uio_resid = uap->nbyte;
218 auio.uio_segflg = UIO_USERSPACE;
219 error = kern_preadv(td, uap->fd, &auio, uap->offset);
223 #if defined(COMPAT_FREEBSD6)
225 freebsd6_pread(td, uap)
227 struct freebsd6_pread_args *uap;
229 struct pread_args oargs;
232 oargs.buf = uap->buf;
233 oargs.nbyte = uap->nbyte;
234 oargs.offset = uap->offset;
235 return (sys_pread(td, &oargs));
240 * Scatter read system call.
242 #ifndef _SYS_SYSPROTO_H_
250 sys_readv(struct thread *td, struct readv_args *uap)
255 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
258 error = kern_readv(td, uap->fd, auio);
264 kern_readv(struct thread *td, int fd, struct uio *auio)
270 error = fget_read(td, fd, cap_rights_init(&rights, CAP_READ), &fp);
273 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
279 * Scatter positioned read system call.
281 #ifndef _SYS_SYSPROTO_H_
290 sys_preadv(struct thread *td, struct preadv_args *uap)
295 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
298 error = kern_preadv(td, uap->fd, auio, uap->offset);
304 kern_preadv(td, fd, auio, offset)
314 error = fget_read(td, fd, cap_rights_init(&rights, CAP_PREAD), &fp);
317 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
319 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
322 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
328 * Common code for readv and preadv that reads data in
329 * from a file using the passed in uio, offset, and flags.
332 dofileread(td, fd, fp, auio, offset, flags)
343 struct uio *ktruio = NULL;
346 /* Finish zero length reads right here */
347 if (auio->uio_resid == 0) {
348 td->td_retval[0] = 0;
351 auio->uio_rw = UIO_READ;
352 auio->uio_offset = offset;
355 if (KTRPOINT(td, KTR_GENIO))
356 ktruio = cloneuio(auio);
358 cnt = auio->uio_resid;
359 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
360 if (auio->uio_resid != cnt && (error == ERESTART ||
361 error == EINTR || error == EWOULDBLOCK))
364 cnt -= auio->uio_resid;
366 if (ktruio != NULL) {
367 ktruio->uio_resid = cnt;
368 ktrgenio(fd, UIO_READ, ktruio, error);
371 td->td_retval[0] = cnt;
375 #ifndef _SYS_SYSPROTO_H_
385 struct write_args *uap;
391 if (uap->nbyte > IOSIZE_MAX)
393 aiov.iov_base = (void *)(uintptr_t)uap->buf;
394 aiov.iov_len = uap->nbyte;
395 auio.uio_iov = &aiov;
397 auio.uio_resid = uap->nbyte;
398 auio.uio_segflg = UIO_USERSPACE;
399 error = kern_writev(td, uap->fd, &auio);
404 * Positioned write system call.
406 #ifndef _SYS_SYSPROTO_H_
418 struct pwrite_args *uap;
424 if (uap->nbyte > IOSIZE_MAX)
426 aiov.iov_base = (void *)(uintptr_t)uap->buf;
427 aiov.iov_len = uap->nbyte;
428 auio.uio_iov = &aiov;
430 auio.uio_resid = uap->nbyte;
431 auio.uio_segflg = UIO_USERSPACE;
432 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
436 #if defined(COMPAT_FREEBSD6)
438 freebsd6_pwrite(td, uap)
440 struct freebsd6_pwrite_args *uap;
442 struct pwrite_args oargs;
445 oargs.buf = uap->buf;
446 oargs.nbyte = uap->nbyte;
447 oargs.offset = uap->offset;
448 return (sys_pwrite(td, &oargs));
453 * Gather write system call.
455 #ifndef _SYS_SYSPROTO_H_
463 sys_writev(struct thread *td, struct writev_args *uap)
468 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
471 error = kern_writev(td, uap->fd, auio);
477 kern_writev(struct thread *td, int fd, struct uio *auio)
483 error = fget_write(td, fd, cap_rights_init(&rights, CAP_WRITE), &fp);
486 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
492 * Gather positioned write system call.
494 #ifndef _SYS_SYSPROTO_H_
495 struct pwritev_args {
503 sys_pwritev(struct thread *td, struct pwritev_args *uap)
508 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
511 error = kern_pwritev(td, uap->fd, auio, uap->offset);
517 kern_pwritev(td, fd, auio, offset)
527 error = fget_write(td, fd, cap_rights_init(&rights, CAP_PWRITE), &fp);
530 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
532 else if (offset < 0 && 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(td, fd, fp, auio, offset, flags)
556 struct uio *ktruio = NULL;
559 auio->uio_rw = UIO_WRITE;
561 auio->uio_offset = offset;
563 if (KTRPOINT(td, KTR_GENIO))
564 ktruio = cloneuio(auio);
566 cnt = auio->uio_resid;
567 if (fp->f_type == DTYPE_VNODE &&
568 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
570 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
571 if (auio->uio_resid != cnt && (error == ERESTART ||
572 error == EINTR || error == EWOULDBLOCK))
574 /* Socket layer is responsible for issuing SIGPIPE. */
575 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
576 PROC_LOCK(td->td_proc);
577 tdsignal(td, SIGPIPE);
578 PROC_UNLOCK(td->td_proc);
581 cnt -= auio->uio_resid;
583 if (ktruio != NULL) {
584 ktruio->uio_resid = cnt;
585 ktrgenio(fd, UIO_WRITE, ktruio, error);
588 td->td_retval[0] = cnt;
593 * Truncate a file given a file descriptor.
595 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
596 * descriptor isn't writable.
599 kern_ftruncate(td, fd, length)
611 error = fget(td, fd, cap_rights_init(&rights, CAP_FTRUNCATE), &fp);
614 AUDIT_ARG_FILE(td->td_proc, fp);
615 if (!(fp->f_flag & FWRITE)) {
619 error = fo_truncate(fp, length, td->td_ucred, td);
624 #ifndef _SYS_SYSPROTO_H_
625 struct ftruncate_args {
632 sys_ftruncate(td, uap)
634 struct ftruncate_args *uap;
637 return (kern_ftruncate(td, uap->fd, uap->length));
640 #if defined(COMPAT_43)
641 #ifndef _SYS_SYSPROTO_H_
642 struct oftruncate_args {
650 struct oftruncate_args *uap;
653 return (kern_ftruncate(td, uap->fd, uap->length));
655 #endif /* COMPAT_43 */
657 #ifndef _SYS_SYSPROTO_H_
666 sys_ioctl(struct thread *td, struct ioctl_args *uap)
668 u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
674 if (uap->com > 0xffffffff) {
676 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
677 td->td_proc->p_pid, td->td_name, uap->com);
678 uap->com &= 0xffffffff;
683 * Interpret high order word to find amount of data to be
684 * copied to/from the user's address space.
686 size = IOCPARM_LEN(com);
687 if ((size > IOCPARM_MAX) ||
688 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
689 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
690 ((com & IOC_OUT) && size == 0) ||
692 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
694 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
698 if (com & IOC_VOID) {
699 /* Integer argument. */
700 arg = (intptr_t)uap->data;
704 if (size > SYS_IOCTL_SMALL_SIZE)
705 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
710 data = (void *)&uap->data;
712 error = copyin(uap->data, data, (u_int)size);
715 } else if (com & IOC_OUT) {
717 * Zero the buffer so the user always
718 * gets back something deterministic.
723 error = kern_ioctl(td, uap->fd, com, data);
725 if (error == 0 && (com & IOC_OUT))
726 error = copyout(data, uap->data, (u_int)size);
729 if (size > SYS_IOCTL_SMALL_SIZE)
730 free(data, M_IOCTLOPS);
735 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
738 struct filedesc *fdp;
742 int error, tmp, locked;
747 fdp = td->td_proc->p_fd;
760 locked = LA_UNLOCKED;
766 if ((fp = fget_locked(fdp, fd)) == NULL) {
770 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
771 fp = NULL; /* fhold() was not called yet */
775 if (locked == LA_SLOCKED) {
776 FILEDESC_SUNLOCK(fdp);
777 locked = LA_UNLOCKED;
780 error = fget(td, fd, cap_rights_init(&rights, CAP_IOCTL), &fp);
786 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
793 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
796 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
799 if ((tmp = *(int *)data))
800 atomic_set_int(&fp->f_flag, FNONBLOCK);
802 atomic_clear_int(&fp->f_flag, FNONBLOCK);
806 if ((tmp = *(int *)data))
807 atomic_set_int(&fp->f_flag, FASYNC);
809 atomic_clear_int(&fp->f_flag, FASYNC);
814 error = fo_ioctl(fp, com, data, td->td_ucred, td);
818 FILEDESC_XUNLOCK(fdp);
822 FILEDESC_SUNLOCK(fdp);
826 FILEDESC_UNLOCK_ASSERT(fdp);
835 poll_no_poll(int events)
838 * Return true for read/write. If the user asked for something
839 * special, return POLLNVAL, so that clients have a way of
840 * determining reliably whether or not the extended
841 * functionality is present without hard-coding knowledge
842 * of specific filesystem implementations.
844 if (events & ~POLLSTANDARD)
847 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
851 sys_pselect(struct thread *td, struct pselect_args *uap)
854 struct timeval tv, *tvp;
858 if (uap->ts != NULL) {
859 error = copyin(uap->ts, &ts, sizeof(ts));
862 TIMESPEC_TO_TIMEVAL(&tv, &ts);
866 if (uap->sm != NULL) {
867 error = copyin(uap->sm, &set, sizeof(set));
873 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
878 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
879 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
884 error = kern_sigprocmask(td, SIG_SETMASK, uset,
885 &td->td_oldsigmask, 0);
888 td->td_pflags |= TDP_OLDMASK;
890 * Make sure that ast() is called on return to
891 * usermode and TDP_OLDMASK is cleared, restoring old
895 td->td_flags |= TDF_ASTPENDING;
898 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
902 #ifndef _SYS_SYSPROTO_H_
905 fd_set *in, *ou, *ex;
910 sys_select(struct thread *td, struct select_args *uap)
912 struct timeval tv, *tvp;
915 if (uap->tv != NULL) {
916 error = copyin(uap->tv, &tv, sizeof(tv));
923 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
928 * In the unlikely case when user specified n greater then the last
929 * open file descriptor, check that no bits are set after the last
930 * valid fd. We must return EBADF if any is set.
932 * There are applications that rely on the behaviour.
934 * nd is fd_lastfile + 1.
937 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
943 if (nd >= ndu || fd_in == NULL)
947 bits = 0; /* silence gcc */
948 for (i = nd; i < ndu; i++) {
950 #if BYTE_ORDER == LITTLE_ENDIAN
951 addr = (char *)fd_in + b;
953 addr = (char *)fd_in;
954 if (abi_nfdbits == NFDBITS) {
955 addr += rounddown(b, sizeof(fd_mask)) +
956 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
958 addr += rounddown(b, sizeof(uint32_t)) +
959 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
969 if ((bits & (1 << (i % NBBY))) != 0)
976 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
977 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
979 struct filedesc *fdp;
981 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
982 * infds with the new FD_SETSIZE of 1024, and more than enough for
983 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
986 fd_mask s_selbits[howmany(2048, NFDBITS)];
987 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
989 sbintime_t asbt, precision, rsbt;
990 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
995 fdp = td->td_proc->p_fd;
997 lf = fdp->fd_lastfile;
1001 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1004 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1007 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1012 * Allocate just enough bits for the non-null fd_sets. Use the
1013 * preallocated auto buffer if possible.
1015 nfdbits = roundup(nd, NFDBITS);
1016 ncpbytes = nfdbits / NBBY;
1017 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1020 nbufbytes += 2 * ncpbytes;
1022 nbufbytes += 2 * ncpbytes;
1024 nbufbytes += 2 * ncpbytes;
1025 if (nbufbytes <= sizeof s_selbits)
1026 selbits = &s_selbits[0];
1028 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1031 * Assign pointers into the bit buffers and fetch the input bits.
1032 * Put the output buffers together so that they can be bzeroed
1036 #define getbits(name, x) \
1038 if (name == NULL) { \
1042 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1044 sbp += ncpbytes / sizeof *sbp; \
1045 error = copyin(name, ibits[x], ncpubytes); \
1048 bzero((char *)ibits[x] + ncpubytes, \
1049 ncpbytes - ncpubytes); \
1057 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1059 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1060 * we are running under 32-bit emulation. This should be more
1063 #define swizzle_fdset(bits) \
1064 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1066 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1067 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1070 #define swizzle_fdset(bits)
1073 /* Make sure the bit order makes it through an ABI transition */
1074 swizzle_fdset(ibits[0]);
1075 swizzle_fdset(ibits[1]);
1076 swizzle_fdset(ibits[2]);
1079 bzero(selbits, nbufbytes / 2);
1084 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1085 rtv.tv_usec >= 1000000) {
1089 if (!timevalisset(&rtv))
1091 else if (rtv.tv_sec <= INT32_MAX) {
1092 rsbt = tvtosbt(rtv);
1094 precision >>= tc_precexp;
1095 if (TIMESEL(&asbt, rsbt))
1096 asbt += tc_tick_sbt;
1097 if (asbt <= SBT_MAX - rsbt)
1106 /* Iterate until the timeout expires or descriptors become ready. */
1108 error = selscan(td, ibits, obits, nd);
1109 if (error || td->td_retval[0] != 0)
1111 error = seltdwait(td, asbt, precision);
1114 error = selrescan(td, ibits, obits);
1115 if (error || td->td_retval[0] != 0)
1121 /* select is not restarted after signals... */
1122 if (error == ERESTART)
1124 if (error == EWOULDBLOCK)
1127 /* swizzle bit order back, if necessary */
1128 swizzle_fdset(obits[0]);
1129 swizzle_fdset(obits[1]);
1130 swizzle_fdset(obits[2]);
1131 #undef swizzle_fdset
1133 #define putbits(name, x) \
1134 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1144 if (selbits != &s_selbits[0])
1145 free(selbits, M_SELECT);
1150 * Convert a select bit set to poll flags.
1152 * The backend always returns POLLHUP/POLLERR if appropriate and we
1153 * return this as a set bit in any set.
1155 static int select_flags[3] = {
1156 POLLRDNORM | POLLHUP | POLLERR,
1157 POLLWRNORM | POLLHUP | POLLERR,
1158 POLLRDBAND | POLLERR
1162 * Compute the fo_poll flags required for a fd given by the index and
1163 * bit position in the fd_mask array.
1166 selflags(fd_mask **ibits, int idx, fd_mask bit)
1172 for (msk = 0; msk < 3; msk++) {
1173 if (ibits[msk] == NULL)
1175 if ((ibits[msk][idx] & bit) == 0)
1177 flags |= select_flags[msk];
1183 * Set the appropriate output bits given a mask of fired events and the
1184 * input bits originally requested.
1187 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1193 for (msk = 0; msk < 3; msk++) {
1194 if ((events & select_flags[msk]) == 0)
1196 if (ibits[msk] == NULL)
1198 if ((ibits[msk][idx] & bit) == 0)
1201 * XXX Check for a duplicate set. This can occur because a
1202 * socket calls selrecord() twice for each poll() call
1203 * resulting in two selfds per real fd. selrescan() will
1204 * call selsetbits twice as a result.
1206 if ((obits[msk][idx] & bit) != 0)
1208 obits[msk][idx] |= bit;
1216 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1218 cap_rights_t rights;
1220 cap_rights_init(&rights, CAP_EVENT);
1222 return (fget_unlocked(fdp, fd, &rights, fpp, NULL));
1226 * Traverse the list of fds attached to this thread's seltd and check for
1230 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1232 struct filedesc *fdp;
1242 fdp = td->td_proc->p_fd;
1245 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1246 fd = (int)(uintptr_t)sfp->sf_cookie;
1248 selfdfree(stp, sfp);
1249 /* If the selinfo wasn't cleared the event didn't fire. */
1252 error = getselfd_cap(fdp, fd, &fp);
1256 bit = (fd_mask)1 << (fd % NFDBITS);
1257 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1260 n += selsetbits(ibits, obits, idx, bit, ev);
1263 td->td_retval[0] = n;
1268 * Perform the initial filedescriptor scan and register ourselves with
1272 selscan(td, ibits, obits, nfd)
1274 fd_mask **ibits, **obits;
1277 struct filedesc *fdp;
1280 int ev, flags, end, fd;
1284 fdp = td->td_proc->p_fd;
1286 for (idx = 0, fd = 0; fd < nfd; idx++) {
1287 end = imin(fd + NFDBITS, nfd);
1288 for (bit = 1; fd < end; bit <<= 1, fd++) {
1289 /* Compute the list of events we're interested in. */
1290 flags = selflags(ibits, idx, bit);
1293 error = getselfd_cap(fdp, fd, &fp);
1296 selfdalloc(td, (void *)(uintptr_t)fd);
1297 ev = fo_poll(fp, flags, td->td_ucred, td);
1300 n += selsetbits(ibits, obits, idx, bit, ev);
1304 td->td_retval[0] = n;
1309 sys_poll(struct thread *td, struct poll_args *uap)
1311 struct timespec ts, *tsp;
1313 if (uap->timeout != INFTIM) {
1314 if (uap->timeout < 0)
1316 ts.tv_sec = uap->timeout / 1000;
1317 ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1322 return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1326 kern_poll(struct thread *td, struct pollfd *fds, u_int nfds,
1327 struct timespec *tsp, sigset_t *uset)
1329 struct pollfd *bits;
1330 struct pollfd smallbits[32];
1331 sbintime_t sbt, precision, tmp;
1339 if (tsp->tv_sec < 0)
1341 if (tsp->tv_nsec < 0 || tsp->tv_nsec >= 1000000000)
1343 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1347 if (ts.tv_sec > INT32_MAX / 2) {
1348 over = ts.tv_sec - INT32_MAX / 2;
1354 precision >>= tc_precexp;
1355 if (TIMESEL(&sbt, tmp))
1362 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1364 ni = nfds * sizeof(struct pollfd);
1365 if (ni > sizeof(smallbits))
1366 bits = malloc(ni, M_TEMP, M_WAITOK);
1369 error = copyin(fds, bits, ni);
1374 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1375 &td->td_oldsigmask, 0);
1378 td->td_pflags |= TDP_OLDMASK;
1380 * Make sure that ast() is called on return to
1381 * usermode and TDP_OLDMASK is cleared, restoring old
1385 td->td_flags |= TDF_ASTPENDING;
1390 /* Iterate until the timeout expires or descriptors become ready. */
1392 error = pollscan(td, bits, nfds);
1393 if (error || td->td_retval[0] != 0)
1395 error = seltdwait(td, sbt, precision);
1398 error = pollrescan(td);
1399 if (error || td->td_retval[0] != 0)
1405 /* poll is not restarted after signals... */
1406 if (error == ERESTART)
1408 if (error == EWOULDBLOCK)
1411 error = pollout(td, bits, fds, nfds);
1416 if (ni > sizeof(smallbits))
1422 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1424 struct timespec ts, *tsp;
1428 if (uap->ts != NULL) {
1429 error = copyin(uap->ts, &ts, sizeof(ts));
1435 if (uap->set != NULL) {
1436 error = copyin(uap->set, &set, sizeof(set));
1443 * fds is still a pointer to user space. kern_poll() will
1444 * take care of copyin that array to the kernel space.
1447 return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1451 pollrescan(struct thread *td)
1457 struct filedesc *fdp;
1461 cap_rights_t rights;
1466 fdp = td->td_proc->p_fd;
1468 FILEDESC_SLOCK(fdp);
1469 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1470 fd = (struct pollfd *)sfp->sf_cookie;
1472 selfdfree(stp, sfp);
1473 /* If the selinfo wasn't cleared the event didn't fire. */
1476 fp = fdp->fd_ofiles[fd->fd].fde_file;
1479 cap_check(cap_rights(fdp, fd->fd),
1480 cap_rights_init(&rights, CAP_EVENT)) != 0)
1485 fd->revents = POLLNVAL;
1491 * Note: backend also returns POLLHUP and
1492 * POLLERR if appropriate.
1494 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1495 if (fd->revents != 0)
1498 FILEDESC_SUNLOCK(fdp);
1500 td->td_retval[0] = n;
1506 pollout(td, fds, ufds, nfd)
1509 struct pollfd *ufds;
1516 for (i = 0; i < nfd; i++) {
1517 error = copyout(&fds->revents, &ufds->revents,
1518 sizeof(ufds->revents));
1521 if (fds->revents != 0)
1526 td->td_retval[0] = n;
1531 pollscan(td, fds, nfd)
1536 struct filedesc *fdp = td->td_proc->p_fd;
1539 cap_rights_t rights;
1543 FILEDESC_SLOCK(fdp);
1544 for (i = 0; i < nfd; i++, fds++) {
1545 if (fds->fd > fdp->fd_lastfile) {
1546 fds->revents = POLLNVAL;
1548 } else if (fds->fd < 0) {
1551 fp = fdp->fd_ofiles[fds->fd].fde_file;
1554 cap_check(cap_rights(fdp, fds->fd),
1555 cap_rights_init(&rights, CAP_EVENT)) != 0)
1560 fds->revents = POLLNVAL;
1564 * Note: backend also returns POLLHUP and
1565 * POLLERR if appropriate.
1567 selfdalloc(td, fds);
1568 fds->revents = fo_poll(fp, fds->events,
1571 * POSIX requires POLLOUT to be never
1572 * set simultaneously with POLLHUP.
1574 if ((fds->revents & POLLHUP) != 0)
1575 fds->revents &= ~POLLOUT;
1577 if (fds->revents != 0)
1582 FILEDESC_SUNLOCK(fdp);
1583 td->td_retval[0] = n;
1588 * OpenBSD poll system call.
1590 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1592 #ifndef _SYS_SYSPROTO_H_
1593 struct openbsd_poll_args {
1600 sys_openbsd_poll(td, uap)
1601 register struct thread *td;
1602 register struct openbsd_poll_args *uap;
1604 return (sys_poll(td, (struct poll_args *)uap));
1608 * XXX This was created specifically to support netncp and netsmb. This
1609 * allows the caller to specify a socket to wait for events on. It returns
1610 * 0 if any events matched and an error otherwise. There is no way to
1611 * determine which events fired.
1614 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1617 sbintime_t asbt, precision, rsbt;
1620 precision = 0; /* stupid gcc! */
1623 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1624 rtv.tv_usec >= 1000000)
1626 if (!timevalisset(&rtv))
1628 else if (rtv.tv_sec <= INT32_MAX) {
1629 rsbt = tvtosbt(rtv);
1631 precision >>= tc_precexp;
1632 if (TIMESEL(&asbt, rsbt))
1633 asbt += tc_tick_sbt;
1634 if (asbt <= SBT_MAX - rsbt)
1644 * Iterate until the timeout expires or the socket becomes ready.
1647 selfdalloc(td, NULL);
1648 error = sopoll(so, events, NULL, td);
1649 /* error here is actually the ready events. */
1652 error = seltdwait(td, asbt, precision);
1657 /* XXX Duplicates ncp/smb behavior. */
1658 if (error == ERESTART)
1664 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1665 * have two select sets, one for read and another for write.
1668 selfdalloc(struct thread *td, void *cookie)
1673 if (stp->st_free1 == NULL)
1674 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1675 stp->st_free1->sf_td = stp;
1676 stp->st_free1->sf_cookie = cookie;
1677 if (stp->st_free2 == NULL)
1678 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1679 stp->st_free2->sf_td = stp;
1680 stp->st_free2->sf_cookie = cookie;
1684 selfdfree(struct seltd *stp, struct selfd *sfp)
1686 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1687 if (sfp->sf_si != NULL) {
1688 mtx_lock(sfp->sf_mtx);
1689 if (sfp->sf_si != NULL) {
1690 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1691 refcount_release(&sfp->sf_refs);
1693 mtx_unlock(sfp->sf_mtx);
1695 if (refcount_release(&sfp->sf_refs))
1696 uma_zfree(selfd_zone, sfp);
1699 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1702 struct selinfo *sip;
1706 * This feature is already provided by doselwakeup(), thus it is
1707 * enough to go for it.
1708 * Eventually, the context, should take care to avoid races
1709 * between thread calling select()/poll() and file descriptor
1710 * detaching, but, again, the races are just the same as
1713 doselwakeup(sip, -1);
1717 * Record a select request.
1720 selrecord(selector, sip)
1721 struct thread *selector;
1722 struct selinfo *sip;
1728 stp = selector->td_sel;
1730 * Don't record when doing a rescan.
1732 if (stp->st_flags & SELTD_RESCAN)
1735 * Grab one of the preallocated descriptors.
1738 if ((sfp = stp->st_free1) != NULL)
1739 stp->st_free1 = NULL;
1740 else if ((sfp = stp->st_free2) != NULL)
1741 stp->st_free2 = NULL;
1743 panic("selrecord: No free selfd on selq");
1746 mtxp = mtx_pool_find(mtxpool_select, sip);
1748 * Initialize the sfp and queue it in the thread.
1752 refcount_init(&sfp->sf_refs, 2);
1753 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1755 * Now that we've locked the sip, check for initialization.
1758 if (sip->si_mtx == NULL) {
1760 TAILQ_INIT(&sip->si_tdlist);
1763 * Add this thread to the list of selfds listening on this selinfo.
1765 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1766 mtx_unlock(sip->si_mtx);
1769 /* Wake up a selecting thread. */
1772 struct selinfo *sip;
1774 doselwakeup(sip, -1);
1777 /* Wake up a selecting thread, and set its priority. */
1779 selwakeuppri(sip, pri)
1780 struct selinfo *sip;
1783 doselwakeup(sip, pri);
1787 * Do a wakeup when a selectable event occurs.
1790 doselwakeup(sip, pri)
1791 struct selinfo *sip;
1798 /* If it's not initialized there can't be any waiters. */
1799 if (sip->si_mtx == NULL)
1802 * Locking the selinfo locks all selfds associated with it.
1804 mtx_lock(sip->si_mtx);
1805 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1807 * Once we remove this sfp from the list and clear the
1808 * sf_si seltdclear will know to ignore this si.
1810 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1813 mtx_lock(&stp->st_mtx);
1814 stp->st_flags |= SELTD_PENDING;
1815 cv_broadcastpri(&stp->st_wait, pri);
1816 mtx_unlock(&stp->st_mtx);
1817 if (refcount_release(&sfp->sf_refs))
1818 uma_zfree(selfd_zone, sfp);
1820 mtx_unlock(sip->si_mtx);
1824 seltdinit(struct thread *td)
1828 if ((stp = td->td_sel) != NULL)
1830 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1831 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1832 cv_init(&stp->st_wait, "select");
1835 STAILQ_INIT(&stp->st_selq);
1839 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1846 * An event of interest may occur while we do not hold the seltd
1847 * locked so check the pending flag before we sleep.
1849 mtx_lock(&stp->st_mtx);
1851 * Any further calls to selrecord will be a rescan.
1853 stp->st_flags |= SELTD_RESCAN;
1854 if (stp->st_flags & SELTD_PENDING) {
1855 mtx_unlock(&stp->st_mtx);
1859 error = EWOULDBLOCK;
1861 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1862 sbt, precision, C_ABSOLUTE);
1864 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1865 mtx_unlock(&stp->st_mtx);
1871 seltdfini(struct thread *td)
1879 uma_zfree(selfd_zone, stp->st_free1);
1881 uma_zfree(selfd_zone, stp->st_free2);
1883 free(stp, M_SELECT);
1887 * Remove the references to the thread from all of the objects we were
1891 seltdclear(struct thread *td)
1898 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1899 selfdfree(stp, sfp);
1903 static void selectinit(void *);
1904 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1906 selectinit(void *dummy __unused)
1909 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1910 NULL, NULL, UMA_ALIGN_PTR, 0);
1911 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1915 * Set up a syscall return value that follows the convention specified for
1916 * posix_* functions.
1919 kern_posix_error(struct thread *td, int error)
1924 td->td_errno = error;
1925 td->td_pflags |= TDP_NERRNO;
1926 td->td_retval[0] = error;