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)
248 error = fget_read(td, fd, CAP_READ, &fp);
251 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
257 * Scatter positioned read system call.
259 #ifndef _SYS_SYSPROTO_H_
268 sys_preadv(struct thread *td, struct preadv_args *uap)
273 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
276 error = kern_preadv(td, uap->fd, auio, uap->offset);
282 kern_preadv(td, fd, auio, offset)
291 error = fget_read(td, fd, CAP_PREAD, &fp);
294 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
296 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
299 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
305 * Common code for readv and preadv that reads data in
306 * from a file using the passed in uio, offset, and flags.
309 dofileread(td, fd, fp, auio, offset, flags)
320 struct uio *ktruio = NULL;
323 /* Finish zero length reads right here */
324 if (auio->uio_resid == 0) {
325 td->td_retval[0] = 0;
328 auio->uio_rw = UIO_READ;
329 auio->uio_offset = offset;
332 if (KTRPOINT(td, KTR_GENIO))
333 ktruio = cloneuio(auio);
335 cnt = auio->uio_resid;
336 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
337 if (auio->uio_resid != cnt && (error == ERESTART ||
338 error == EINTR || error == EWOULDBLOCK))
341 cnt -= auio->uio_resid;
343 if (ktruio != NULL) {
344 ktruio->uio_resid = cnt;
345 ktrgenio(fd, UIO_READ, ktruio, error);
348 td->td_retval[0] = cnt;
352 #ifndef _SYS_SYSPROTO_H_
362 struct write_args *uap;
368 if (uap->nbyte > IOSIZE_MAX)
370 aiov.iov_base = (void *)(uintptr_t)uap->buf;
371 aiov.iov_len = uap->nbyte;
372 auio.uio_iov = &aiov;
374 auio.uio_resid = uap->nbyte;
375 auio.uio_segflg = UIO_USERSPACE;
376 error = kern_writev(td, uap->fd, &auio);
381 * Positioned write system call.
383 #ifndef _SYS_SYSPROTO_H_
395 struct pwrite_args *uap;
401 if (uap->nbyte > IOSIZE_MAX)
403 aiov.iov_base = (void *)(uintptr_t)uap->buf;
404 aiov.iov_len = uap->nbyte;
405 auio.uio_iov = &aiov;
407 auio.uio_resid = uap->nbyte;
408 auio.uio_segflg = UIO_USERSPACE;
409 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
414 freebsd6_pwrite(td, uap)
416 struct freebsd6_pwrite_args *uap;
418 struct pwrite_args oargs;
421 oargs.buf = uap->buf;
422 oargs.nbyte = uap->nbyte;
423 oargs.offset = uap->offset;
424 return (sys_pwrite(td, &oargs));
428 * Gather write system call.
430 #ifndef _SYS_SYSPROTO_H_
438 sys_writev(struct thread *td, struct writev_args *uap)
443 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
446 error = kern_writev(td, uap->fd, auio);
452 kern_writev(struct thread *td, int fd, struct uio *auio)
457 error = fget_write(td, fd, CAP_WRITE, &fp);
460 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
466 * Gather positioned write system call.
468 #ifndef _SYS_SYSPROTO_H_
469 struct pwritev_args {
477 sys_pwritev(struct thread *td, struct pwritev_args *uap)
482 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
485 error = kern_pwritev(td, uap->fd, auio, uap->offset);
491 kern_pwritev(td, fd, auio, offset)
500 error = fget_write(td, fd, CAP_PWRITE, &fp);
503 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
505 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
508 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
514 * Common code for writev and pwritev that writes data to
515 * a file using the passed in uio, offset, and flags.
518 dofilewrite(td, fd, fp, auio, offset, flags)
529 struct uio *ktruio = NULL;
532 auio->uio_rw = UIO_WRITE;
534 auio->uio_offset = offset;
536 if (KTRPOINT(td, KTR_GENIO))
537 ktruio = cloneuio(auio);
539 cnt = auio->uio_resid;
540 if (fp->f_type == DTYPE_VNODE &&
541 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
543 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
544 if (auio->uio_resid != cnt && (error == ERESTART ||
545 error == EINTR || error == EWOULDBLOCK))
547 /* Socket layer is responsible for issuing SIGPIPE. */
548 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
549 PROC_LOCK(td->td_proc);
550 tdsignal(td, SIGPIPE);
551 PROC_UNLOCK(td->td_proc);
554 cnt -= auio->uio_resid;
556 if (ktruio != NULL) {
557 ktruio->uio_resid = cnt;
558 ktrgenio(fd, UIO_WRITE, ktruio, error);
561 td->td_retval[0] = cnt;
566 * Truncate a file given a file descriptor.
568 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
569 * descriptor isn't writable.
572 kern_ftruncate(td, fd, length)
583 error = fget(td, fd, CAP_FTRUNCATE, &fp);
586 AUDIT_ARG_FILE(td->td_proc, fp);
587 if (!(fp->f_flag & FWRITE)) {
591 error = fo_truncate(fp, length, td->td_ucred, td);
596 #ifndef _SYS_SYSPROTO_H_
597 struct ftruncate_args {
604 sys_ftruncate(td, uap)
606 struct ftruncate_args *uap;
609 return (kern_ftruncate(td, uap->fd, uap->length));
612 #if defined(COMPAT_43)
613 #ifndef _SYS_SYSPROTO_H_
614 struct oftruncate_args {
622 struct oftruncate_args *uap;
625 return (kern_ftruncate(td, uap->fd, uap->length));
627 #endif /* COMPAT_43 */
629 #ifndef _SYS_SYSPROTO_H_
638 sys_ioctl(struct thread *td, struct ioctl_args *uap)
645 if (uap->com > 0xffffffff) {
647 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
648 td->td_proc->p_pid, td->td_name, uap->com);
649 uap->com &= 0xffffffff;
654 * Interpret high order word to find amount of data to be
655 * copied to/from the user's address space.
657 size = IOCPARM_LEN(com);
658 if ((size > IOCPARM_MAX) ||
659 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
660 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
661 ((com & IOC_OUT) && size == 0) ||
663 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
665 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
669 if (com & IOC_VOID) {
670 /* Integer argument. */
671 arg = (intptr_t)uap->data;
675 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
677 data = (void *)&uap->data;
679 error = copyin(uap->data, data, (u_int)size);
682 free(data, M_IOCTLOPS);
685 } else if (com & IOC_OUT) {
687 * Zero the buffer so the user always
688 * gets back something deterministic.
693 error = kern_ioctl(td, uap->fd, com, data);
695 if (error == 0 && (com & IOC_OUT))
696 error = copyout(data, uap->data, (u_int)size);
699 free(data, M_IOCTLOPS);
704 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
707 struct filedesc *fdp;
708 int error, tmp, locked;
713 fdp = td->td_proc->p_fd;
726 locked = LA_UNLOCKED;
732 if ((fp = fget_locked(fdp, fd)) == NULL) {
736 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
737 fp = NULL; /* fhold() was not called yet */
741 if (locked == LA_SLOCKED) {
742 FILEDESC_SUNLOCK(fdp);
743 locked = LA_UNLOCKED;
746 if ((error = fget(td, fd, CAP_IOCTL, &fp)) != 0) {
751 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
758 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
761 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
764 if ((tmp = *(int *)data))
765 atomic_set_int(&fp->f_flag, FNONBLOCK);
767 atomic_clear_int(&fp->f_flag, FNONBLOCK);
771 if ((tmp = *(int *)data))
772 atomic_set_int(&fp->f_flag, FASYNC);
774 atomic_clear_int(&fp->f_flag, FASYNC);
779 error = fo_ioctl(fp, com, data, td->td_ucred, td);
783 FILEDESC_XUNLOCK(fdp);
787 FILEDESC_SUNLOCK(fdp);
791 FILEDESC_UNLOCK_ASSERT(fdp);
800 poll_no_poll(int events)
803 * Return true for read/write. If the user asked for something
804 * special, return POLLNVAL, so that clients have a way of
805 * determining reliably whether or not the extended
806 * functionality is present without hard-coding knowledge
807 * of specific filesystem implementations.
809 if (events & ~POLLSTANDARD)
812 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
816 sys_pselect(struct thread *td, struct pselect_args *uap)
819 struct timeval tv, *tvp;
823 if (uap->ts != NULL) {
824 error = copyin(uap->ts, &ts, sizeof(ts));
827 TIMESPEC_TO_TIMEVAL(&tv, &ts);
831 if (uap->sm != NULL) {
832 error = copyin(uap->sm, &set, sizeof(set));
838 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
843 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
844 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
849 error = kern_sigprocmask(td, SIG_SETMASK, uset,
850 &td->td_oldsigmask, 0);
853 td->td_pflags |= TDP_OLDMASK;
855 * Make sure that ast() is called on return to
856 * usermode and TDP_OLDMASK is cleared, restoring old
860 td->td_flags |= TDF_ASTPENDING;
863 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
867 #ifndef _SYS_SYSPROTO_H_
870 fd_set *in, *ou, *ex;
875 sys_select(struct thread *td, struct select_args *uap)
877 struct timeval tv, *tvp;
880 if (uap->tv != NULL) {
881 error = copyin(uap->tv, &tv, sizeof(tv));
888 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
893 * In the unlikely case when user specified n greater then the last
894 * open file descriptor, check that no bits are set after the last
895 * valid fd. We must return EBADF if any is set.
897 * There are applications that rely on the behaviour.
899 * nd is fd_lastfile + 1.
902 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
908 if (nd >= ndu || fd_in == NULL)
912 bits = 0; /* silence gcc */
913 for (i = nd; i < ndu; i++) {
915 #if BYTE_ORDER == LITTLE_ENDIAN
916 addr = (char *)fd_in + b;
918 addr = (char *)fd_in;
919 if (abi_nfdbits == NFDBITS) {
920 addr += rounddown(b, sizeof(fd_mask)) +
921 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
923 addr += rounddown(b, sizeof(uint32_t)) +
924 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
934 if ((bits & (1 << (i % NBBY))) != 0)
941 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
942 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
944 struct filedesc *fdp;
946 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
947 * infds with the new FD_SETSIZE of 1024, and more than enough for
948 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
951 fd_mask s_selbits[howmany(2048, NFDBITS)];
952 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
954 sbintime_t asbt, precision, rsbt;
955 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
960 fdp = td->td_proc->p_fd;
962 lf = fdp->fd_lastfile;
966 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
969 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
972 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
977 * Allocate just enough bits for the non-null fd_sets. Use the
978 * preallocated auto buffer if possible.
980 nfdbits = roundup(nd, NFDBITS);
981 ncpbytes = nfdbits / NBBY;
982 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
985 nbufbytes += 2 * ncpbytes;
987 nbufbytes += 2 * ncpbytes;
989 nbufbytes += 2 * ncpbytes;
990 if (nbufbytes <= sizeof s_selbits)
991 selbits = &s_selbits[0];
993 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
996 * Assign pointers into the bit buffers and fetch the input bits.
997 * Put the output buffers together so that they can be bzeroed
1001 #define getbits(name, x) \
1003 if (name == NULL) { \
1007 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1009 sbp += ncpbytes / sizeof *sbp; \
1010 error = copyin(name, ibits[x], ncpubytes); \
1013 bzero((char *)ibits[x] + ncpubytes, \
1014 ncpbytes - ncpubytes); \
1022 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1024 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1025 * we are running under 32-bit emulation. This should be more
1028 #define swizzle_fdset(bits) \
1029 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1031 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1032 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1035 #define swizzle_fdset(bits)
1038 /* Make sure the bit order makes it through an ABI transition */
1039 swizzle_fdset(ibits[0]);
1040 swizzle_fdset(ibits[1]);
1041 swizzle_fdset(ibits[2]);
1044 bzero(selbits, nbufbytes / 2);
1049 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1050 rtv.tv_usec >= 1000000) {
1054 if (!timevalisset(&rtv))
1056 else if (rtv.tv_sec <= INT32_MAX) {
1057 rsbt = tvtosbt(rtv);
1059 precision >>= tc_precexp;
1060 if (TIMESEL(&asbt, rsbt))
1061 asbt += tc_tick_sbt;
1062 if (asbt <= INT64_MAX - rsbt)
1071 /* Iterate until the timeout expires or descriptors become ready. */
1073 error = selscan(td, ibits, obits, nd);
1074 if (error || td->td_retval[0] != 0)
1076 error = seltdwait(td, asbt, precision);
1079 error = selrescan(td, ibits, obits);
1080 if (error || td->td_retval[0] != 0)
1086 /* select is not restarted after signals... */
1087 if (error == ERESTART)
1089 if (error == EWOULDBLOCK)
1092 /* swizzle bit order back, if necessary */
1093 swizzle_fdset(obits[0]);
1094 swizzle_fdset(obits[1]);
1095 swizzle_fdset(obits[2]);
1096 #undef swizzle_fdset
1098 #define putbits(name, x) \
1099 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1109 if (selbits != &s_selbits[0])
1110 free(selbits, M_SELECT);
1115 * Convert a select bit set to poll flags.
1117 * The backend always returns POLLHUP/POLLERR if appropriate and we
1118 * return this as a set bit in any set.
1120 static int select_flags[3] = {
1121 POLLRDNORM | POLLHUP | POLLERR,
1122 POLLWRNORM | POLLHUP | POLLERR,
1123 POLLRDBAND | POLLERR
1127 * Compute the fo_poll flags required for a fd given by the index and
1128 * bit position in the fd_mask array.
1131 selflags(fd_mask **ibits, int idx, fd_mask bit)
1137 for (msk = 0; msk < 3; msk++) {
1138 if (ibits[msk] == NULL)
1140 if ((ibits[msk][idx] & bit) == 0)
1142 flags |= select_flags[msk];
1148 * Set the appropriate output bits given a mask of fired events and the
1149 * input bits originally requested.
1152 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1158 for (msk = 0; msk < 3; msk++) {
1159 if ((events & select_flags[msk]) == 0)
1161 if (ibits[msk] == NULL)
1163 if ((ibits[msk][idx] & bit) == 0)
1166 * XXX Check for a duplicate set. This can occur because a
1167 * socket calls selrecord() twice for each poll() call
1168 * resulting in two selfds per real fd. selrescan() will
1169 * call selsetbits twice as a result.
1171 if ((obits[msk][idx] & bit) != 0)
1173 obits[msk][idx] |= bit;
1181 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1184 return (fget_unlocked(fdp, fd, CAP_POLL_EVENT, 0, fpp, NULL));
1188 * Traverse the list of fds attached to this thread's seltd and check for
1192 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1194 struct filedesc *fdp;
1204 fdp = td->td_proc->p_fd;
1207 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1208 fd = (int)(uintptr_t)sfp->sf_cookie;
1210 selfdfree(stp, sfp);
1211 /* If the selinfo wasn't cleared the event didn't fire. */
1214 error = getselfd_cap(fdp, fd, &fp);
1218 bit = (fd_mask)1 << (fd % NFDBITS);
1219 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1222 n += selsetbits(ibits, obits, idx, bit, ev);
1225 td->td_retval[0] = n;
1230 * Perform the initial filedescriptor scan and register ourselves with
1234 selscan(td, ibits, obits, nfd)
1236 fd_mask **ibits, **obits;
1239 struct filedesc *fdp;
1242 int ev, flags, end, fd;
1246 fdp = td->td_proc->p_fd;
1248 for (idx = 0, fd = 0; fd < nfd; idx++) {
1249 end = imin(fd + NFDBITS, nfd);
1250 for (bit = 1; fd < end; bit <<= 1, fd++) {
1251 /* Compute the list of events we're interested in. */
1252 flags = selflags(ibits, idx, bit);
1255 error = getselfd_cap(fdp, fd, &fp);
1258 selfdalloc(td, (void *)(uintptr_t)fd);
1259 ev = fo_poll(fp, flags, td->td_ucred, td);
1262 n += selsetbits(ibits, obits, idx, bit, ev);
1266 td->td_retval[0] = n;
1270 #ifndef _SYS_SYSPROTO_H_
1280 struct poll_args *uap;
1282 struct pollfd *bits;
1283 struct pollfd smallbits[32];
1284 sbintime_t asbt, precision, rsbt;
1290 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1292 ni = nfds * sizeof(struct pollfd);
1293 if (ni > sizeof(smallbits))
1294 bits = malloc(ni, M_TEMP, M_WAITOK);
1297 error = copyin(uap->fds, bits, ni);
1301 if (uap->timeout != INFTIM) {
1302 if (uap->timeout < 0) {
1306 if (uap->timeout == 0)
1309 rsbt = SBT_1MS * uap->timeout;
1311 precision >>= tc_precexp;
1312 if (TIMESEL(&asbt, rsbt))
1313 asbt += tc_tick_sbt;
1319 /* Iterate until the timeout expires or descriptors become ready. */
1321 error = pollscan(td, bits, nfds);
1322 if (error || td->td_retval[0] != 0)
1324 error = seltdwait(td, asbt, precision);
1327 error = pollrescan(td);
1328 if (error || td->td_retval[0] != 0)
1334 /* poll is not restarted after signals... */
1335 if (error == ERESTART)
1337 if (error == EWOULDBLOCK)
1340 error = pollout(td, bits, uap->fds, nfds);
1345 if (ni > sizeof(smallbits))
1351 pollrescan(struct thread *td)
1357 struct filedesc *fdp;
1363 fdp = td->td_proc->p_fd;
1365 FILEDESC_SLOCK(fdp);
1366 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1367 fd = (struct pollfd *)sfp->sf_cookie;
1369 selfdfree(stp, sfp);
1370 /* If the selinfo wasn't cleared the event didn't fire. */
1373 fp = fdp->fd_ofiles[fd->fd].fde_file;
1376 cap_check(cap_rights(fdp, fd->fd), CAP_POLL_EVENT) != 0)
1381 fd->revents = POLLNVAL;
1387 * Note: backend also returns POLLHUP and
1388 * POLLERR if appropriate.
1390 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1391 if (fd->revents != 0)
1394 FILEDESC_SUNLOCK(fdp);
1396 td->td_retval[0] = n;
1402 pollout(td, fds, ufds, nfd)
1405 struct pollfd *ufds;
1412 for (i = 0; i < nfd; i++) {
1413 error = copyout(&fds->revents, &ufds->revents,
1414 sizeof(ufds->revents));
1417 if (fds->revents != 0)
1422 td->td_retval[0] = n;
1427 pollscan(td, fds, nfd)
1432 struct filedesc *fdp = td->td_proc->p_fd;
1436 FILEDESC_SLOCK(fdp);
1437 for (i = 0; i < nfd; i++, fds++) {
1438 if (fds->fd >= fdp->fd_nfiles) {
1439 fds->revents = POLLNVAL;
1441 } else if (fds->fd < 0) {
1444 fp = fdp->fd_ofiles[fds->fd].fde_file;
1447 cap_check(cap_rights(fdp, fds->fd),
1448 CAP_POLL_EVENT) != 0)
1453 fds->revents = POLLNVAL;
1457 * Note: backend also returns POLLHUP and
1458 * POLLERR if appropriate.
1460 selfdalloc(td, fds);
1461 fds->revents = fo_poll(fp, fds->events,
1464 * POSIX requires POLLOUT to be never
1465 * set simultaneously with POLLHUP.
1467 if ((fds->revents & POLLHUP) != 0)
1468 fds->revents &= ~POLLOUT;
1470 if (fds->revents != 0)
1475 FILEDESC_SUNLOCK(fdp);
1476 td->td_retval[0] = n;
1481 * OpenBSD poll system call.
1483 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1485 #ifndef _SYS_SYSPROTO_H_
1486 struct openbsd_poll_args {
1493 sys_openbsd_poll(td, uap)
1494 register struct thread *td;
1495 register struct openbsd_poll_args *uap;
1497 return (sys_poll(td, (struct poll_args *)uap));
1501 * XXX This was created specifically to support netncp and netsmb. This
1502 * allows the caller to specify a socket to wait for events on. It returns
1503 * 0 if any events matched and an error otherwise. There is no way to
1504 * determine which events fired.
1507 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1510 sbintime_t asbt, precision, rsbt;
1513 precision = 0; /* stupid gcc! */
1516 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1517 rtv.tv_usec >= 1000000)
1519 if (!timevalisset(&rtv))
1521 else if (rtv.tv_sec <= INT32_MAX) {
1522 rsbt = tvtosbt(rtv);
1524 precision >>= tc_precexp;
1525 if (TIMESEL(&asbt, rsbt))
1526 asbt += tc_tick_sbt;
1527 if (asbt <= INT64_MAX - rsbt)
1537 * Iterate until the timeout expires or the socket becomes ready.
1540 selfdalloc(td, NULL);
1541 error = sopoll(so, events, NULL, td);
1542 /* error here is actually the ready events. */
1545 error = seltdwait(td, asbt, precision);
1550 /* XXX Duplicates ncp/smb behavior. */
1551 if (error == ERESTART)
1557 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1558 * have two select sets, one for read and another for write.
1561 selfdalloc(struct thread *td, void *cookie)
1566 if (stp->st_free1 == NULL)
1567 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1568 stp->st_free1->sf_td = stp;
1569 stp->st_free1->sf_cookie = cookie;
1570 if (stp->st_free2 == NULL)
1571 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1572 stp->st_free2->sf_td = stp;
1573 stp->st_free2->sf_cookie = cookie;
1577 selfdfree(struct seltd *stp, struct selfd *sfp)
1579 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1580 mtx_lock(sfp->sf_mtx);
1582 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1583 mtx_unlock(sfp->sf_mtx);
1584 uma_zfree(selfd_zone, sfp);
1587 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1590 struct selinfo *sip;
1594 * This feature is already provided by doselwakeup(), thus it is
1595 * enough to go for it.
1596 * Eventually, the context, should take care to avoid races
1597 * between thread calling select()/poll() and file descriptor
1598 * detaching, but, again, the races are just the same as
1601 doselwakeup(sip, -1);
1605 * Record a select request.
1608 selrecord(selector, sip)
1609 struct thread *selector;
1610 struct selinfo *sip;
1616 stp = selector->td_sel;
1618 * Don't record when doing a rescan.
1620 if (stp->st_flags & SELTD_RESCAN)
1623 * Grab one of the preallocated descriptors.
1626 if ((sfp = stp->st_free1) != NULL)
1627 stp->st_free1 = NULL;
1628 else if ((sfp = stp->st_free2) != NULL)
1629 stp->st_free2 = NULL;
1631 panic("selrecord: No free selfd on selq");
1634 mtxp = mtx_pool_find(mtxpool_select, sip);
1636 * Initialize the sfp and queue it in the thread.
1640 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1642 * Now that we've locked the sip, check for initialization.
1645 if (sip->si_mtx == NULL) {
1647 TAILQ_INIT(&sip->si_tdlist);
1650 * Add this thread to the list of selfds listening on this selinfo.
1652 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1653 mtx_unlock(sip->si_mtx);
1656 /* Wake up a selecting thread. */
1659 struct selinfo *sip;
1661 doselwakeup(sip, -1);
1664 /* Wake up a selecting thread, and set its priority. */
1666 selwakeuppri(sip, pri)
1667 struct selinfo *sip;
1670 doselwakeup(sip, pri);
1674 * Do a wakeup when a selectable event occurs.
1677 doselwakeup(sip, pri)
1678 struct selinfo *sip;
1685 /* If it's not initialized there can't be any waiters. */
1686 if (sip->si_mtx == NULL)
1689 * Locking the selinfo locks all selfds associated with it.
1691 mtx_lock(sip->si_mtx);
1692 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1694 * Once we remove this sfp from the list and clear the
1695 * sf_si seltdclear will know to ignore this si.
1697 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1700 mtx_lock(&stp->st_mtx);
1701 stp->st_flags |= SELTD_PENDING;
1702 cv_broadcastpri(&stp->st_wait, pri);
1703 mtx_unlock(&stp->st_mtx);
1705 mtx_unlock(sip->si_mtx);
1709 seltdinit(struct thread *td)
1713 if ((stp = td->td_sel) != NULL)
1715 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1716 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1717 cv_init(&stp->st_wait, "select");
1720 STAILQ_INIT(&stp->st_selq);
1724 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1731 * An event of interest may occur while we do not hold the seltd
1732 * locked so check the pending flag before we sleep.
1734 mtx_lock(&stp->st_mtx);
1736 * Any further calls to selrecord will be a rescan.
1738 stp->st_flags |= SELTD_RESCAN;
1739 if (stp->st_flags & SELTD_PENDING) {
1740 mtx_unlock(&stp->st_mtx);
1744 error = EWOULDBLOCK;
1746 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1747 sbt, precision, C_ABSOLUTE);
1749 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1750 mtx_unlock(&stp->st_mtx);
1756 seltdfini(struct thread *td)
1764 uma_zfree(selfd_zone, stp->st_free1);
1766 uma_zfree(selfd_zone, stp->st_free2);
1768 free(stp, M_SELECT);
1772 * Remove the references to the thread from all of the objects we were
1776 seltdclear(struct thread *td)
1783 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1784 selfdfree(stp, sfp);
1788 static void selectinit(void *);
1789 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1791 selectinit(void *dummy __unused)
1794 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1795 NULL, NULL, UMA_ALIGN_PTR, 0);
1796 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);