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>
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>
78 int iosize_max_clamp = 1;
79 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
80 &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
82 * Assert that the return value of read(2) and write(2) syscalls fits
83 * into a register. If not, an architecture will need to provide the
84 * usermode wrappers to reconstruct the result.
86 CTASSERT(sizeof(register_t) >= sizeof(size_t));
88 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
89 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
90 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
92 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
94 static int pollscan(struct thread *, struct pollfd *, u_int);
95 static int pollrescan(struct thread *);
96 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
97 static int selrescan(struct thread *, fd_mask **, fd_mask **);
98 static void selfdalloc(struct thread *, void *);
99 static void selfdfree(struct seltd *, struct selfd *);
100 static int dofileread(struct thread *, int, struct file *, struct uio *,
102 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
104 static void doselwakeup(struct selinfo *, int);
105 static void seltdinit(struct thread *);
106 static int seltdwait(struct thread *, sbintime_t, sbintime_t);
107 static void seltdclear(struct thread *);
110 * One seltd per-thread allocated on demand as needed.
112 * t - protected by st_mtx
113 * k - Only accessed by curthread or read-only
116 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
117 struct selfd *st_free1; /* (k) free fd for read set. */
118 struct selfd *st_free2; /* (k) free fd for write set. */
119 struct mtx st_mtx; /* Protects struct seltd */
120 struct cv st_wait; /* (t) Wait channel. */
121 int st_flags; /* (t) SELTD_ flags. */
124 #define SELTD_PENDING 0x0001 /* We have pending events. */
125 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
128 * One selfd allocated per-thread per-file-descriptor.
129 * f - protected by sf_mtx
132 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
133 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
134 struct selinfo *sf_si; /* (f) selinfo when linked. */
135 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
136 struct seltd *sf_td; /* (k) owning seltd. */
137 void *sf_cookie; /* (k) fd or pollfd. */
140 static uma_zone_t selfd_zone;
141 static struct mtx_pool *mtxpool_select;
143 #ifndef _SYS_SYSPROTO_H_
153 struct read_args *uap;
159 if (uap->nbyte > IOSIZE_MAX)
161 aiov.iov_base = uap->buf;
162 aiov.iov_len = uap->nbyte;
163 auio.uio_iov = &aiov;
165 auio.uio_resid = uap->nbyte;
166 auio.uio_segflg = UIO_USERSPACE;
167 error = kern_readv(td, uap->fd, &auio);
172 * Positioned read system call
174 #ifndef _SYS_SYSPROTO_H_
186 struct pread_args *uap;
192 if (uap->nbyte > IOSIZE_MAX)
194 aiov.iov_base = uap->buf;
195 aiov.iov_len = uap->nbyte;
196 auio.uio_iov = &aiov;
198 auio.uio_resid = uap->nbyte;
199 auio.uio_segflg = UIO_USERSPACE;
200 error = kern_preadv(td, uap->fd, &auio, uap->offset);
205 freebsd6_pread(td, uap)
207 struct freebsd6_pread_args *uap;
209 struct pread_args oargs;
212 oargs.buf = uap->buf;
213 oargs.nbyte = uap->nbyte;
214 oargs.offset = uap->offset;
215 return (sys_pread(td, &oargs));
219 * Scatter read system call.
221 #ifndef _SYS_SYSPROTO_H_
229 sys_readv(struct thread *td, struct readv_args *uap)
234 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
237 error = kern_readv(td, uap->fd, auio);
243 kern_readv(struct thread *td, int fd, struct uio *auio)
249 error = fget_read(td, fd, cap_rights_init(&rights, CAP_READ), &fp);
252 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
258 * Scatter positioned read system call.
260 #ifndef _SYS_SYSPROTO_H_
269 sys_preadv(struct thread *td, struct preadv_args *uap)
274 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
277 error = kern_preadv(td, uap->fd, auio, uap->offset);
283 kern_preadv(td, fd, auio, offset)
293 error = fget_read(td, fd, cap_rights_init(&rights, CAP_PREAD), &fp);
296 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
298 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
301 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
307 * Common code for readv and preadv that reads data in
308 * from a file using the passed in uio, offset, and flags.
311 dofileread(td, fd, fp, auio, offset, flags)
322 struct uio *ktruio = NULL;
325 /* Finish zero length reads right here */
326 if (auio->uio_resid == 0) {
327 td->td_retval[0] = 0;
330 auio->uio_rw = UIO_READ;
331 auio->uio_offset = offset;
334 if (KTRPOINT(td, KTR_GENIO))
335 ktruio = cloneuio(auio);
337 cnt = auio->uio_resid;
338 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
339 if (auio->uio_resid != cnt && (error == ERESTART ||
340 error == EINTR || error == EWOULDBLOCK))
343 cnt -= auio->uio_resid;
345 if (ktruio != NULL) {
346 ktruio->uio_resid = cnt;
347 ktrgenio(fd, UIO_READ, ktruio, error);
350 td->td_retval[0] = cnt;
354 #ifndef _SYS_SYSPROTO_H_
364 struct write_args *uap;
370 if (uap->nbyte > IOSIZE_MAX)
372 aiov.iov_base = (void *)(uintptr_t)uap->buf;
373 aiov.iov_len = uap->nbyte;
374 auio.uio_iov = &aiov;
376 auio.uio_resid = uap->nbyte;
377 auio.uio_segflg = UIO_USERSPACE;
378 error = kern_writev(td, uap->fd, &auio);
383 * Positioned write system call.
385 #ifndef _SYS_SYSPROTO_H_
397 struct pwrite_args *uap;
403 if (uap->nbyte > IOSIZE_MAX)
405 aiov.iov_base = (void *)(uintptr_t)uap->buf;
406 aiov.iov_len = uap->nbyte;
407 auio.uio_iov = &aiov;
409 auio.uio_resid = uap->nbyte;
410 auio.uio_segflg = UIO_USERSPACE;
411 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
416 freebsd6_pwrite(td, uap)
418 struct freebsd6_pwrite_args *uap;
420 struct pwrite_args oargs;
423 oargs.buf = uap->buf;
424 oargs.nbyte = uap->nbyte;
425 oargs.offset = uap->offset;
426 return (sys_pwrite(td, &oargs));
430 * Gather write system call.
432 #ifndef _SYS_SYSPROTO_H_
440 sys_writev(struct thread *td, struct writev_args *uap)
445 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
448 error = kern_writev(td, uap->fd, auio);
454 kern_writev(struct thread *td, int fd, struct uio *auio)
460 error = fget_write(td, fd, cap_rights_init(&rights, CAP_WRITE), &fp);
463 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
469 * Gather positioned write system call.
471 #ifndef _SYS_SYSPROTO_H_
472 struct pwritev_args {
480 sys_pwritev(struct thread *td, struct pwritev_args *uap)
485 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
488 error = kern_pwritev(td, uap->fd, auio, uap->offset);
494 kern_pwritev(td, fd, auio, offset)
504 error = fget_write(td, fd, cap_rights_init(&rights, CAP_PWRITE), &fp);
507 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
509 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
512 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
518 * Common code for writev and pwritev that writes data to
519 * a file using the passed in uio, offset, and flags.
522 dofilewrite(td, fd, fp, auio, offset, flags)
533 struct uio *ktruio = NULL;
536 auio->uio_rw = UIO_WRITE;
538 auio->uio_offset = offset;
540 if (KTRPOINT(td, KTR_GENIO))
541 ktruio = cloneuio(auio);
543 cnt = auio->uio_resid;
544 if (fp->f_type == DTYPE_VNODE &&
545 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
547 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
548 if (auio->uio_resid != cnt && (error == ERESTART ||
549 error == EINTR || error == EWOULDBLOCK))
551 /* Socket layer is responsible for issuing SIGPIPE. */
552 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
553 PROC_LOCK(td->td_proc);
554 tdsignal(td, SIGPIPE);
555 PROC_UNLOCK(td->td_proc);
558 cnt -= auio->uio_resid;
560 if (ktruio != NULL) {
561 ktruio->uio_resid = cnt;
562 ktrgenio(fd, UIO_WRITE, ktruio, error);
565 td->td_retval[0] = cnt;
570 * Truncate a file given a file descriptor.
572 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
573 * descriptor isn't writable.
576 kern_ftruncate(td, fd, length)
588 error = fget(td, fd, cap_rights_init(&rights, CAP_FTRUNCATE), &fp);
591 AUDIT_ARG_FILE(td->td_proc, fp);
592 if (!(fp->f_flag & FWRITE)) {
596 error = fo_truncate(fp, length, td->td_ucred, td);
601 #ifndef _SYS_SYSPROTO_H_
602 struct ftruncate_args {
609 sys_ftruncate(td, uap)
611 struct ftruncate_args *uap;
614 return (kern_ftruncate(td, uap->fd, uap->length));
617 #if defined(COMPAT_43)
618 #ifndef _SYS_SYSPROTO_H_
619 struct oftruncate_args {
627 struct oftruncate_args *uap;
630 return (kern_ftruncate(td, uap->fd, uap->length));
632 #endif /* COMPAT_43 */
634 #ifndef _SYS_SYSPROTO_H_
643 sys_ioctl(struct thread *td, struct ioctl_args *uap)
650 if (uap->com > 0xffffffff) {
652 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
653 td->td_proc->p_pid, td->td_name, uap->com);
654 uap->com &= 0xffffffff;
659 * Interpret high order word to find amount of data to be
660 * copied to/from the user's address space.
662 size = IOCPARM_LEN(com);
663 if ((size > IOCPARM_MAX) ||
664 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
665 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
666 ((com & IOC_OUT) && size == 0) ||
668 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
670 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
674 if (com & IOC_VOID) {
675 /* Integer argument. */
676 arg = (intptr_t)uap->data;
680 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
682 data = (void *)&uap->data;
684 error = copyin(uap->data, data, (u_int)size);
687 free(data, M_IOCTLOPS);
690 } else if (com & IOC_OUT) {
692 * Zero the buffer so the user always
693 * gets back something deterministic.
698 error = kern_ioctl(td, uap->fd, com, data);
700 if (error == 0 && (com & IOC_OUT))
701 error = copyout(data, uap->data, (u_int)size);
704 free(data, M_IOCTLOPS);
709 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
712 struct filedesc *fdp;
716 int error, tmp, locked;
721 fdp = td->td_proc->p_fd;
734 locked = LA_UNLOCKED;
740 if ((fp = fget_locked(fdp, fd)) == NULL) {
744 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
745 fp = NULL; /* fhold() was not called yet */
749 if (locked == LA_SLOCKED) {
750 FILEDESC_SUNLOCK(fdp);
751 locked = LA_UNLOCKED;
754 error = fget(td, fd, cap_rights_init(&rights, CAP_IOCTL), &fp);
760 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
767 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
770 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
773 if ((tmp = *(int *)data))
774 atomic_set_int(&fp->f_flag, FNONBLOCK);
776 atomic_clear_int(&fp->f_flag, FNONBLOCK);
780 if ((tmp = *(int *)data))
781 atomic_set_int(&fp->f_flag, FASYNC);
783 atomic_clear_int(&fp->f_flag, FASYNC);
788 error = fo_ioctl(fp, com, data, td->td_ucred, td);
792 FILEDESC_XUNLOCK(fdp);
796 FILEDESC_SUNLOCK(fdp);
800 FILEDESC_UNLOCK_ASSERT(fdp);
809 poll_no_poll(int events)
812 * Return true for read/write. If the user asked for something
813 * special, return POLLNVAL, so that clients have a way of
814 * determining reliably whether or not the extended
815 * functionality is present without hard-coding knowledge
816 * of specific filesystem implementations.
818 if (events & ~POLLSTANDARD)
821 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
825 sys_pselect(struct thread *td, struct pselect_args *uap)
828 struct timeval tv, *tvp;
832 if (uap->ts != NULL) {
833 error = copyin(uap->ts, &ts, sizeof(ts));
836 TIMESPEC_TO_TIMEVAL(&tv, &ts);
840 if (uap->sm != NULL) {
841 error = copyin(uap->sm, &set, sizeof(set));
847 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
852 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
853 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
858 error = kern_sigprocmask(td, SIG_SETMASK, uset,
859 &td->td_oldsigmask, 0);
862 td->td_pflags |= TDP_OLDMASK;
864 * Make sure that ast() is called on return to
865 * usermode and TDP_OLDMASK is cleared, restoring old
869 td->td_flags |= TDF_ASTPENDING;
872 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
876 #ifndef _SYS_SYSPROTO_H_
879 fd_set *in, *ou, *ex;
884 sys_select(struct thread *td, struct select_args *uap)
886 struct timeval tv, *tvp;
889 if (uap->tv != NULL) {
890 error = copyin(uap->tv, &tv, sizeof(tv));
897 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
902 * In the unlikely case when user specified n greater then the last
903 * open file descriptor, check that no bits are set after the last
904 * valid fd. We must return EBADF if any is set.
906 * There are applications that rely on the behaviour.
908 * nd is fd_lastfile + 1.
911 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
917 if (nd >= ndu || fd_in == NULL)
921 bits = 0; /* silence gcc */
922 for (i = nd; i < ndu; i++) {
924 #if BYTE_ORDER == LITTLE_ENDIAN
925 addr = (char *)fd_in + b;
927 addr = (char *)fd_in;
928 if (abi_nfdbits == NFDBITS) {
929 addr += rounddown(b, sizeof(fd_mask)) +
930 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
932 addr += rounddown(b, sizeof(uint32_t)) +
933 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
943 if ((bits & (1 << (i % NBBY))) != 0)
950 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
951 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
953 struct filedesc *fdp;
955 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
956 * infds with the new FD_SETSIZE of 1024, and more than enough for
957 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
960 fd_mask s_selbits[howmany(2048, NFDBITS)];
961 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
963 sbintime_t asbt, precision, rsbt;
964 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
969 fdp = td->td_proc->p_fd;
971 lf = fdp->fd_lastfile;
975 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
978 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
981 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
986 * Allocate just enough bits for the non-null fd_sets. Use the
987 * preallocated auto buffer if possible.
989 nfdbits = roundup(nd, NFDBITS);
990 ncpbytes = nfdbits / NBBY;
991 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
994 nbufbytes += 2 * ncpbytes;
996 nbufbytes += 2 * ncpbytes;
998 nbufbytes += 2 * ncpbytes;
999 if (nbufbytes <= sizeof s_selbits)
1000 selbits = &s_selbits[0];
1002 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1005 * Assign pointers into the bit buffers and fetch the input bits.
1006 * Put the output buffers together so that they can be bzeroed
1010 #define getbits(name, x) \
1012 if (name == NULL) { \
1016 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1018 sbp += ncpbytes / sizeof *sbp; \
1019 error = copyin(name, ibits[x], ncpubytes); \
1022 bzero((char *)ibits[x] + ncpubytes, \
1023 ncpbytes - ncpubytes); \
1031 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1033 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1034 * we are running under 32-bit emulation. This should be more
1037 #define swizzle_fdset(bits) \
1038 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1040 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1041 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1044 #define swizzle_fdset(bits)
1047 /* Make sure the bit order makes it through an ABI transition */
1048 swizzle_fdset(ibits[0]);
1049 swizzle_fdset(ibits[1]);
1050 swizzle_fdset(ibits[2]);
1053 bzero(selbits, nbufbytes / 2);
1058 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1059 rtv.tv_usec >= 1000000) {
1063 if (!timevalisset(&rtv))
1065 else if (rtv.tv_sec <= INT32_MAX) {
1066 rsbt = tvtosbt(rtv);
1068 precision >>= tc_precexp;
1069 if (TIMESEL(&asbt, rsbt))
1070 asbt += tc_tick_sbt;
1071 if (asbt <= INT64_MAX - rsbt)
1080 /* Iterate until the timeout expires or descriptors become ready. */
1082 error = selscan(td, ibits, obits, nd);
1083 if (error || td->td_retval[0] != 0)
1085 error = seltdwait(td, asbt, precision);
1088 error = selrescan(td, ibits, obits);
1089 if (error || td->td_retval[0] != 0)
1095 /* select is not restarted after signals... */
1096 if (error == ERESTART)
1098 if (error == EWOULDBLOCK)
1101 /* swizzle bit order back, if necessary */
1102 swizzle_fdset(obits[0]);
1103 swizzle_fdset(obits[1]);
1104 swizzle_fdset(obits[2]);
1105 #undef swizzle_fdset
1107 #define putbits(name, x) \
1108 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1118 if (selbits != &s_selbits[0])
1119 free(selbits, M_SELECT);
1124 * Convert a select bit set to poll flags.
1126 * The backend always returns POLLHUP/POLLERR if appropriate and we
1127 * return this as a set bit in any set.
1129 static int select_flags[3] = {
1130 POLLRDNORM | POLLHUP | POLLERR,
1131 POLLWRNORM | POLLHUP | POLLERR,
1132 POLLRDBAND | POLLERR
1136 * Compute the fo_poll flags required for a fd given by the index and
1137 * bit position in the fd_mask array.
1140 selflags(fd_mask **ibits, int idx, fd_mask bit)
1146 for (msk = 0; msk < 3; msk++) {
1147 if (ibits[msk] == NULL)
1149 if ((ibits[msk][idx] & bit) == 0)
1151 flags |= select_flags[msk];
1157 * Set the appropriate output bits given a mask of fired events and the
1158 * input bits originally requested.
1161 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1167 for (msk = 0; msk < 3; msk++) {
1168 if ((events & select_flags[msk]) == 0)
1170 if (ibits[msk] == NULL)
1172 if ((ibits[msk][idx] & bit) == 0)
1175 * XXX Check for a duplicate set. This can occur because a
1176 * socket calls selrecord() twice for each poll() call
1177 * resulting in two selfds per real fd. selrescan() will
1178 * call selsetbits twice as a result.
1180 if ((obits[msk][idx] & bit) != 0)
1182 obits[msk][idx] |= bit;
1190 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1192 cap_rights_t rights;
1194 return (fget_unlocked(fdp, fd, cap_rights_init(&rights, CAP_POLL_EVENT),
1199 * Traverse the list of fds attached to this thread's seltd and check for
1203 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1205 struct filedesc *fdp;
1215 fdp = td->td_proc->p_fd;
1218 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1219 fd = (int)(uintptr_t)sfp->sf_cookie;
1221 selfdfree(stp, sfp);
1222 /* If the selinfo wasn't cleared the event didn't fire. */
1225 error = getselfd_cap(fdp, fd, &fp);
1229 bit = (fd_mask)1 << (fd % NFDBITS);
1230 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1233 n += selsetbits(ibits, obits, idx, bit, ev);
1236 td->td_retval[0] = n;
1241 * Perform the initial filedescriptor scan and register ourselves with
1245 selscan(td, ibits, obits, nfd)
1247 fd_mask **ibits, **obits;
1250 struct filedesc *fdp;
1253 int ev, flags, end, fd;
1257 fdp = td->td_proc->p_fd;
1259 for (idx = 0, fd = 0; fd < nfd; idx++) {
1260 end = imin(fd + NFDBITS, nfd);
1261 for (bit = 1; fd < end; bit <<= 1, fd++) {
1262 /* Compute the list of events we're interested in. */
1263 flags = selflags(ibits, idx, bit);
1266 error = getselfd_cap(fdp, fd, &fp);
1269 selfdalloc(td, (void *)(uintptr_t)fd);
1270 ev = fo_poll(fp, flags, td->td_ucred, td);
1273 n += selsetbits(ibits, obits, idx, bit, ev);
1277 td->td_retval[0] = n;
1281 #ifndef _SYS_SYSPROTO_H_
1291 struct poll_args *uap;
1293 struct pollfd *bits;
1294 struct pollfd smallbits[32];
1295 sbintime_t asbt, precision, rsbt;
1301 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1303 ni = nfds * sizeof(struct pollfd);
1304 if (ni > sizeof(smallbits))
1305 bits = malloc(ni, M_TEMP, M_WAITOK);
1308 error = copyin(uap->fds, bits, ni);
1312 if (uap->timeout != INFTIM) {
1313 if (uap->timeout < 0) {
1317 if (uap->timeout == 0)
1320 rsbt = SBT_1MS * uap->timeout;
1322 precision >>= tc_precexp;
1323 if (TIMESEL(&asbt, rsbt))
1324 asbt += tc_tick_sbt;
1330 /* Iterate until the timeout expires or descriptors become ready. */
1332 error = pollscan(td, bits, nfds);
1333 if (error || td->td_retval[0] != 0)
1335 error = seltdwait(td, asbt, precision);
1338 error = pollrescan(td);
1339 if (error || td->td_retval[0] != 0)
1345 /* poll is not restarted after signals... */
1346 if (error == ERESTART)
1348 if (error == EWOULDBLOCK)
1351 error = pollout(td, bits, uap->fds, nfds);
1356 if (ni > sizeof(smallbits))
1362 pollrescan(struct thread *td)
1368 struct filedesc *fdp;
1372 cap_rights_t rights;
1377 fdp = td->td_proc->p_fd;
1379 FILEDESC_SLOCK(fdp);
1380 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1381 fd = (struct pollfd *)sfp->sf_cookie;
1383 selfdfree(stp, sfp);
1384 /* If the selinfo wasn't cleared the event didn't fire. */
1387 fp = fdp->fd_ofiles[fd->fd].fde_file;
1390 cap_check(cap_rights(fdp, fd->fd),
1391 cap_rights_init(&rights, CAP_POLL_EVENT)) != 0)
1396 fd->revents = POLLNVAL;
1402 * Note: backend also returns POLLHUP and
1403 * POLLERR if appropriate.
1405 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1406 if (fd->revents != 0)
1409 FILEDESC_SUNLOCK(fdp);
1411 td->td_retval[0] = n;
1417 pollout(td, fds, ufds, nfd)
1420 struct pollfd *ufds;
1427 for (i = 0; i < nfd; i++) {
1428 error = copyout(&fds->revents, &ufds->revents,
1429 sizeof(ufds->revents));
1432 if (fds->revents != 0)
1437 td->td_retval[0] = n;
1442 pollscan(td, fds, nfd)
1447 struct filedesc *fdp = td->td_proc->p_fd;
1450 cap_rights_t rights;
1454 FILEDESC_SLOCK(fdp);
1455 for (i = 0; i < nfd; i++, fds++) {
1456 if (fds->fd >= fdp->fd_nfiles) {
1457 fds->revents = POLLNVAL;
1459 } else if (fds->fd < 0) {
1462 fp = fdp->fd_ofiles[fds->fd].fde_file;
1465 cap_check(cap_rights(fdp, fds->fd),
1466 cap_rights_init(&rights, CAP_POLL_EVENT)) != 0)
1471 fds->revents = POLLNVAL;
1475 * Note: backend also returns POLLHUP and
1476 * POLLERR if appropriate.
1478 selfdalloc(td, fds);
1479 fds->revents = fo_poll(fp, fds->events,
1482 * POSIX requires POLLOUT to be never
1483 * set simultaneously with POLLHUP.
1485 if ((fds->revents & POLLHUP) != 0)
1486 fds->revents &= ~POLLOUT;
1488 if (fds->revents != 0)
1493 FILEDESC_SUNLOCK(fdp);
1494 td->td_retval[0] = n;
1499 * OpenBSD poll system call.
1501 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1503 #ifndef _SYS_SYSPROTO_H_
1504 struct openbsd_poll_args {
1511 sys_openbsd_poll(td, uap)
1512 register struct thread *td;
1513 register struct openbsd_poll_args *uap;
1515 return (sys_poll(td, (struct poll_args *)uap));
1519 * XXX This was created specifically to support netncp and netsmb. This
1520 * allows the caller to specify a socket to wait for events on. It returns
1521 * 0 if any events matched and an error otherwise. There is no way to
1522 * determine which events fired.
1525 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1528 sbintime_t asbt, precision, rsbt;
1531 precision = 0; /* stupid gcc! */
1534 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1535 rtv.tv_usec >= 1000000)
1537 if (!timevalisset(&rtv))
1539 else if (rtv.tv_sec <= INT32_MAX) {
1540 rsbt = tvtosbt(rtv);
1542 precision >>= tc_precexp;
1543 if (TIMESEL(&asbt, rsbt))
1544 asbt += tc_tick_sbt;
1545 if (asbt <= INT64_MAX - rsbt)
1555 * Iterate until the timeout expires or the socket becomes ready.
1558 selfdalloc(td, NULL);
1559 error = sopoll(so, events, NULL, td);
1560 /* error here is actually the ready events. */
1563 error = seltdwait(td, asbt, precision);
1568 /* XXX Duplicates ncp/smb behavior. */
1569 if (error == ERESTART)
1575 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1576 * have two select sets, one for read and another for write.
1579 selfdalloc(struct thread *td, void *cookie)
1584 if (stp->st_free1 == NULL)
1585 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1586 stp->st_free1->sf_td = stp;
1587 stp->st_free1->sf_cookie = cookie;
1588 if (stp->st_free2 == NULL)
1589 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1590 stp->st_free2->sf_td = stp;
1591 stp->st_free2->sf_cookie = cookie;
1595 selfdfree(struct seltd *stp, struct selfd *sfp)
1597 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1598 mtx_lock(sfp->sf_mtx);
1600 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1601 mtx_unlock(sfp->sf_mtx);
1602 uma_zfree(selfd_zone, sfp);
1605 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1608 struct selinfo *sip;
1612 * This feature is already provided by doselwakeup(), thus it is
1613 * enough to go for it.
1614 * Eventually, the context, should take care to avoid races
1615 * between thread calling select()/poll() and file descriptor
1616 * detaching, but, again, the races are just the same as
1619 doselwakeup(sip, -1);
1623 * Record a select request.
1626 selrecord(selector, sip)
1627 struct thread *selector;
1628 struct selinfo *sip;
1634 stp = selector->td_sel;
1636 * Don't record when doing a rescan.
1638 if (stp->st_flags & SELTD_RESCAN)
1641 * Grab one of the preallocated descriptors.
1644 if ((sfp = stp->st_free1) != NULL)
1645 stp->st_free1 = NULL;
1646 else if ((sfp = stp->st_free2) != NULL)
1647 stp->st_free2 = NULL;
1649 panic("selrecord: No free selfd on selq");
1652 mtxp = mtx_pool_find(mtxpool_select, sip);
1654 * Initialize the sfp and queue it in the thread.
1658 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1660 * Now that we've locked the sip, check for initialization.
1663 if (sip->si_mtx == NULL) {
1665 TAILQ_INIT(&sip->si_tdlist);
1668 * Add this thread to the list of selfds listening on this selinfo.
1670 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1671 mtx_unlock(sip->si_mtx);
1674 /* Wake up a selecting thread. */
1677 struct selinfo *sip;
1679 doselwakeup(sip, -1);
1682 /* Wake up a selecting thread, and set its priority. */
1684 selwakeuppri(sip, pri)
1685 struct selinfo *sip;
1688 doselwakeup(sip, pri);
1692 * Do a wakeup when a selectable event occurs.
1695 doselwakeup(sip, pri)
1696 struct selinfo *sip;
1703 /* If it's not initialized there can't be any waiters. */
1704 if (sip->si_mtx == NULL)
1707 * Locking the selinfo locks all selfds associated with it.
1709 mtx_lock(sip->si_mtx);
1710 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1712 * Once we remove this sfp from the list and clear the
1713 * sf_si seltdclear will know to ignore this si.
1715 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1718 mtx_lock(&stp->st_mtx);
1719 stp->st_flags |= SELTD_PENDING;
1720 cv_broadcastpri(&stp->st_wait, pri);
1721 mtx_unlock(&stp->st_mtx);
1723 mtx_unlock(sip->si_mtx);
1727 seltdinit(struct thread *td)
1731 if ((stp = td->td_sel) != NULL)
1733 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1734 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1735 cv_init(&stp->st_wait, "select");
1738 STAILQ_INIT(&stp->st_selq);
1742 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1749 * An event of interest may occur while we do not hold the seltd
1750 * locked so check the pending flag before we sleep.
1752 mtx_lock(&stp->st_mtx);
1754 * Any further calls to selrecord will be a rescan.
1756 stp->st_flags |= SELTD_RESCAN;
1757 if (stp->st_flags & SELTD_PENDING) {
1758 mtx_unlock(&stp->st_mtx);
1762 error = EWOULDBLOCK;
1764 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1765 sbt, precision, C_ABSOLUTE);
1767 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1768 mtx_unlock(&stp->st_mtx);
1774 seltdfini(struct thread *td)
1782 uma_zfree(selfd_zone, stp->st_free1);
1784 uma_zfree(selfd_zone, stp->st_free2);
1786 free(stp, M_SELECT);
1790 * Remove the references to the thread from all of the objects we were
1794 seltdclear(struct thread *td)
1801 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1802 selfdfree(stp, sfp);
1806 static void selectinit(void *);
1807 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1809 selectinit(void *dummy __unused)
1812 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1813 NULL, NULL, UMA_ALIGN_PTR, 0);
1814 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);