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>
78 * The following macro defines how many bytes will be allocated from
79 * the stack instead of memory allocated when passing the IOCTL data
80 * structures from userspace and to the kernel. Some IOCTLs having
81 * small data structures are used very frequently and this small
82 * buffer on the stack gives a significant speedup improvement for
83 * those requests. The value of this define should be greater or equal
84 * to 64 bytes and should also be power of two. The data structure is
85 * currently hard-aligned to a 8-byte boundary on the stack. This
86 * should currently be sufficient for all supported platforms.
88 #define SYS_IOCTL_SMALL_SIZE 128 /* bytes */
89 #define SYS_IOCTL_SMALL_ALIGN 8 /* bytes */
91 int iosize_max_clamp = 1;
92 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
93 &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
94 int devfs_iosize_max_clamp = 1;
95 SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
96 &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
99 * Assert that the return value of read(2) and write(2) syscalls fits
100 * into a register. If not, an architecture will need to provide the
101 * usermode wrappers to reconstruct the result.
103 CTASSERT(sizeof(register_t) >= sizeof(size_t));
105 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
106 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
107 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
109 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
111 static int pollscan(struct thread *, struct pollfd *, u_int);
112 static int pollrescan(struct thread *);
113 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
114 static int selrescan(struct thread *, fd_mask **, fd_mask **);
115 static void selfdalloc(struct thread *, void *);
116 static void selfdfree(struct seltd *, struct selfd *);
117 static int dofileread(struct thread *, int, struct file *, struct uio *,
119 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
121 static void doselwakeup(struct selinfo *, int);
122 static void seltdinit(struct thread *);
123 static int seltdwait(struct thread *, int);
124 static void seltdclear(struct thread *);
127 * One seltd per-thread allocated on demand as needed.
129 * t - protected by st_mtx
130 * k - Only accessed by curthread or read-only
133 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
134 struct selfd *st_free1; /* (k) free fd for read set. */
135 struct selfd *st_free2; /* (k) free fd for write set. */
136 struct mtx st_mtx; /* Protects struct seltd */
137 struct cv st_wait; /* (t) Wait channel. */
138 int st_flags; /* (t) SELTD_ flags. */
141 #define SELTD_PENDING 0x0001 /* We have pending events. */
142 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
145 * One selfd allocated per-thread per-file-descriptor.
146 * f - protected by sf_mtx
149 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
150 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
151 struct selinfo *sf_si; /* (f) selinfo when linked. */
152 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
153 struct seltd *sf_td; /* (k) owning seltd. */
154 void *sf_cookie; /* (k) fd or pollfd. */
157 static uma_zone_t selfd_zone;
158 static struct mtx_pool *mtxpool_select;
160 #ifndef _SYS_SYSPROTO_H_
170 struct read_args *uap;
176 if (uap->nbyte > IOSIZE_MAX)
178 aiov.iov_base = uap->buf;
179 aiov.iov_len = uap->nbyte;
180 auio.uio_iov = &aiov;
182 auio.uio_resid = uap->nbyte;
183 auio.uio_segflg = UIO_USERSPACE;
184 error = kern_readv(td, uap->fd, &auio);
189 * Positioned read system call
191 #ifndef _SYS_SYSPROTO_H_
203 struct pread_args *uap;
209 if (uap->nbyte > IOSIZE_MAX)
211 aiov.iov_base = uap->buf;
212 aiov.iov_len = uap->nbyte;
213 auio.uio_iov = &aiov;
215 auio.uio_resid = uap->nbyte;
216 auio.uio_segflg = UIO_USERSPACE;
217 error = kern_preadv(td, uap->fd, &auio, uap->offset);
222 freebsd6_pread(td, uap)
224 struct freebsd6_pread_args *uap;
226 struct pread_args oargs;
229 oargs.buf = uap->buf;
230 oargs.nbyte = uap->nbyte;
231 oargs.offset = uap->offset;
232 return (sys_pread(td, &oargs));
236 * Scatter read system call.
238 #ifndef _SYS_SYSPROTO_H_
246 sys_readv(struct thread *td, struct readv_args *uap)
251 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
254 error = kern_readv(td, uap->fd, auio);
260 kern_readv(struct thread *td, int fd, struct uio *auio)
265 error = fget_read(td, fd, CAP_READ | CAP_SEEK, &fp);
268 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
274 * Scatter positioned read system call.
276 #ifndef _SYS_SYSPROTO_H_
285 sys_preadv(struct thread *td, struct preadv_args *uap)
290 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
293 error = kern_preadv(td, uap->fd, auio, uap->offset);
299 kern_preadv(td, fd, auio, offset)
308 error = fget_read(td, fd, CAP_READ, &fp);
311 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
313 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
316 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
322 * Common code for readv and preadv that reads data in
323 * from a file using the passed in uio, offset, and flags.
326 dofileread(td, fd, fp, auio, offset, flags)
337 struct uio *ktruio = NULL;
340 /* Finish zero length reads right here */
341 if (auio->uio_resid == 0) {
342 td->td_retval[0] = 0;
345 auio->uio_rw = UIO_READ;
346 auio->uio_offset = offset;
349 if (KTRPOINT(td, KTR_GENIO))
350 ktruio = cloneuio(auio);
352 cnt = auio->uio_resid;
353 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
354 if (auio->uio_resid != cnt && (error == ERESTART ||
355 error == EINTR || error == EWOULDBLOCK))
358 cnt -= auio->uio_resid;
360 if (ktruio != NULL) {
361 ktruio->uio_resid = cnt;
362 ktrgenio(fd, UIO_READ, ktruio, error);
365 td->td_retval[0] = cnt;
369 #ifndef _SYS_SYSPROTO_H_
379 struct write_args *uap;
385 if (uap->nbyte > IOSIZE_MAX)
387 aiov.iov_base = (void *)(uintptr_t)uap->buf;
388 aiov.iov_len = uap->nbyte;
389 auio.uio_iov = &aiov;
391 auio.uio_resid = uap->nbyte;
392 auio.uio_segflg = UIO_USERSPACE;
393 error = kern_writev(td, uap->fd, &auio);
398 * Positioned write system call.
400 #ifndef _SYS_SYSPROTO_H_
412 struct pwrite_args *uap;
418 if (uap->nbyte > IOSIZE_MAX)
420 aiov.iov_base = (void *)(uintptr_t)uap->buf;
421 aiov.iov_len = uap->nbyte;
422 auio.uio_iov = &aiov;
424 auio.uio_resid = uap->nbyte;
425 auio.uio_segflg = UIO_USERSPACE;
426 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
431 freebsd6_pwrite(td, uap)
433 struct freebsd6_pwrite_args *uap;
435 struct pwrite_args oargs;
438 oargs.buf = uap->buf;
439 oargs.nbyte = uap->nbyte;
440 oargs.offset = uap->offset;
441 return (sys_pwrite(td, &oargs));
445 * Gather write system call.
447 #ifndef _SYS_SYSPROTO_H_
455 sys_writev(struct thread *td, struct writev_args *uap)
460 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
463 error = kern_writev(td, uap->fd, auio);
469 kern_writev(struct thread *td, int fd, struct uio *auio)
474 error = fget_write(td, fd, CAP_WRITE | CAP_SEEK, &fp);
477 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
483 * Gather positioned write system call.
485 #ifndef _SYS_SYSPROTO_H_
486 struct pwritev_args {
494 sys_pwritev(struct thread *td, struct pwritev_args *uap)
499 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
502 error = kern_pwritev(td, uap->fd, auio, uap->offset);
508 kern_pwritev(td, fd, auio, offset)
517 error = fget_write(td, fd, CAP_WRITE, &fp);
520 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
522 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
525 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
531 * Common code for writev and pwritev that writes data to
532 * a file using the passed in uio, offset, and flags.
535 dofilewrite(td, fd, fp, auio, offset, flags)
546 struct uio *ktruio = NULL;
549 auio->uio_rw = UIO_WRITE;
551 auio->uio_offset = offset;
553 if (KTRPOINT(td, KTR_GENIO))
554 ktruio = cloneuio(auio);
556 cnt = auio->uio_resid;
557 if (fp->f_type == DTYPE_VNODE &&
558 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
560 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
561 if (auio->uio_resid != cnt && (error == ERESTART ||
562 error == EINTR || error == EWOULDBLOCK))
564 /* Socket layer is responsible for issuing SIGPIPE. */
565 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
566 PROC_LOCK(td->td_proc);
567 tdsignal(td, SIGPIPE);
568 PROC_UNLOCK(td->td_proc);
571 cnt -= auio->uio_resid;
573 if (ktruio != NULL) {
574 ktruio->uio_resid = cnt;
575 ktrgenio(fd, UIO_WRITE, ktruio, error);
578 td->td_retval[0] = cnt;
583 * Truncate a file given a file descriptor.
585 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
586 * descriptor isn't writable.
589 kern_ftruncate(td, fd, length)
600 error = fget(td, fd, CAP_FTRUNCATE, &fp);
603 AUDIT_ARG_FILE(td->td_proc, fp);
604 if (!(fp->f_flag & FWRITE)) {
608 error = fo_truncate(fp, length, td->td_ucred, td);
613 #ifndef _SYS_SYSPROTO_H_
614 struct ftruncate_args {
621 sys_ftruncate(td, uap)
623 struct ftruncate_args *uap;
626 return (kern_ftruncate(td, uap->fd, uap->length));
629 #if defined(COMPAT_43)
630 #ifndef _SYS_SYSPROTO_H_
631 struct oftruncate_args {
639 struct oftruncate_args *uap;
642 return (kern_ftruncate(td, uap->fd, uap->length));
644 #endif /* COMPAT_43 */
646 #ifndef _SYS_SYSPROTO_H_
655 sys_ioctl(struct thread *td, struct ioctl_args *uap)
657 u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
663 if (uap->com > 0xffffffff) {
665 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
666 td->td_proc->p_pid, td->td_name, uap->com);
667 uap->com &= 0xffffffff;
672 * Interpret high order word to find amount of data to be
673 * copied to/from the user's address space.
675 size = IOCPARM_LEN(com);
676 if ((size > IOCPARM_MAX) ||
677 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
678 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
679 ((com & IOC_OUT) && size == 0) ||
681 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
683 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
687 if (com & IOC_VOID) {
688 /* Integer argument. */
689 arg = (intptr_t)uap->data;
693 if (size > SYS_IOCTL_SMALL_SIZE)
694 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
699 data = (void *)&uap->data;
701 error = copyin(uap->data, data, (u_int)size);
704 } else if (com & IOC_OUT) {
706 * Zero the buffer so the user always
707 * gets back something deterministic.
712 error = kern_ioctl(td, uap->fd, com, data);
714 if (error == 0 && (com & IOC_OUT))
715 error = copyout(data, uap->data, (u_int)size);
718 if (size > SYS_IOCTL_SMALL_SIZE)
719 free(data, M_IOCTLOPS);
724 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
727 struct filedesc *fdp;
733 if ((error = fget(td, fd, CAP_IOCTL, &fp)) != 0)
735 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
739 fdp = td->td_proc->p_fd;
743 fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
744 FILEDESC_XUNLOCK(fdp);
748 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
749 FILEDESC_XUNLOCK(fdp);
752 if ((tmp = *(int *)data))
753 atomic_set_int(&fp->f_flag, FNONBLOCK);
755 atomic_clear_int(&fp->f_flag, FNONBLOCK);
759 if ((tmp = *(int *)data))
760 atomic_set_int(&fp->f_flag, FASYNC);
762 atomic_clear_int(&fp->f_flag, FASYNC);
767 error = fo_ioctl(fp, com, data, td->td_ucred, td);
774 poll_no_poll(int events)
777 * Return true for read/write. If the user asked for something
778 * special, return POLLNVAL, so that clients have a way of
779 * determining reliably whether or not the extended
780 * functionality is present without hard-coding knowledge
781 * of specific filesystem implementations.
783 if (events & ~POLLSTANDARD)
786 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
790 sys_pselect(struct thread *td, struct pselect_args *uap)
793 struct timeval tv, *tvp;
797 if (uap->ts != NULL) {
798 error = copyin(uap->ts, &ts, sizeof(ts));
801 TIMESPEC_TO_TIMEVAL(&tv, &ts);
805 if (uap->sm != NULL) {
806 error = copyin(uap->sm, &set, sizeof(set));
812 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
817 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
818 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
823 error = kern_sigprocmask(td, SIG_SETMASK, uset,
824 &td->td_oldsigmask, 0);
827 td->td_pflags |= TDP_OLDMASK;
829 * Make sure that ast() is called on return to
830 * usermode and TDP_OLDMASK is cleared, restoring old
834 td->td_flags |= TDF_ASTPENDING;
837 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
841 #ifndef _SYS_SYSPROTO_H_
844 fd_set *in, *ou, *ex;
849 sys_select(struct thread *td, struct select_args *uap)
851 struct timeval tv, *tvp;
854 if (uap->tv != NULL) {
855 error = copyin(uap->tv, &tv, sizeof(tv));
862 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
867 * In the unlikely case when user specified n greater then the last
868 * open file descriptor, check that no bits are set after the last
869 * valid fd. We must return EBADF if any is set.
871 * There are applications that rely on the behaviour.
873 * nd is fd_lastfile + 1.
876 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
882 if (nd >= ndu || fd_in == NULL)
886 bits = 0; /* silence gcc */
887 for (i = nd; i < ndu; i++) {
889 #if BYTE_ORDER == LITTLE_ENDIAN
890 addr = (char *)fd_in + b;
892 addr = (char *)fd_in;
893 if (abi_nfdbits == NFDBITS) {
894 addr += rounddown(b, sizeof(fd_mask)) +
895 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
897 addr += rounddown(b, sizeof(uint32_t)) +
898 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
908 if ((bits & (1 << (i % NBBY))) != 0)
915 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
916 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
918 struct filedesc *fdp;
920 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
921 * infds with the new FD_SETSIZE of 1024, and more than enough for
922 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
925 fd_mask s_selbits[howmany(2048, NFDBITS)];
926 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
927 struct timeval atv, rtv, ttv;
928 int error, lf, ndu, timo;
929 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
933 fdp = td->td_proc->p_fd;
935 lf = fdp->fd_lastfile;
939 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
942 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
945 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
950 * Allocate just enough bits for the non-null fd_sets. Use the
951 * preallocated auto buffer if possible.
953 nfdbits = roundup(nd, NFDBITS);
954 ncpbytes = nfdbits / NBBY;
955 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
958 nbufbytes += 2 * ncpbytes;
960 nbufbytes += 2 * ncpbytes;
962 nbufbytes += 2 * ncpbytes;
963 if (nbufbytes <= sizeof s_selbits)
964 selbits = &s_selbits[0];
966 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
969 * Assign pointers into the bit buffers and fetch the input bits.
970 * Put the output buffers together so that they can be bzeroed
974 #define getbits(name, x) \
976 if (name == NULL) { \
980 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
982 sbp += ncpbytes / sizeof *sbp; \
983 error = copyin(name, ibits[x], ncpubytes); \
986 bzero((char *)ibits[x] + ncpubytes, \
987 ncpbytes - ncpubytes); \
995 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
997 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
998 * we are running under 32-bit emulation. This should be more
1001 #define swizzle_fdset(bits) \
1002 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1004 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1005 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1008 #define swizzle_fdset(bits)
1011 /* Make sure the bit order makes it through an ABI transition */
1012 swizzle_fdset(ibits[0]);
1013 swizzle_fdset(ibits[1]);
1014 swizzle_fdset(ibits[2]);
1017 bzero(selbits, nbufbytes / 2);
1021 if (itimerfix(&atv)) {
1025 getmicrouptime(&rtv);
1026 timevaladd(&atv, &rtv);
1033 /* Iterate until the timeout expires or descriptors become ready. */
1035 error = selscan(td, ibits, obits, nd);
1036 if (error || td->td_retval[0] != 0)
1038 if (atv.tv_sec || atv.tv_usec) {
1039 getmicrouptime(&rtv);
1040 if (timevalcmp(&rtv, &atv, >=))
1043 timevalsub(&ttv, &rtv);
1044 timo = ttv.tv_sec > 24 * 60 * 60 ?
1045 24 * 60 * 60 * hz : tvtohz(&ttv);
1047 error = seltdwait(td, timo);
1050 error = selrescan(td, ibits, obits);
1051 if (error || td->td_retval[0] != 0)
1057 /* select is not restarted after signals... */
1058 if (error == ERESTART)
1060 if (error == EWOULDBLOCK)
1063 /* swizzle bit order back, if necessary */
1064 swizzle_fdset(obits[0]);
1065 swizzle_fdset(obits[1]);
1066 swizzle_fdset(obits[2]);
1067 #undef swizzle_fdset
1069 #define putbits(name, x) \
1070 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1080 if (selbits != &s_selbits[0])
1081 free(selbits, M_SELECT);
1086 * Convert a select bit set to poll flags.
1088 * The backend always returns POLLHUP/POLLERR if appropriate and we
1089 * return this as a set bit in any set.
1091 static int select_flags[3] = {
1092 POLLRDNORM | POLLHUP | POLLERR,
1093 POLLWRNORM | POLLHUP | POLLERR,
1094 POLLRDBAND | POLLERR
1098 * Compute the fo_poll flags required for a fd given by the index and
1099 * bit position in the fd_mask array.
1102 selflags(fd_mask **ibits, int idx, fd_mask bit)
1108 for (msk = 0; msk < 3; msk++) {
1109 if (ibits[msk] == NULL)
1111 if ((ibits[msk][idx] & bit) == 0)
1113 flags |= select_flags[msk];
1119 * Set the appropriate output bits given a mask of fired events and the
1120 * input bits originally requested.
1123 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1129 for (msk = 0; msk < 3; msk++) {
1130 if ((events & select_flags[msk]) == 0)
1132 if (ibits[msk] == NULL)
1134 if ((ibits[msk][idx] & bit) == 0)
1137 * XXX Check for a duplicate set. This can occur because a
1138 * socket calls selrecord() twice for each poll() call
1139 * resulting in two selfds per real fd. selrescan() will
1140 * call selsetbits twice as a result.
1142 if ((obits[msk][idx] & bit) != 0)
1144 obits[msk][idx] |= bit;
1152 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1156 struct file *fp_fromcap;
1160 if ((fp = fget_unlocked(fdp, fd)) == NULL)
1164 * If the file descriptor is for a capability, test rights and use
1165 * the file descriptor references by the capability.
1167 error = cap_funwrap(fp, CAP_POLL_EVENT, &fp_fromcap);
1169 fdrop(fp, curthread);
1172 if (fp != fp_fromcap) {
1174 fdrop(fp, curthread);
1177 #endif /* CAPABILITIES */
1183 * Traverse the list of fds attached to this thread's seltd and check for
1187 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1189 struct filedesc *fdp;
1199 fdp = td->td_proc->p_fd;
1202 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1203 fd = (int)(uintptr_t)sfp->sf_cookie;
1205 selfdfree(stp, sfp);
1206 /* If the selinfo wasn't cleared the event didn't fire. */
1209 error = getselfd_cap(fdp, fd, &fp);
1213 bit = (fd_mask)1 << (fd % NFDBITS);
1214 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1217 n += selsetbits(ibits, obits, idx, bit, ev);
1220 td->td_retval[0] = n;
1225 * Perform the initial filedescriptor scan and register ourselves with
1229 selscan(td, ibits, obits, nfd)
1231 fd_mask **ibits, **obits;
1234 struct filedesc *fdp;
1237 int ev, flags, end, fd;
1241 fdp = td->td_proc->p_fd;
1243 for (idx = 0, fd = 0; fd < nfd; idx++) {
1244 end = imin(fd + NFDBITS, nfd);
1245 for (bit = 1; fd < end; bit <<= 1, fd++) {
1246 /* Compute the list of events we're interested in. */
1247 flags = selflags(ibits, idx, bit);
1250 error = getselfd_cap(fdp, fd, &fp);
1253 selfdalloc(td, (void *)(uintptr_t)fd);
1254 ev = fo_poll(fp, flags, td->td_ucred, td);
1257 n += selsetbits(ibits, obits, idx, bit, ev);
1261 td->td_retval[0] = n;
1265 #ifndef _SYS_SYSPROTO_H_
1275 struct poll_args *uap;
1277 struct pollfd *bits;
1278 struct pollfd smallbits[32];
1279 struct timeval atv, rtv, ttv;
1285 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1287 ni = nfds * sizeof(struct pollfd);
1288 if (ni > sizeof(smallbits))
1289 bits = malloc(ni, M_TEMP, M_WAITOK);
1292 error = copyin(uap->fds, bits, ni);
1295 if (uap->timeout != INFTIM) {
1296 atv.tv_sec = uap->timeout / 1000;
1297 atv.tv_usec = (uap->timeout % 1000) * 1000;
1298 if (itimerfix(&atv)) {
1302 getmicrouptime(&rtv);
1303 timevaladd(&atv, &rtv);
1310 /* Iterate until the timeout expires or descriptors become ready. */
1312 error = pollscan(td, bits, nfds);
1313 if (error || td->td_retval[0] != 0)
1315 if (atv.tv_sec || atv.tv_usec) {
1316 getmicrouptime(&rtv);
1317 if (timevalcmp(&rtv, &atv, >=))
1320 timevalsub(&ttv, &rtv);
1321 timo = ttv.tv_sec > 24 * 60 * 60 ?
1322 24 * 60 * 60 * hz : tvtohz(&ttv);
1324 error = seltdwait(td, timo);
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];
1376 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1380 fd->revents = POLLNVAL;
1386 * Note: backend also returns POLLHUP and
1387 * POLLERR if appropriate.
1389 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1390 if (fd->revents != 0)
1393 FILEDESC_SUNLOCK(fdp);
1395 td->td_retval[0] = n;
1401 pollout(td, fds, ufds, nfd)
1404 struct pollfd *ufds;
1411 for (i = 0; i < nfd; i++) {
1412 error = copyout(&fds->revents, &ufds->revents,
1413 sizeof(ufds->revents));
1416 if (fds->revents != 0)
1421 td->td_retval[0] = n;
1426 pollscan(td, fds, nfd)
1431 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];
1447 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1451 fds->revents = POLLNVAL;
1455 * Note: backend also returns POLLHUP and
1456 * POLLERR if appropriate.
1458 selfdalloc(td, fds);
1459 fds->revents = fo_poll(fp, fds->events,
1462 * POSIX requires POLLOUT to be never
1463 * set simultaneously with POLLHUP.
1465 if ((fds->revents & POLLHUP) != 0)
1466 fds->revents &= ~POLLOUT;
1468 if (fds->revents != 0)
1473 FILEDESC_SUNLOCK(fdp);
1474 td->td_retval[0] = n;
1479 * OpenBSD poll system call.
1481 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1483 #ifndef _SYS_SYSPROTO_H_
1484 struct openbsd_poll_args {
1491 sys_openbsd_poll(td, uap)
1492 register struct thread *td;
1493 register struct openbsd_poll_args *uap;
1495 return (sys_poll(td, (struct poll_args *)uap));
1499 * XXX This was created specifically to support netncp and netsmb. This
1500 * allows the caller to specify a socket to wait for events on. It returns
1501 * 0 if any events matched and an error otherwise. There is no way to
1502 * determine which events fired.
1505 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1507 struct timeval atv, rtv, ttv;
1512 if (itimerfix(&atv))
1514 getmicrouptime(&rtv);
1515 timevaladd(&atv, &rtv);
1524 * Iterate until the timeout expires or the socket becomes ready.
1527 selfdalloc(td, NULL);
1528 error = sopoll(so, events, NULL, td);
1529 /* error here is actually the ready events. */
1532 if (atv.tv_sec || atv.tv_usec) {
1533 getmicrouptime(&rtv);
1534 if (timevalcmp(&rtv, &atv, >=)) {
1536 return (EWOULDBLOCK);
1539 timevalsub(&ttv, &rtv);
1540 timo = ttv.tv_sec > 24 * 60 * 60 ?
1541 24 * 60 * 60 * hz : tvtohz(&ttv);
1543 error = seltdwait(td, timo);
1548 /* XXX Duplicates ncp/smb behavior. */
1549 if (error == ERESTART)
1555 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1556 * have two select sets, one for read and another for write.
1559 selfdalloc(struct thread *td, void *cookie)
1564 if (stp->st_free1 == NULL)
1565 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1566 stp->st_free1->sf_td = stp;
1567 stp->st_free1->sf_cookie = cookie;
1568 if (stp->st_free2 == NULL)
1569 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1570 stp->st_free2->sf_td = stp;
1571 stp->st_free2->sf_cookie = cookie;
1575 selfdfree(struct seltd *stp, struct selfd *sfp)
1577 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1578 mtx_lock(sfp->sf_mtx);
1580 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1581 mtx_unlock(sfp->sf_mtx);
1582 uma_zfree(selfd_zone, sfp);
1585 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1588 struct selinfo *sip;
1592 * This feature is already provided by doselwakeup(), thus it is
1593 * enough to go for it.
1594 * Eventually, the context, should take care to avoid races
1595 * between thread calling select()/poll() and file descriptor
1596 * detaching, but, again, the races are just the same as
1599 doselwakeup(sip, -1);
1603 * Record a select request.
1606 selrecord(selector, sip)
1607 struct thread *selector;
1608 struct selinfo *sip;
1614 stp = selector->td_sel;
1616 * Don't record when doing a rescan.
1618 if (stp->st_flags & SELTD_RESCAN)
1621 * Grab one of the preallocated descriptors.
1624 if ((sfp = stp->st_free1) != NULL)
1625 stp->st_free1 = NULL;
1626 else if ((sfp = stp->st_free2) != NULL)
1627 stp->st_free2 = NULL;
1629 panic("selrecord: No free selfd on selq");
1632 mtxp = mtx_pool_find(mtxpool_select, sip);
1634 * Initialize the sfp and queue it in the thread.
1638 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1640 * Now that we've locked the sip, check for initialization.
1643 if (sip->si_mtx == NULL) {
1645 TAILQ_INIT(&sip->si_tdlist);
1648 * Add this thread to the list of selfds listening on this selinfo.
1650 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1651 mtx_unlock(sip->si_mtx);
1654 /* Wake up a selecting thread. */
1657 struct selinfo *sip;
1659 doselwakeup(sip, -1);
1662 /* Wake up a selecting thread, and set its priority. */
1664 selwakeuppri(sip, pri)
1665 struct selinfo *sip;
1668 doselwakeup(sip, pri);
1672 * Do a wakeup when a selectable event occurs.
1675 doselwakeup(sip, pri)
1676 struct selinfo *sip;
1683 /* If it's not initialized there can't be any waiters. */
1684 if (sip->si_mtx == NULL)
1687 * Locking the selinfo locks all selfds associated with it.
1689 mtx_lock(sip->si_mtx);
1690 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1692 * Once we remove this sfp from the list and clear the
1693 * sf_si seltdclear will know to ignore this si.
1695 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1698 mtx_lock(&stp->st_mtx);
1699 stp->st_flags |= SELTD_PENDING;
1700 cv_broadcastpri(&stp->st_wait, pri);
1701 mtx_unlock(&stp->st_mtx);
1703 mtx_unlock(sip->si_mtx);
1707 seltdinit(struct thread *td)
1711 if ((stp = td->td_sel) != NULL)
1713 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1714 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1715 cv_init(&stp->st_wait, "select");
1718 STAILQ_INIT(&stp->st_selq);
1722 seltdwait(struct thread *td, int timo)
1729 * An event of interest may occur while we do not hold the seltd
1730 * locked so check the pending flag before we sleep.
1732 mtx_lock(&stp->st_mtx);
1734 * Any further calls to selrecord will be a rescan.
1736 stp->st_flags |= SELTD_RESCAN;
1737 if (stp->st_flags & SELTD_PENDING) {
1738 mtx_unlock(&stp->st_mtx);
1742 error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1744 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1745 mtx_unlock(&stp->st_mtx);
1751 seltdfini(struct thread *td)
1759 uma_zfree(selfd_zone, stp->st_free1);
1761 uma_zfree(selfd_zone, stp->st_free2);
1763 free(stp, M_SELECT);
1767 * Remove the references to the thread from all of the objects we were
1771 seltdclear(struct thread *td)
1778 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1779 selfdfree(stp, sfp);
1783 static void selectinit(void *);
1784 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1786 selectinit(void *dummy __unused)
1789 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1790 NULL, NULL, UMA_ALIGN_PTR, 0);
1791 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);