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/capability.h>
48 #include <sys/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/fcntl.h>
53 #include <sys/signalvar.h>
54 #include <sys/socketvar.h>
56 #include <sys/kernel.h>
58 #include <sys/limits.h>
59 #include <sys/malloc.h>
61 #include <sys/resourcevar.h>
62 #include <sys/selinfo.h>
63 #include <sys/sleepqueue.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/vnode.h>
70 #include <sys/condvar.h>
72 #include <sys/ktrace.h>
75 #include <security/audit/audit.h>
77 int iosize_max_clamp = 1;
78 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
79 &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
81 * Assert that the return value of read(2) and write(2) syscalls fits
82 * into a register. If not, an architecture will need to provide the
83 * usermode wrappers to reconstruct the result.
85 CTASSERT(sizeof(register_t) >= sizeof(size_t));
87 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
88 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
89 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
91 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
93 static int pollscan(struct thread *, struct pollfd *, u_int);
94 static int pollrescan(struct thread *);
95 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
96 static int selrescan(struct thread *, fd_mask **, fd_mask **);
97 static void selfdalloc(struct thread *, void *);
98 static void selfdfree(struct seltd *, struct selfd *);
99 static int dofileread(struct thread *, int, struct file *, struct uio *,
101 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
103 static void doselwakeup(struct selinfo *, int);
104 static void seltdinit(struct thread *);
105 static int seltdwait(struct thread *, int);
106 static void seltdclear(struct thread *);
109 * One seltd per-thread allocated on demand as needed.
111 * t - protected by st_mtx
112 * k - Only accessed by curthread or read-only
115 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
116 struct selfd *st_free1; /* (k) free fd for read set. */
117 struct selfd *st_free2; /* (k) free fd for write set. */
118 struct mtx st_mtx; /* Protects struct seltd */
119 struct cv st_wait; /* (t) Wait channel. */
120 int st_flags; /* (t) SELTD_ flags. */
123 #define SELTD_PENDING 0x0001 /* We have pending events. */
124 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
127 * One selfd allocated per-thread per-file-descriptor.
128 * f - protected by sf_mtx
131 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
132 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
133 struct selinfo *sf_si; /* (f) selinfo when linked. */
134 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
135 struct seltd *sf_td; /* (k) owning seltd. */
136 void *sf_cookie; /* (k) fd or pollfd. */
139 static uma_zone_t selfd_zone;
140 static struct mtx_pool *mtxpool_select;
142 #ifndef _SYS_SYSPROTO_H_
152 struct read_args *uap;
158 if (uap->nbyte > IOSIZE_MAX)
160 aiov.iov_base = uap->buf;
161 aiov.iov_len = uap->nbyte;
162 auio.uio_iov = &aiov;
164 auio.uio_resid = uap->nbyte;
165 auio.uio_segflg = UIO_USERSPACE;
166 error = kern_readv(td, uap->fd, &auio);
171 * Positioned read system call
173 #ifndef _SYS_SYSPROTO_H_
185 struct pread_args *uap;
191 if (uap->nbyte > IOSIZE_MAX)
193 aiov.iov_base = uap->buf;
194 aiov.iov_len = uap->nbyte;
195 auio.uio_iov = &aiov;
197 auio.uio_resid = uap->nbyte;
198 auio.uio_segflg = UIO_USERSPACE;
199 error = kern_preadv(td, uap->fd, &auio, uap->offset);
204 freebsd6_pread(td, uap)
206 struct freebsd6_pread_args *uap;
208 struct pread_args oargs;
211 oargs.buf = uap->buf;
212 oargs.nbyte = uap->nbyte;
213 oargs.offset = uap->offset;
214 return (sys_pread(td, &oargs));
218 * Scatter read system call.
220 #ifndef _SYS_SYSPROTO_H_
228 sys_readv(struct thread *td, struct readv_args *uap)
233 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
236 error = kern_readv(td, uap->fd, auio);
242 kern_readv(struct thread *td, int fd, struct uio *auio)
247 error = fget_read(td, fd, CAP_READ | CAP_SEEK, &fp);
250 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
256 * Scatter positioned read system call.
258 #ifndef _SYS_SYSPROTO_H_
267 sys_preadv(struct thread *td, struct preadv_args *uap)
272 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
275 error = kern_preadv(td, uap->fd, auio, uap->offset);
281 kern_preadv(td, fd, auio, offset)
290 error = fget_read(td, fd, CAP_READ, &fp);
293 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
295 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
298 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
304 * Common code for readv and preadv that reads data in
305 * from a file using the passed in uio, offset, and flags.
308 dofileread(td, fd, fp, auio, offset, flags)
319 struct uio *ktruio = NULL;
322 /* Finish zero length reads right here */
323 if (auio->uio_resid == 0) {
324 td->td_retval[0] = 0;
327 auio->uio_rw = UIO_READ;
328 auio->uio_offset = offset;
331 if (KTRPOINT(td, KTR_GENIO))
332 ktruio = cloneuio(auio);
334 cnt = auio->uio_resid;
335 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
336 if (auio->uio_resid != cnt && (error == ERESTART ||
337 error == EINTR || error == EWOULDBLOCK))
340 cnt -= auio->uio_resid;
342 if (ktruio != NULL) {
343 ktruio->uio_resid = cnt;
344 ktrgenio(fd, UIO_READ, ktruio, error);
347 td->td_retval[0] = cnt;
351 #ifndef _SYS_SYSPROTO_H_
361 struct write_args *uap;
367 if (uap->nbyte > IOSIZE_MAX)
369 aiov.iov_base = (void *)(uintptr_t)uap->buf;
370 aiov.iov_len = uap->nbyte;
371 auio.uio_iov = &aiov;
373 auio.uio_resid = uap->nbyte;
374 auio.uio_segflg = UIO_USERSPACE;
375 error = kern_writev(td, uap->fd, &auio);
380 * Positioned write system call.
382 #ifndef _SYS_SYSPROTO_H_
394 struct pwrite_args *uap;
400 if (uap->nbyte > IOSIZE_MAX)
402 aiov.iov_base = (void *)(uintptr_t)uap->buf;
403 aiov.iov_len = uap->nbyte;
404 auio.uio_iov = &aiov;
406 auio.uio_resid = uap->nbyte;
407 auio.uio_segflg = UIO_USERSPACE;
408 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
413 freebsd6_pwrite(td, uap)
415 struct freebsd6_pwrite_args *uap;
417 struct pwrite_args oargs;
420 oargs.buf = uap->buf;
421 oargs.nbyte = uap->nbyte;
422 oargs.offset = uap->offset;
423 return (sys_pwrite(td, &oargs));
427 * Gather write system call.
429 #ifndef _SYS_SYSPROTO_H_
437 sys_writev(struct thread *td, struct writev_args *uap)
442 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
445 error = kern_writev(td, uap->fd, auio);
451 kern_writev(struct thread *td, int fd, struct uio *auio)
456 error = fget_write(td, fd, CAP_WRITE | CAP_SEEK, &fp);
459 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
465 * Gather positioned write system call.
467 #ifndef _SYS_SYSPROTO_H_
468 struct pwritev_args {
476 sys_pwritev(struct thread *td, struct pwritev_args *uap)
481 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
484 error = kern_pwritev(td, uap->fd, auio, uap->offset);
490 kern_pwritev(td, fd, auio, offset)
499 error = fget_write(td, fd, CAP_WRITE, &fp);
502 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
504 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
507 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
513 * Common code for writev and pwritev that writes data to
514 * a file using the passed in uio, offset, and flags.
517 dofilewrite(td, fd, fp, auio, offset, flags)
528 struct uio *ktruio = NULL;
531 auio->uio_rw = UIO_WRITE;
533 auio->uio_offset = offset;
535 if (KTRPOINT(td, KTR_GENIO))
536 ktruio = cloneuio(auio);
538 cnt = auio->uio_resid;
539 if (fp->f_type == DTYPE_VNODE &&
540 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
542 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
543 if (auio->uio_resid != cnt && (error == ERESTART ||
544 error == EINTR || error == EWOULDBLOCK))
546 /* Socket layer is responsible for issuing SIGPIPE. */
547 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
548 PROC_LOCK(td->td_proc);
549 tdsignal(td, SIGPIPE);
550 PROC_UNLOCK(td->td_proc);
553 cnt -= auio->uio_resid;
555 if (ktruio != NULL) {
556 ktruio->uio_resid = cnt;
557 ktrgenio(fd, UIO_WRITE, ktruio, error);
560 td->td_retval[0] = cnt;
565 * Truncate a file given a file descriptor.
567 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
568 * descriptor isn't writable.
571 kern_ftruncate(td, fd, length)
582 error = fget(td, fd, CAP_FTRUNCATE, &fp);
585 AUDIT_ARG_FILE(td->td_proc, fp);
586 if (!(fp->f_flag & FWRITE)) {
590 error = fo_truncate(fp, length, td->td_ucred, td);
595 #ifndef _SYS_SYSPROTO_H_
596 struct ftruncate_args {
603 sys_ftruncate(td, uap)
605 struct ftruncate_args *uap;
608 return (kern_ftruncate(td, uap->fd, uap->length));
611 #if defined(COMPAT_43)
612 #ifndef _SYS_SYSPROTO_H_
613 struct oftruncate_args {
621 struct oftruncate_args *uap;
624 return (kern_ftruncate(td, uap->fd, uap->length));
626 #endif /* COMPAT_43 */
628 #ifndef _SYS_SYSPROTO_H_
637 sys_ioctl(struct thread *td, struct ioctl_args *uap)
644 if (uap->com > 0xffffffff) {
646 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
647 td->td_proc->p_pid, td->td_name, uap->com);
648 uap->com &= 0xffffffff;
653 * Interpret high order word to find amount of data to be
654 * copied to/from the user's address space.
656 size = IOCPARM_LEN(com);
657 if ((size > IOCPARM_MAX) ||
658 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
659 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
660 ((com & IOC_OUT) && size == 0) ||
662 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
664 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
668 if (com & IOC_VOID) {
669 /* Integer argument. */
670 arg = (intptr_t)uap->data;
674 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
676 data = (void *)&uap->data;
678 error = copyin(uap->data, data, (u_int)size);
681 free(data, M_IOCTLOPS);
684 } else if (com & IOC_OUT) {
686 * Zero the buffer so the user always
687 * gets back something deterministic.
692 error = kern_ioctl(td, uap->fd, com, data);
694 if (error == 0 && (com & IOC_OUT))
695 error = copyout(data, uap->data, (u_int)size);
698 free(data, M_IOCTLOPS);
703 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
706 struct filedesc *fdp;
712 if ((error = fget(td, fd, CAP_IOCTL, &fp)) != 0)
714 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
718 fdp = td->td_proc->p_fd;
722 fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
723 FILEDESC_XUNLOCK(fdp);
727 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
728 FILEDESC_XUNLOCK(fdp);
731 if ((tmp = *(int *)data))
732 atomic_set_int(&fp->f_flag, FNONBLOCK);
734 atomic_clear_int(&fp->f_flag, FNONBLOCK);
738 if ((tmp = *(int *)data))
739 atomic_set_int(&fp->f_flag, FASYNC);
741 atomic_clear_int(&fp->f_flag, FASYNC);
746 error = fo_ioctl(fp, com, data, td->td_ucred, td);
753 poll_no_poll(int events)
756 * Return true for read/write. If the user asked for something
757 * special, return POLLNVAL, so that clients have a way of
758 * determining reliably whether or not the extended
759 * functionality is present without hard-coding knowledge
760 * of specific filesystem implementations.
762 if (events & ~POLLSTANDARD)
765 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
769 sys_pselect(struct thread *td, struct pselect_args *uap)
772 struct timeval tv, *tvp;
776 if (uap->ts != NULL) {
777 error = copyin(uap->ts, &ts, sizeof(ts));
780 TIMESPEC_TO_TIMEVAL(&tv, &ts);
784 if (uap->sm != NULL) {
785 error = copyin(uap->sm, &set, sizeof(set));
791 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
796 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
797 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
802 error = kern_sigprocmask(td, SIG_SETMASK, uset,
803 &td->td_oldsigmask, 0);
806 td->td_pflags |= TDP_OLDMASK;
808 * Make sure that ast() is called on return to
809 * usermode and TDP_OLDMASK is cleared, restoring old
813 td->td_flags |= TDF_ASTPENDING;
816 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
820 #ifndef _SYS_SYSPROTO_H_
823 fd_set *in, *ou, *ex;
828 sys_select(struct thread *td, struct select_args *uap)
830 struct timeval tv, *tvp;
833 if (uap->tv != NULL) {
834 error = copyin(uap->tv, &tv, sizeof(tv));
841 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
846 * In the unlikely case when user specified n greater then the last
847 * open file descriptor, check that no bits are set after the last
848 * valid fd. We must return EBADF if any is set.
850 * There are applications that rely on the behaviour.
852 * nd is fd_lastfile + 1.
855 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
861 if (nd >= ndu || fd_in == NULL)
865 bits = 0; /* silence gcc */
866 for (i = nd; i < ndu; i++) {
868 #if BYTE_ORDER == LITTLE_ENDIAN
869 addr = (char *)fd_in + b;
871 addr = (char *)fd_in;
872 if (abi_nfdbits == NFDBITS) {
873 addr += rounddown(b, sizeof(fd_mask)) +
874 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
876 addr += rounddown(b, sizeof(uint32_t)) +
877 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
887 if ((bits & (1 << (i % NBBY))) != 0)
894 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
895 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
897 struct filedesc *fdp;
899 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
900 * infds with the new FD_SETSIZE of 1024, and more than enough for
901 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
904 fd_mask s_selbits[howmany(2048, NFDBITS)];
905 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
906 struct timeval atv, rtv, ttv;
907 int error, lf, ndu, timo;
908 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
912 fdp = td->td_proc->p_fd;
914 lf = fdp->fd_lastfile;
918 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
921 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
924 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
929 * Allocate just enough bits for the non-null fd_sets. Use the
930 * preallocated auto buffer if possible.
932 nfdbits = roundup(nd, NFDBITS);
933 ncpbytes = nfdbits / NBBY;
934 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
937 nbufbytes += 2 * ncpbytes;
939 nbufbytes += 2 * ncpbytes;
941 nbufbytes += 2 * ncpbytes;
942 if (nbufbytes <= sizeof s_selbits)
943 selbits = &s_selbits[0];
945 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
948 * Assign pointers into the bit buffers and fetch the input bits.
949 * Put the output buffers together so that they can be bzeroed
953 #define getbits(name, x) \
955 if (name == NULL) { \
959 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
961 sbp += ncpbytes / sizeof *sbp; \
962 error = copyin(name, ibits[x], ncpubytes); \
965 bzero((char *)ibits[x] + ncpubytes, \
966 ncpbytes - ncpubytes); \
974 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
976 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
977 * we are running under 32-bit emulation. This should be more
980 #define swizzle_fdset(bits) \
981 if (abi_nfdbits != NFDBITS && bits != NULL) { \
983 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
984 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
987 #define swizzle_fdset(bits)
990 /* Make sure the bit order makes it through an ABI transition */
991 swizzle_fdset(ibits[0]);
992 swizzle_fdset(ibits[1]);
993 swizzle_fdset(ibits[2]);
996 bzero(selbits, nbufbytes / 2);
1000 if (itimerfix(&atv)) {
1004 getmicrouptime(&rtv);
1005 timevaladd(&atv, &rtv);
1012 /* Iterate until the timeout expires or descriptors become ready. */
1014 error = selscan(td, ibits, obits, nd);
1015 if (error || td->td_retval[0] != 0)
1017 if (atv.tv_sec || atv.tv_usec) {
1018 getmicrouptime(&rtv);
1019 if (timevalcmp(&rtv, &atv, >=))
1022 timevalsub(&ttv, &rtv);
1023 timo = ttv.tv_sec > 24 * 60 * 60 ?
1024 24 * 60 * 60 * hz : tvtohz(&ttv);
1026 error = seltdwait(td, timo);
1029 error = selrescan(td, ibits, obits);
1030 if (error || td->td_retval[0] != 0)
1036 /* select is not restarted after signals... */
1037 if (error == ERESTART)
1039 if (error == EWOULDBLOCK)
1042 /* swizzle bit order back, if necessary */
1043 swizzle_fdset(obits[0]);
1044 swizzle_fdset(obits[1]);
1045 swizzle_fdset(obits[2]);
1046 #undef swizzle_fdset
1048 #define putbits(name, x) \
1049 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1059 if (selbits != &s_selbits[0])
1060 free(selbits, M_SELECT);
1065 * Convert a select bit set to poll flags.
1067 * The backend always returns POLLHUP/POLLERR if appropriate and we
1068 * return this as a set bit in any set.
1070 static int select_flags[3] = {
1071 POLLRDNORM | POLLHUP | POLLERR,
1072 POLLWRNORM | POLLHUP | POLLERR,
1073 POLLRDBAND | POLLERR
1077 * Compute the fo_poll flags required for a fd given by the index and
1078 * bit position in the fd_mask array.
1081 selflags(fd_mask **ibits, int idx, fd_mask bit)
1087 for (msk = 0; msk < 3; msk++) {
1088 if (ibits[msk] == NULL)
1090 if ((ibits[msk][idx] & bit) == 0)
1092 flags |= select_flags[msk];
1098 * Set the appropriate output bits given a mask of fired events and the
1099 * input bits originally requested.
1102 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1108 for (msk = 0; msk < 3; msk++) {
1109 if ((events & select_flags[msk]) == 0)
1111 if (ibits[msk] == NULL)
1113 if ((ibits[msk][idx] & bit) == 0)
1116 * XXX Check for a duplicate set. This can occur because a
1117 * socket calls selrecord() twice for each poll() call
1118 * resulting in two selfds per real fd. selrescan() will
1119 * call selsetbits twice as a result.
1121 if ((obits[msk][idx] & bit) != 0)
1123 obits[msk][idx] |= bit;
1131 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1135 struct file *fp_fromcap;
1139 if ((fp = fget_unlocked(fdp, fd)) == NULL)
1143 * If the file descriptor is for a capability, test rights and use
1144 * the file descriptor references by the capability.
1146 error = cap_funwrap(fp, CAP_POLL_EVENT, &fp_fromcap);
1148 fdrop(fp, curthread);
1151 if (fp != fp_fromcap) {
1153 fdrop(fp, curthread);
1156 #endif /* CAPABILITIES */
1162 * Traverse the list of fds attached to this thread's seltd and check for
1166 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1168 struct filedesc *fdp;
1178 fdp = td->td_proc->p_fd;
1181 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1182 fd = (int)(uintptr_t)sfp->sf_cookie;
1184 selfdfree(stp, sfp);
1185 /* If the selinfo wasn't cleared the event didn't fire. */
1188 error = getselfd_cap(fdp, fd, &fp);
1192 bit = (fd_mask)1 << (fd % NFDBITS);
1193 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1196 n += selsetbits(ibits, obits, idx, bit, ev);
1199 td->td_retval[0] = n;
1204 * Perform the initial filedescriptor scan and register ourselves with
1208 selscan(td, ibits, obits, nfd)
1210 fd_mask **ibits, **obits;
1213 struct filedesc *fdp;
1216 int ev, flags, end, fd;
1220 fdp = td->td_proc->p_fd;
1222 for (idx = 0, fd = 0; fd < nfd; idx++) {
1223 end = imin(fd + NFDBITS, nfd);
1224 for (bit = 1; fd < end; bit <<= 1, fd++) {
1225 /* Compute the list of events we're interested in. */
1226 flags = selflags(ibits, idx, bit);
1229 error = getselfd_cap(fdp, fd, &fp);
1232 selfdalloc(td, (void *)(uintptr_t)fd);
1233 ev = fo_poll(fp, flags, td->td_ucred, td);
1236 n += selsetbits(ibits, obits, idx, bit, ev);
1240 td->td_retval[0] = n;
1244 #ifndef _SYS_SYSPROTO_H_
1254 struct poll_args *uap;
1256 struct pollfd *bits;
1257 struct pollfd smallbits[32];
1258 struct timeval atv, rtv, ttv;
1264 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1266 ni = nfds * sizeof(struct pollfd);
1267 if (ni > sizeof(smallbits))
1268 bits = malloc(ni, M_TEMP, M_WAITOK);
1271 error = copyin(uap->fds, bits, ni);
1274 if (uap->timeout != INFTIM) {
1275 atv.tv_sec = uap->timeout / 1000;
1276 atv.tv_usec = (uap->timeout % 1000) * 1000;
1277 if (itimerfix(&atv)) {
1281 getmicrouptime(&rtv);
1282 timevaladd(&atv, &rtv);
1289 /* Iterate until the timeout expires or descriptors become ready. */
1291 error = pollscan(td, bits, nfds);
1292 if (error || td->td_retval[0] != 0)
1294 if (atv.tv_sec || atv.tv_usec) {
1295 getmicrouptime(&rtv);
1296 if (timevalcmp(&rtv, &atv, >=))
1299 timevalsub(&ttv, &rtv);
1300 timo = ttv.tv_sec > 24 * 60 * 60 ?
1301 24 * 60 * 60 * hz : tvtohz(&ttv);
1303 error = seltdwait(td, timo);
1306 error = pollrescan(td);
1307 if (error || td->td_retval[0] != 0)
1313 /* poll is not restarted after signals... */
1314 if (error == ERESTART)
1316 if (error == EWOULDBLOCK)
1319 error = pollout(td, bits, uap->fds, nfds);
1324 if (ni > sizeof(smallbits))
1330 pollrescan(struct thread *td)
1336 struct filedesc *fdp;
1342 fdp = td->td_proc->p_fd;
1344 FILEDESC_SLOCK(fdp);
1345 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1346 fd = (struct pollfd *)sfp->sf_cookie;
1348 selfdfree(stp, sfp);
1349 /* If the selinfo wasn't cleared the event didn't fire. */
1352 fp = fdp->fd_ofiles[fd->fd];
1355 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1359 fd->revents = POLLNVAL;
1365 * Note: backend also returns POLLHUP and
1366 * POLLERR if appropriate.
1368 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1369 if (fd->revents != 0)
1372 FILEDESC_SUNLOCK(fdp);
1374 td->td_retval[0] = n;
1380 pollout(td, fds, ufds, nfd)
1383 struct pollfd *ufds;
1390 for (i = 0; i < nfd; i++) {
1391 error = copyout(&fds->revents, &ufds->revents,
1392 sizeof(ufds->revents));
1395 if (fds->revents != 0)
1400 td->td_retval[0] = n;
1405 pollscan(td, fds, nfd)
1410 struct filedesc *fdp = td->td_proc->p_fd;
1415 FILEDESC_SLOCK(fdp);
1416 for (i = 0; i < nfd; i++, fds++) {
1417 if (fds->fd >= fdp->fd_nfiles) {
1418 fds->revents = POLLNVAL;
1420 } else if (fds->fd < 0) {
1423 fp = fdp->fd_ofiles[fds->fd];
1426 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1430 fds->revents = POLLNVAL;
1434 * Note: backend also returns POLLHUP and
1435 * POLLERR if appropriate.
1437 selfdalloc(td, fds);
1438 fds->revents = fo_poll(fp, fds->events,
1441 * POSIX requires POLLOUT to be never
1442 * set simultaneously with POLLHUP.
1444 if ((fds->revents & POLLHUP) != 0)
1445 fds->revents &= ~POLLOUT;
1447 if (fds->revents != 0)
1452 FILEDESC_SUNLOCK(fdp);
1453 td->td_retval[0] = n;
1458 * OpenBSD poll system call.
1460 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1462 #ifndef _SYS_SYSPROTO_H_
1463 struct openbsd_poll_args {
1470 sys_openbsd_poll(td, uap)
1471 register struct thread *td;
1472 register struct openbsd_poll_args *uap;
1474 return (sys_poll(td, (struct poll_args *)uap));
1478 * XXX This was created specifically to support netncp and netsmb. This
1479 * allows the caller to specify a socket to wait for events on. It returns
1480 * 0 if any events matched and an error otherwise. There is no way to
1481 * determine which events fired.
1484 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1486 struct timeval atv, rtv, ttv;
1491 if (itimerfix(&atv))
1493 getmicrouptime(&rtv);
1494 timevaladd(&atv, &rtv);
1503 * Iterate until the timeout expires or the socket becomes ready.
1506 selfdalloc(td, NULL);
1507 error = sopoll(so, events, NULL, td);
1508 /* error here is actually the ready events. */
1511 if (atv.tv_sec || atv.tv_usec) {
1512 getmicrouptime(&rtv);
1513 if (timevalcmp(&rtv, &atv, >=)) {
1515 return (EWOULDBLOCK);
1518 timevalsub(&ttv, &rtv);
1519 timo = ttv.tv_sec > 24 * 60 * 60 ?
1520 24 * 60 * 60 * hz : tvtohz(&ttv);
1522 error = seltdwait(td, timo);
1527 /* XXX Duplicates ncp/smb behavior. */
1528 if (error == ERESTART)
1534 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1535 * have two select sets, one for read and another for write.
1538 selfdalloc(struct thread *td, void *cookie)
1543 if (stp->st_free1 == NULL)
1544 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1545 stp->st_free1->sf_td = stp;
1546 stp->st_free1->sf_cookie = cookie;
1547 if (stp->st_free2 == NULL)
1548 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1549 stp->st_free2->sf_td = stp;
1550 stp->st_free2->sf_cookie = cookie;
1554 selfdfree(struct seltd *stp, struct selfd *sfp)
1556 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1557 mtx_lock(sfp->sf_mtx);
1559 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1560 mtx_unlock(sfp->sf_mtx);
1561 uma_zfree(selfd_zone, sfp);
1564 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1567 struct selinfo *sip;
1571 * This feature is already provided by doselwakeup(), thus it is
1572 * enough to go for it.
1573 * Eventually, the context, should take care to avoid races
1574 * between thread calling select()/poll() and file descriptor
1575 * detaching, but, again, the races are just the same as
1578 doselwakeup(sip, -1);
1582 * Record a select request.
1585 selrecord(selector, sip)
1586 struct thread *selector;
1587 struct selinfo *sip;
1593 stp = selector->td_sel;
1595 * Don't record when doing a rescan.
1597 if (stp->st_flags & SELTD_RESCAN)
1600 * Grab one of the preallocated descriptors.
1603 if ((sfp = stp->st_free1) != NULL)
1604 stp->st_free1 = NULL;
1605 else if ((sfp = stp->st_free2) != NULL)
1606 stp->st_free2 = NULL;
1608 panic("selrecord: No free selfd on selq");
1611 mtxp = mtx_pool_find(mtxpool_select, sip);
1613 * Initialize the sfp and queue it in the thread.
1617 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1619 * Now that we've locked the sip, check for initialization.
1622 if (sip->si_mtx == NULL) {
1624 TAILQ_INIT(&sip->si_tdlist);
1627 * Add this thread to the list of selfds listening on this selinfo.
1629 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1630 mtx_unlock(sip->si_mtx);
1633 /* Wake up a selecting thread. */
1636 struct selinfo *sip;
1638 doselwakeup(sip, -1);
1641 /* Wake up a selecting thread, and set its priority. */
1643 selwakeuppri(sip, pri)
1644 struct selinfo *sip;
1647 doselwakeup(sip, pri);
1651 * Do a wakeup when a selectable event occurs.
1654 doselwakeup(sip, pri)
1655 struct selinfo *sip;
1662 /* If it's not initialized there can't be any waiters. */
1663 if (sip->si_mtx == NULL)
1666 * Locking the selinfo locks all selfds associated with it.
1668 mtx_lock(sip->si_mtx);
1669 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1671 * Once we remove this sfp from the list and clear the
1672 * sf_si seltdclear will know to ignore this si.
1674 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1677 mtx_lock(&stp->st_mtx);
1678 stp->st_flags |= SELTD_PENDING;
1679 cv_broadcastpri(&stp->st_wait, pri);
1680 mtx_unlock(&stp->st_mtx);
1682 mtx_unlock(sip->si_mtx);
1686 seltdinit(struct thread *td)
1690 if ((stp = td->td_sel) != NULL)
1692 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1693 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1694 cv_init(&stp->st_wait, "select");
1697 STAILQ_INIT(&stp->st_selq);
1701 seltdwait(struct thread *td, int timo)
1708 * An event of interest may occur while we do not hold the seltd
1709 * locked so check the pending flag before we sleep.
1711 mtx_lock(&stp->st_mtx);
1713 * Any further calls to selrecord will be a rescan.
1715 stp->st_flags |= SELTD_RESCAN;
1716 if (stp->st_flags & SELTD_PENDING) {
1717 mtx_unlock(&stp->st_mtx);
1721 error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1723 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1724 mtx_unlock(&stp->st_mtx);
1730 seltdfini(struct thread *td)
1738 uma_zfree(selfd_zone, stp->st_free1);
1740 uma_zfree(selfd_zone, stp->st_free2);
1742 free(stp, M_SELECT);
1746 * Remove the references to the thread from all of the objects we were
1750 seltdclear(struct thread *td)
1757 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1758 selfdfree(stp, sfp);
1762 static void selectinit(void *);
1763 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1765 selectinit(void *dummy __unused)
1768 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1769 NULL, NULL, UMA_ALIGN_PTR, 0);
1770 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);