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");
80 int devfs_iosize_max_clamp = 1;
81 SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
82 &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
85 * Assert that the return value of read(2) and write(2) syscalls fits
86 * into a register. If not, an architecture will need to provide the
87 * usermode wrappers to reconstruct the result.
89 CTASSERT(sizeof(register_t) >= sizeof(size_t));
91 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
92 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
93 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
95 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
97 static int pollscan(struct thread *, struct pollfd *, u_int);
98 static int pollrescan(struct thread *);
99 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
100 static int selrescan(struct thread *, fd_mask **, fd_mask **);
101 static void selfdalloc(struct thread *, void *);
102 static void selfdfree(struct seltd *, struct selfd *);
103 static int dofileread(struct thread *, int, struct file *, struct uio *,
105 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
107 static void doselwakeup(struct selinfo *, int);
108 static void seltdinit(struct thread *);
109 static int seltdwait(struct thread *, int);
110 static void seltdclear(struct thread *);
113 * One seltd per-thread allocated on demand as needed.
115 * t - protected by st_mtx
116 * k - Only accessed by curthread or read-only
119 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
120 struct selfd *st_free1; /* (k) free fd for read set. */
121 struct selfd *st_free2; /* (k) free fd for write set. */
122 struct mtx st_mtx; /* Protects struct seltd */
123 struct cv st_wait; /* (t) Wait channel. */
124 int st_flags; /* (t) SELTD_ flags. */
127 #define SELTD_PENDING 0x0001 /* We have pending events. */
128 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
131 * One selfd allocated per-thread per-file-descriptor.
132 * f - protected by sf_mtx
135 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
136 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
137 struct selinfo *sf_si; /* (f) selinfo when linked. */
138 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
139 struct seltd *sf_td; /* (k) owning seltd. */
140 void *sf_cookie; /* (k) fd or pollfd. */
143 static uma_zone_t selfd_zone;
144 static struct mtx_pool *mtxpool_select;
146 #ifndef _SYS_SYSPROTO_H_
156 struct read_args *uap;
162 if (uap->nbyte > IOSIZE_MAX)
164 aiov.iov_base = uap->buf;
165 aiov.iov_len = uap->nbyte;
166 auio.uio_iov = &aiov;
168 auio.uio_resid = uap->nbyte;
169 auio.uio_segflg = UIO_USERSPACE;
170 error = kern_readv(td, uap->fd, &auio);
175 * Positioned read system call
177 #ifndef _SYS_SYSPROTO_H_
189 struct pread_args *uap;
195 if (uap->nbyte > IOSIZE_MAX)
197 aiov.iov_base = uap->buf;
198 aiov.iov_len = uap->nbyte;
199 auio.uio_iov = &aiov;
201 auio.uio_resid = uap->nbyte;
202 auio.uio_segflg = UIO_USERSPACE;
203 error = kern_preadv(td, uap->fd, &auio, uap->offset);
208 freebsd6_pread(td, uap)
210 struct freebsd6_pread_args *uap;
212 struct pread_args oargs;
215 oargs.buf = uap->buf;
216 oargs.nbyte = uap->nbyte;
217 oargs.offset = uap->offset;
218 return (sys_pread(td, &oargs));
222 * Scatter read system call.
224 #ifndef _SYS_SYSPROTO_H_
232 sys_readv(struct thread *td, struct readv_args *uap)
237 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
240 error = kern_readv(td, uap->fd, auio);
246 kern_readv(struct thread *td, int fd, struct uio *auio)
251 error = fget_read(td, fd, CAP_READ | CAP_SEEK, &fp);
254 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
260 * Scatter positioned read system call.
262 #ifndef _SYS_SYSPROTO_H_
271 sys_preadv(struct thread *td, struct preadv_args *uap)
276 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
279 error = kern_preadv(td, uap->fd, auio, uap->offset);
285 kern_preadv(td, fd, auio, offset)
294 error = fget_read(td, fd, CAP_READ, &fp);
297 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
299 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
302 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
308 * Common code for readv and preadv that reads data in
309 * from a file using the passed in uio, offset, and flags.
312 dofileread(td, fd, fp, auio, offset, flags)
323 struct uio *ktruio = NULL;
326 /* Finish zero length reads right here */
327 if (auio->uio_resid == 0) {
328 td->td_retval[0] = 0;
331 auio->uio_rw = UIO_READ;
332 auio->uio_offset = offset;
335 if (KTRPOINT(td, KTR_GENIO))
336 ktruio = cloneuio(auio);
338 cnt = auio->uio_resid;
339 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
340 if (auio->uio_resid != cnt && (error == ERESTART ||
341 error == EINTR || error == EWOULDBLOCK))
344 cnt -= auio->uio_resid;
346 if (ktruio != NULL) {
347 ktruio->uio_resid = cnt;
348 ktrgenio(fd, UIO_READ, ktruio, error);
351 td->td_retval[0] = cnt;
355 #ifndef _SYS_SYSPROTO_H_
365 struct write_args *uap;
371 if (uap->nbyte > IOSIZE_MAX)
373 aiov.iov_base = (void *)(uintptr_t)uap->buf;
374 aiov.iov_len = uap->nbyte;
375 auio.uio_iov = &aiov;
377 auio.uio_resid = uap->nbyte;
378 auio.uio_segflg = UIO_USERSPACE;
379 error = kern_writev(td, uap->fd, &auio);
384 * Positioned write system call.
386 #ifndef _SYS_SYSPROTO_H_
398 struct pwrite_args *uap;
404 if (uap->nbyte > IOSIZE_MAX)
406 aiov.iov_base = (void *)(uintptr_t)uap->buf;
407 aiov.iov_len = uap->nbyte;
408 auio.uio_iov = &aiov;
410 auio.uio_resid = uap->nbyte;
411 auio.uio_segflg = UIO_USERSPACE;
412 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
417 freebsd6_pwrite(td, uap)
419 struct freebsd6_pwrite_args *uap;
421 struct pwrite_args oargs;
424 oargs.buf = uap->buf;
425 oargs.nbyte = uap->nbyte;
426 oargs.offset = uap->offset;
427 return (sys_pwrite(td, &oargs));
431 * Gather write system call.
433 #ifndef _SYS_SYSPROTO_H_
441 sys_writev(struct thread *td, struct writev_args *uap)
446 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
449 error = kern_writev(td, uap->fd, auio);
455 kern_writev(struct thread *td, int fd, struct uio *auio)
460 error = fget_write(td, fd, CAP_WRITE | CAP_SEEK, &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)
503 error = fget_write(td, fd, CAP_WRITE, &fp);
506 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
508 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
511 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
517 * Common code for writev and pwritev that writes data to
518 * a file using the passed in uio, offset, and flags.
521 dofilewrite(td, fd, fp, auio, offset, flags)
532 struct uio *ktruio = NULL;
535 auio->uio_rw = UIO_WRITE;
537 auio->uio_offset = offset;
539 if (KTRPOINT(td, KTR_GENIO))
540 ktruio = cloneuio(auio);
542 cnt = auio->uio_resid;
543 if (fp->f_type == DTYPE_VNODE &&
544 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
546 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
547 if (auio->uio_resid != cnt && (error == ERESTART ||
548 error == EINTR || error == EWOULDBLOCK))
550 /* Socket layer is responsible for issuing SIGPIPE. */
551 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
552 PROC_LOCK(td->td_proc);
553 tdsignal(td, SIGPIPE);
554 PROC_UNLOCK(td->td_proc);
557 cnt -= auio->uio_resid;
559 if (ktruio != NULL) {
560 ktruio->uio_resid = cnt;
561 ktrgenio(fd, UIO_WRITE, ktruio, error);
564 td->td_retval[0] = cnt;
569 * Truncate a file given a file descriptor.
571 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
572 * descriptor isn't writable.
575 kern_ftruncate(td, fd, length)
586 error = fget(td, fd, CAP_FTRUNCATE, &fp);
589 AUDIT_ARG_FILE(td->td_proc, fp);
590 if (!(fp->f_flag & FWRITE)) {
594 error = fo_truncate(fp, length, td->td_ucred, td);
599 #ifndef _SYS_SYSPROTO_H_
600 struct ftruncate_args {
607 sys_ftruncate(td, uap)
609 struct ftruncate_args *uap;
612 return (kern_ftruncate(td, uap->fd, uap->length));
615 #if defined(COMPAT_43)
616 #ifndef _SYS_SYSPROTO_H_
617 struct oftruncate_args {
625 struct oftruncate_args *uap;
628 return (kern_ftruncate(td, uap->fd, uap->length));
630 #endif /* COMPAT_43 */
632 #ifndef _SYS_SYSPROTO_H_
641 sys_ioctl(struct thread *td, struct ioctl_args *uap)
648 if (uap->com > 0xffffffff) {
650 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
651 td->td_proc->p_pid, td->td_name, uap->com);
652 uap->com &= 0xffffffff;
657 * Interpret high order word to find amount of data to be
658 * copied to/from the user's address space.
660 size = IOCPARM_LEN(com);
661 if ((size > IOCPARM_MAX) ||
662 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
663 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
664 ((com & IOC_OUT) && size == 0) ||
666 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
668 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
672 if (com & IOC_VOID) {
673 /* Integer argument. */
674 arg = (intptr_t)uap->data;
678 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
680 data = (void *)&uap->data;
682 error = copyin(uap->data, data, (u_int)size);
685 free(data, M_IOCTLOPS);
688 } else if (com & IOC_OUT) {
690 * Zero the buffer so the user always
691 * gets back something deterministic.
696 error = kern_ioctl(td, uap->fd, com, data);
698 if (error == 0 && (com & IOC_OUT))
699 error = copyout(data, uap->data, (u_int)size);
702 free(data, M_IOCTLOPS);
707 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
710 struct filedesc *fdp;
716 if ((error = fget(td, fd, CAP_IOCTL, &fp)) != 0)
718 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
722 fdp = td->td_proc->p_fd;
726 fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
727 FILEDESC_XUNLOCK(fdp);
731 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
732 FILEDESC_XUNLOCK(fdp);
735 if ((tmp = *(int *)data))
736 atomic_set_int(&fp->f_flag, FNONBLOCK);
738 atomic_clear_int(&fp->f_flag, FNONBLOCK);
742 if ((tmp = *(int *)data))
743 atomic_set_int(&fp->f_flag, FASYNC);
745 atomic_clear_int(&fp->f_flag, FASYNC);
750 error = fo_ioctl(fp, com, data, td->td_ucred, td);
757 poll_no_poll(int events)
760 * Return true for read/write. If the user asked for something
761 * special, return POLLNVAL, so that clients have a way of
762 * determining reliably whether or not the extended
763 * functionality is present without hard-coding knowledge
764 * of specific filesystem implementations.
766 if (events & ~POLLSTANDARD)
769 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
773 sys_pselect(struct thread *td, struct pselect_args *uap)
776 struct timeval tv, *tvp;
780 if (uap->ts != NULL) {
781 error = copyin(uap->ts, &ts, sizeof(ts));
784 TIMESPEC_TO_TIMEVAL(&tv, &ts);
788 if (uap->sm != NULL) {
789 error = copyin(uap->sm, &set, sizeof(set));
795 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
800 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
801 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
806 error = kern_sigprocmask(td, SIG_SETMASK, uset,
807 &td->td_oldsigmask, 0);
810 td->td_pflags |= TDP_OLDMASK;
812 * Make sure that ast() is called on return to
813 * usermode and TDP_OLDMASK is cleared, restoring old
817 td->td_flags |= TDF_ASTPENDING;
820 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
824 #ifndef _SYS_SYSPROTO_H_
827 fd_set *in, *ou, *ex;
832 sys_select(struct thread *td, struct select_args *uap)
834 struct timeval tv, *tvp;
837 if (uap->tv != NULL) {
838 error = copyin(uap->tv, &tv, sizeof(tv));
845 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
850 * In the unlikely case when user specified n greater then the last
851 * open file descriptor, check that no bits are set after the last
852 * valid fd. We must return EBADF if any is set.
854 * There are applications that rely on the behaviour.
856 * nd is fd_lastfile + 1.
859 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
865 if (nd >= ndu || fd_in == NULL)
869 bits = 0; /* silence gcc */
870 for (i = nd; i < ndu; i++) {
872 #if BYTE_ORDER == LITTLE_ENDIAN
873 addr = (char *)fd_in + b;
875 addr = (char *)fd_in;
876 if (abi_nfdbits == NFDBITS) {
877 addr += rounddown(b, sizeof(fd_mask)) +
878 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
880 addr += rounddown(b, sizeof(uint32_t)) +
881 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
891 if ((bits & (1 << (i % NBBY))) != 0)
898 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
899 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
901 struct filedesc *fdp;
903 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
904 * infds with the new FD_SETSIZE of 1024, and more than enough for
905 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
908 fd_mask s_selbits[howmany(2048, NFDBITS)];
909 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
910 struct timeval atv, rtv, ttv;
911 int error, lf, ndu, timo;
912 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
916 fdp = td->td_proc->p_fd;
918 lf = fdp->fd_lastfile;
922 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
925 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
928 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
933 * Allocate just enough bits for the non-null fd_sets. Use the
934 * preallocated auto buffer if possible.
936 nfdbits = roundup(nd, NFDBITS);
937 ncpbytes = nfdbits / NBBY;
938 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
941 nbufbytes += 2 * ncpbytes;
943 nbufbytes += 2 * ncpbytes;
945 nbufbytes += 2 * ncpbytes;
946 if (nbufbytes <= sizeof s_selbits)
947 selbits = &s_selbits[0];
949 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
952 * Assign pointers into the bit buffers and fetch the input bits.
953 * Put the output buffers together so that they can be bzeroed
957 #define getbits(name, x) \
959 if (name == NULL) { \
963 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
965 sbp += ncpbytes / sizeof *sbp; \
966 error = copyin(name, ibits[x], ncpubytes); \
969 bzero((char *)ibits[x] + ncpubytes, \
970 ncpbytes - ncpubytes); \
978 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
980 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
981 * we are running under 32-bit emulation. This should be more
984 #define swizzle_fdset(bits) \
985 if (abi_nfdbits != NFDBITS && bits != NULL) { \
987 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
988 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
991 #define swizzle_fdset(bits)
994 /* Make sure the bit order makes it through an ABI transition */
995 swizzle_fdset(ibits[0]);
996 swizzle_fdset(ibits[1]);
997 swizzle_fdset(ibits[2]);
1000 bzero(selbits, nbufbytes / 2);
1004 if (itimerfix(&atv)) {
1008 getmicrouptime(&rtv);
1009 timevaladd(&atv, &rtv);
1016 /* Iterate until the timeout expires or descriptors become ready. */
1018 error = selscan(td, ibits, obits, nd);
1019 if (error || td->td_retval[0] != 0)
1021 if (atv.tv_sec || atv.tv_usec) {
1022 getmicrouptime(&rtv);
1023 if (timevalcmp(&rtv, &atv, >=))
1026 timevalsub(&ttv, &rtv);
1027 timo = ttv.tv_sec > 24 * 60 * 60 ?
1028 24 * 60 * 60 * hz : tvtohz(&ttv);
1030 error = seltdwait(td, timo);
1033 error = selrescan(td, ibits, obits);
1034 if (error || td->td_retval[0] != 0)
1040 /* select is not restarted after signals... */
1041 if (error == ERESTART)
1043 if (error == EWOULDBLOCK)
1046 /* swizzle bit order back, if necessary */
1047 swizzle_fdset(obits[0]);
1048 swizzle_fdset(obits[1]);
1049 swizzle_fdset(obits[2]);
1050 #undef swizzle_fdset
1052 #define putbits(name, x) \
1053 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1063 if (selbits != &s_selbits[0])
1064 free(selbits, M_SELECT);
1069 * Convert a select bit set to poll flags.
1071 * The backend always returns POLLHUP/POLLERR if appropriate and we
1072 * return this as a set bit in any set.
1074 static int select_flags[3] = {
1075 POLLRDNORM | POLLHUP | POLLERR,
1076 POLLWRNORM | POLLHUP | POLLERR,
1077 POLLRDBAND | POLLERR
1081 * Compute the fo_poll flags required for a fd given by the index and
1082 * bit position in the fd_mask array.
1085 selflags(fd_mask **ibits, int idx, fd_mask bit)
1091 for (msk = 0; msk < 3; msk++) {
1092 if (ibits[msk] == NULL)
1094 if ((ibits[msk][idx] & bit) == 0)
1096 flags |= select_flags[msk];
1102 * Set the appropriate output bits given a mask of fired events and the
1103 * input bits originally requested.
1106 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1112 for (msk = 0; msk < 3; msk++) {
1113 if ((events & select_flags[msk]) == 0)
1115 if (ibits[msk] == NULL)
1117 if ((ibits[msk][idx] & bit) == 0)
1120 * XXX Check for a duplicate set. This can occur because a
1121 * socket calls selrecord() twice for each poll() call
1122 * resulting in two selfds per real fd. selrescan() will
1123 * call selsetbits twice as a result.
1125 if ((obits[msk][idx] & bit) != 0)
1127 obits[msk][idx] |= bit;
1135 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1139 struct file *fp_fromcap;
1143 if ((fp = fget_unlocked(fdp, fd)) == NULL)
1147 * If the file descriptor is for a capability, test rights and use
1148 * the file descriptor references by the capability.
1150 error = cap_funwrap(fp, CAP_POLL_EVENT, &fp_fromcap);
1152 fdrop(fp, curthread);
1155 if (fp != fp_fromcap) {
1157 fdrop(fp, curthread);
1160 #endif /* CAPABILITIES */
1166 * Traverse the list of fds attached to this thread's seltd and check for
1170 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1172 struct filedesc *fdp;
1182 fdp = td->td_proc->p_fd;
1185 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1186 fd = (int)(uintptr_t)sfp->sf_cookie;
1188 selfdfree(stp, sfp);
1189 /* If the selinfo wasn't cleared the event didn't fire. */
1192 error = getselfd_cap(fdp, fd, &fp);
1196 bit = (fd_mask)1 << (fd % NFDBITS);
1197 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1200 n += selsetbits(ibits, obits, idx, bit, ev);
1203 td->td_retval[0] = n;
1208 * Perform the initial filedescriptor scan and register ourselves with
1212 selscan(td, ibits, obits, nfd)
1214 fd_mask **ibits, **obits;
1217 struct filedesc *fdp;
1220 int ev, flags, end, fd;
1224 fdp = td->td_proc->p_fd;
1226 for (idx = 0, fd = 0; fd < nfd; idx++) {
1227 end = imin(fd + NFDBITS, nfd);
1228 for (bit = 1; fd < end; bit <<= 1, fd++) {
1229 /* Compute the list of events we're interested in. */
1230 flags = selflags(ibits, idx, bit);
1233 error = getselfd_cap(fdp, fd, &fp);
1236 selfdalloc(td, (void *)(uintptr_t)fd);
1237 ev = fo_poll(fp, flags, td->td_ucred, td);
1240 n += selsetbits(ibits, obits, idx, bit, ev);
1244 td->td_retval[0] = n;
1248 #ifndef _SYS_SYSPROTO_H_
1258 struct poll_args *uap;
1260 struct pollfd *bits;
1261 struct pollfd smallbits[32];
1262 struct timeval atv, rtv, ttv;
1268 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1270 ni = nfds * sizeof(struct pollfd);
1271 if (ni > sizeof(smallbits))
1272 bits = malloc(ni, M_TEMP, M_WAITOK);
1275 error = copyin(uap->fds, bits, ni);
1278 if (uap->timeout != INFTIM) {
1279 atv.tv_sec = uap->timeout / 1000;
1280 atv.tv_usec = (uap->timeout % 1000) * 1000;
1281 if (itimerfix(&atv)) {
1285 getmicrouptime(&rtv);
1286 timevaladd(&atv, &rtv);
1293 /* Iterate until the timeout expires or descriptors become ready. */
1295 error = pollscan(td, bits, nfds);
1296 if (error || td->td_retval[0] != 0)
1298 if (atv.tv_sec || atv.tv_usec) {
1299 getmicrouptime(&rtv);
1300 if (timevalcmp(&rtv, &atv, >=))
1303 timevalsub(&ttv, &rtv);
1304 timo = ttv.tv_sec > 24 * 60 * 60 ?
1305 24 * 60 * 60 * hz : tvtohz(&ttv);
1307 error = seltdwait(td, timo);
1310 error = pollrescan(td);
1311 if (error || td->td_retval[0] != 0)
1317 /* poll is not restarted after signals... */
1318 if (error == ERESTART)
1320 if (error == EWOULDBLOCK)
1323 error = pollout(td, bits, uap->fds, nfds);
1328 if (ni > sizeof(smallbits))
1334 pollrescan(struct thread *td)
1340 struct filedesc *fdp;
1346 fdp = td->td_proc->p_fd;
1348 FILEDESC_SLOCK(fdp);
1349 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1350 fd = (struct pollfd *)sfp->sf_cookie;
1352 selfdfree(stp, sfp);
1353 /* If the selinfo wasn't cleared the event didn't fire. */
1356 fp = fdp->fd_ofiles[fd->fd];
1359 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1363 fd->revents = POLLNVAL;
1369 * Note: backend also returns POLLHUP and
1370 * POLLERR if appropriate.
1372 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1373 if (fd->revents != 0)
1376 FILEDESC_SUNLOCK(fdp);
1378 td->td_retval[0] = n;
1384 pollout(td, fds, ufds, nfd)
1387 struct pollfd *ufds;
1394 for (i = 0; i < nfd; i++) {
1395 error = copyout(&fds->revents, &ufds->revents,
1396 sizeof(ufds->revents));
1399 if (fds->revents != 0)
1404 td->td_retval[0] = n;
1409 pollscan(td, fds, nfd)
1414 struct filedesc *fdp = td->td_proc->p_fd;
1419 FILEDESC_SLOCK(fdp);
1420 for (i = 0; i < nfd; i++, fds++) {
1421 if (fds->fd >= fdp->fd_nfiles) {
1422 fds->revents = POLLNVAL;
1424 } else if (fds->fd < 0) {
1427 fp = fdp->fd_ofiles[fds->fd];
1430 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1434 fds->revents = POLLNVAL;
1438 * Note: backend also returns POLLHUP and
1439 * POLLERR if appropriate.
1441 selfdalloc(td, fds);
1442 fds->revents = fo_poll(fp, fds->events,
1445 * POSIX requires POLLOUT to be never
1446 * set simultaneously with POLLHUP.
1448 if ((fds->revents & POLLHUP) != 0)
1449 fds->revents &= ~POLLOUT;
1451 if (fds->revents != 0)
1456 FILEDESC_SUNLOCK(fdp);
1457 td->td_retval[0] = n;
1462 * OpenBSD poll system call.
1464 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1466 #ifndef _SYS_SYSPROTO_H_
1467 struct openbsd_poll_args {
1474 sys_openbsd_poll(td, uap)
1475 register struct thread *td;
1476 register struct openbsd_poll_args *uap;
1478 return (sys_poll(td, (struct poll_args *)uap));
1482 * XXX This was created specifically to support netncp and netsmb. This
1483 * allows the caller to specify a socket to wait for events on. It returns
1484 * 0 if any events matched and an error otherwise. There is no way to
1485 * determine which events fired.
1488 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1490 struct timeval atv, rtv, ttv;
1495 if (itimerfix(&atv))
1497 getmicrouptime(&rtv);
1498 timevaladd(&atv, &rtv);
1507 * Iterate until the timeout expires or the socket becomes ready.
1510 selfdalloc(td, NULL);
1511 error = sopoll(so, events, NULL, td);
1512 /* error here is actually the ready events. */
1515 if (atv.tv_sec || atv.tv_usec) {
1516 getmicrouptime(&rtv);
1517 if (timevalcmp(&rtv, &atv, >=)) {
1519 return (EWOULDBLOCK);
1522 timevalsub(&ttv, &rtv);
1523 timo = ttv.tv_sec > 24 * 60 * 60 ?
1524 24 * 60 * 60 * hz : tvtohz(&ttv);
1526 error = seltdwait(td, timo);
1531 /* XXX Duplicates ncp/smb behavior. */
1532 if (error == ERESTART)
1538 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1539 * have two select sets, one for read and another for write.
1542 selfdalloc(struct thread *td, void *cookie)
1547 if (stp->st_free1 == NULL)
1548 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1549 stp->st_free1->sf_td = stp;
1550 stp->st_free1->sf_cookie = cookie;
1551 if (stp->st_free2 == NULL)
1552 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1553 stp->st_free2->sf_td = stp;
1554 stp->st_free2->sf_cookie = cookie;
1558 selfdfree(struct seltd *stp, struct selfd *sfp)
1560 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1561 mtx_lock(sfp->sf_mtx);
1563 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1564 mtx_unlock(sfp->sf_mtx);
1565 uma_zfree(selfd_zone, sfp);
1568 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1571 struct selinfo *sip;
1575 * This feature is already provided by doselwakeup(), thus it is
1576 * enough to go for it.
1577 * Eventually, the context, should take care to avoid races
1578 * between thread calling select()/poll() and file descriptor
1579 * detaching, but, again, the races are just the same as
1582 doselwakeup(sip, -1);
1586 * Record a select request.
1589 selrecord(selector, sip)
1590 struct thread *selector;
1591 struct selinfo *sip;
1597 stp = selector->td_sel;
1599 * Don't record when doing a rescan.
1601 if (stp->st_flags & SELTD_RESCAN)
1604 * Grab one of the preallocated descriptors.
1607 if ((sfp = stp->st_free1) != NULL)
1608 stp->st_free1 = NULL;
1609 else if ((sfp = stp->st_free2) != NULL)
1610 stp->st_free2 = NULL;
1612 panic("selrecord: No free selfd on selq");
1615 mtxp = mtx_pool_find(mtxpool_select, sip);
1617 * Initialize the sfp and queue it in the thread.
1621 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1623 * Now that we've locked the sip, check for initialization.
1626 if (sip->si_mtx == NULL) {
1628 TAILQ_INIT(&sip->si_tdlist);
1631 * Add this thread to the list of selfds listening on this selinfo.
1633 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1634 mtx_unlock(sip->si_mtx);
1637 /* Wake up a selecting thread. */
1640 struct selinfo *sip;
1642 doselwakeup(sip, -1);
1645 /* Wake up a selecting thread, and set its priority. */
1647 selwakeuppri(sip, pri)
1648 struct selinfo *sip;
1651 doselwakeup(sip, pri);
1655 * Do a wakeup when a selectable event occurs.
1658 doselwakeup(sip, pri)
1659 struct selinfo *sip;
1666 /* If it's not initialized there can't be any waiters. */
1667 if (sip->si_mtx == NULL)
1670 * Locking the selinfo locks all selfds associated with it.
1672 mtx_lock(sip->si_mtx);
1673 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1675 * Once we remove this sfp from the list and clear the
1676 * sf_si seltdclear will know to ignore this si.
1678 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1681 mtx_lock(&stp->st_mtx);
1682 stp->st_flags |= SELTD_PENDING;
1683 cv_broadcastpri(&stp->st_wait, pri);
1684 mtx_unlock(&stp->st_mtx);
1686 mtx_unlock(sip->si_mtx);
1690 seltdinit(struct thread *td)
1694 if ((stp = td->td_sel) != NULL)
1696 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1697 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1698 cv_init(&stp->st_wait, "select");
1701 STAILQ_INIT(&stp->st_selq);
1705 seltdwait(struct thread *td, int timo)
1712 * An event of interest may occur while we do not hold the seltd
1713 * locked so check the pending flag before we sleep.
1715 mtx_lock(&stp->st_mtx);
1717 * Any further calls to selrecord will be a rescan.
1719 stp->st_flags |= SELTD_RESCAN;
1720 if (stp->st_flags & SELTD_PENDING) {
1721 mtx_unlock(&stp->st_mtx);
1725 error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1727 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1728 mtx_unlock(&stp->st_mtx);
1734 seltdfini(struct thread *td)
1742 uma_zfree(selfd_zone, stp->st_free1);
1744 uma_zfree(selfd_zone, stp->st_free2);
1746 free(stp, M_SELECT);
1750 * Remove the references to the thread from all of the objects we were
1754 seltdclear(struct thread *td)
1761 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1762 selfdfree(stp, sfp);
1766 static void selectinit(void *);
1767 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1769 selectinit(void *dummy __unused)
1772 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1773 NULL, NULL, UMA_ALIGN_PTR, 0);
1774 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);