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/capsicum.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>
79 * The following macro defines how many bytes will be allocated from
80 * the stack instead of memory allocated when passing the IOCTL data
81 * structures from userspace and to the kernel. Some IOCTLs having
82 * small data structures are used very frequently and this small
83 * buffer on the stack gives a significant speedup improvement for
84 * those requests. The value of this define should be greater or equal
85 * to 64 bytes and should also be power of two. The data structure is
86 * currently hard-aligned to a 8-byte boundary on the stack. This
87 * should currently be sufficient for all supported platforms.
89 #define SYS_IOCTL_SMALL_SIZE 128 /* bytes */
90 #define SYS_IOCTL_SMALL_ALIGN 8 /* bytes */
93 static int iosize_max_clamp = 0;
94 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
95 &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
96 static int devfs_iosize_max_clamp = 1;
97 SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
98 &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
102 * Assert that the return value of read(2) and write(2) syscalls fits
103 * into a register. If not, an architecture will need to provide the
104 * usermode wrappers to reconstruct the result.
106 CTASSERT(sizeof(register_t) >= sizeof(size_t));
108 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
109 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
110 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
112 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
114 static int pollscan(struct thread *, struct pollfd *, u_int);
115 static int pollrescan(struct thread *);
116 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
117 static int selrescan(struct thread *, fd_mask **, fd_mask **);
118 static void selfdalloc(struct thread *, void *);
119 static void selfdfree(struct seltd *, struct selfd *);
120 static int dofileread(struct thread *, int, struct file *, struct uio *,
122 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
124 static void doselwakeup(struct selinfo *, int);
125 static void seltdinit(struct thread *);
126 static int seltdwait(struct thread *, sbintime_t, sbintime_t);
127 static void seltdclear(struct thread *);
130 * One seltd per-thread allocated on demand as needed.
132 * t - protected by st_mtx
133 * k - Only accessed by curthread or read-only
136 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
137 struct selfd *st_free1; /* (k) free fd for read set. */
138 struct selfd *st_free2; /* (k) free fd for write set. */
139 struct mtx st_mtx; /* Protects struct seltd */
140 struct cv st_wait; /* (t) Wait channel. */
141 int st_flags; /* (t) SELTD_ flags. */
144 #define SELTD_PENDING 0x0001 /* We have pending events. */
145 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
148 * One selfd allocated per-thread per-file-descriptor.
149 * f - protected by sf_mtx
152 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
153 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
154 struct selinfo *sf_si; /* (f) selinfo when linked. */
155 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
156 struct seltd *sf_td; /* (k) owning seltd. */
157 void *sf_cookie; /* (k) fd or pollfd. */
161 static uma_zone_t selfd_zone;
162 static struct mtx_pool *mtxpool_select;
166 devfs_iosize_max(void)
169 return (devfs_iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
170 INT_MAX : SSIZE_MAX);
177 return (iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
178 INT_MAX : SSIZE_MAX);
182 #ifndef _SYS_SYSPROTO_H_
192 struct read_args *uap;
198 if (uap->nbyte > IOSIZE_MAX)
200 aiov.iov_base = uap->buf;
201 aiov.iov_len = uap->nbyte;
202 auio.uio_iov = &aiov;
204 auio.uio_resid = uap->nbyte;
205 auio.uio_segflg = UIO_USERSPACE;
206 error = kern_readv(td, uap->fd, &auio);
211 * Positioned read system call
213 #ifndef _SYS_SYSPROTO_H_
223 sys_pread(struct thread *td, struct pread_args *uap)
226 return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
230 kern_pread(struct thread *td, int fd, void *buf, size_t nbyte, off_t offset)
236 if (nbyte > IOSIZE_MAX)
239 aiov.iov_len = nbyte;
240 auio.uio_iov = &aiov;
242 auio.uio_resid = nbyte;
243 auio.uio_segflg = UIO_USERSPACE;
244 error = kern_preadv(td, fd, &auio, offset);
248 #if defined(COMPAT_FREEBSD6)
250 freebsd6_pread(struct thread *td, struct freebsd6_pread_args *uap)
253 return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
258 * Scatter read system call.
260 #ifndef _SYS_SYSPROTO_H_
268 sys_readv(struct thread *td, struct readv_args *uap)
273 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
276 error = kern_readv(td, uap->fd, auio);
282 kern_readv(struct thread *td, int fd, struct uio *auio)
288 error = fget_read(td, fd, cap_rights_init(&rights, CAP_READ), &fp);
291 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
297 * Scatter positioned read system call.
299 #ifndef _SYS_SYSPROTO_H_
308 sys_preadv(struct thread *td, struct preadv_args *uap)
313 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
316 error = kern_preadv(td, uap->fd, auio, uap->offset);
322 kern_preadv(td, fd, auio, offset)
332 error = fget_read(td, fd, cap_rights_init(&rights, CAP_PREAD), &fp);
335 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
337 else if (offset < 0 &&
338 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
341 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
347 * Common code for readv and preadv that reads data in
348 * from a file using the passed in uio, offset, and flags.
351 dofileread(td, fd, fp, auio, offset, flags)
362 struct uio *ktruio = NULL;
367 /* Finish zero length reads right here */
368 if (auio->uio_resid == 0) {
369 td->td_retval[0] = 0;
372 auio->uio_rw = UIO_READ;
373 auio->uio_offset = offset;
376 if (KTRPOINT(td, KTR_GENIO))
377 ktruio = cloneuio(auio);
379 cnt = auio->uio_resid;
380 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
381 if (auio->uio_resid != cnt && (error == ERESTART ||
382 error == EINTR || error == EWOULDBLOCK))
385 cnt -= auio->uio_resid;
387 if (ktruio != NULL) {
388 ktruio->uio_resid = cnt;
389 ktrgenio(fd, UIO_READ, ktruio, error);
392 td->td_retval[0] = cnt;
396 #ifndef _SYS_SYSPROTO_H_
406 struct write_args *uap;
412 if (uap->nbyte > IOSIZE_MAX)
414 aiov.iov_base = (void *)(uintptr_t)uap->buf;
415 aiov.iov_len = uap->nbyte;
416 auio.uio_iov = &aiov;
418 auio.uio_resid = uap->nbyte;
419 auio.uio_segflg = UIO_USERSPACE;
420 error = kern_writev(td, uap->fd, &auio);
425 * Positioned write system call.
427 #ifndef _SYS_SYSPROTO_H_
437 sys_pwrite(struct thread *td, struct pwrite_args *uap)
440 return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
444 kern_pwrite(struct thread *td, int fd, const void *buf, size_t nbyte,
451 if (nbyte > IOSIZE_MAX)
453 aiov.iov_base = (void *)(uintptr_t)buf;
454 aiov.iov_len = nbyte;
455 auio.uio_iov = &aiov;
457 auio.uio_resid = nbyte;
458 auio.uio_segflg = UIO_USERSPACE;
459 error = kern_pwritev(td, fd, &auio, offset);
463 #if defined(COMPAT_FREEBSD6)
465 freebsd6_pwrite(struct thread *td, struct freebsd6_pwrite_args *uap)
468 return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
473 * Gather write system call.
475 #ifndef _SYS_SYSPROTO_H_
483 sys_writev(struct thread *td, struct writev_args *uap)
488 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
491 error = kern_writev(td, uap->fd, auio);
497 kern_writev(struct thread *td, int fd, struct uio *auio)
503 error = fget_write(td, fd, cap_rights_init(&rights, CAP_WRITE), &fp);
506 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
512 * Gather positioned write system call.
514 #ifndef _SYS_SYSPROTO_H_
515 struct pwritev_args {
523 sys_pwritev(struct thread *td, struct pwritev_args *uap)
528 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
531 error = kern_pwritev(td, uap->fd, auio, uap->offset);
537 kern_pwritev(td, fd, auio, offset)
547 error = fget_write(td, fd, cap_rights_init(&rights, CAP_PWRITE), &fp);
550 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
552 else if (offset < 0 &&
553 (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
556 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
562 * Common code for writev and pwritev that writes data to
563 * a file using the passed in uio, offset, and flags.
566 dofilewrite(td, fd, fp, auio, offset, flags)
577 struct uio *ktruio = NULL;
581 auio->uio_rw = UIO_WRITE;
583 auio->uio_offset = offset;
585 if (KTRPOINT(td, KTR_GENIO))
586 ktruio = cloneuio(auio);
588 cnt = auio->uio_resid;
589 if (fp->f_type == DTYPE_VNODE &&
590 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
592 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
593 if (auio->uio_resid != cnt && (error == ERESTART ||
594 error == EINTR || error == EWOULDBLOCK))
596 /* Socket layer is responsible for issuing SIGPIPE. */
597 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
598 PROC_LOCK(td->td_proc);
599 tdsignal(td, SIGPIPE);
600 PROC_UNLOCK(td->td_proc);
603 cnt -= auio->uio_resid;
605 if (ktruio != NULL) {
606 ktruio->uio_resid = cnt;
607 ktrgenio(fd, UIO_WRITE, ktruio, error);
610 td->td_retval[0] = cnt;
615 * Truncate a file given a file descriptor.
617 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
618 * descriptor isn't writable.
621 kern_ftruncate(td, fd, length)
633 error = fget(td, fd, cap_rights_init(&rights, CAP_FTRUNCATE), &fp);
636 AUDIT_ARG_FILE(td->td_proc, fp);
637 if (!(fp->f_flag & FWRITE)) {
641 error = fo_truncate(fp, length, td->td_ucred, td);
646 #ifndef _SYS_SYSPROTO_H_
647 struct ftruncate_args {
654 sys_ftruncate(td, uap)
656 struct ftruncate_args *uap;
659 return (kern_ftruncate(td, uap->fd, uap->length));
662 #if defined(COMPAT_43)
663 #ifndef _SYS_SYSPROTO_H_
664 struct oftruncate_args {
672 struct oftruncate_args *uap;
675 return (kern_ftruncate(td, uap->fd, uap->length));
677 #endif /* COMPAT_43 */
679 #ifndef _SYS_SYSPROTO_H_
688 sys_ioctl(struct thread *td, struct ioctl_args *uap)
690 u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
696 if (uap->com > 0xffffffff) {
698 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
699 td->td_proc->p_pid, td->td_name, uap->com);
700 uap->com &= 0xffffffff;
705 * Interpret high order word to find amount of data to be
706 * copied to/from the user's address space.
708 size = IOCPARM_LEN(com);
709 if ((size > IOCPARM_MAX) ||
710 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
711 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
712 ((com & IOC_OUT) && size == 0) ||
714 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
716 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
720 if (com & IOC_VOID) {
721 /* Integer argument. */
722 arg = (intptr_t)uap->data;
726 if (size > SYS_IOCTL_SMALL_SIZE)
727 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
732 data = (void *)&uap->data;
734 error = copyin(uap->data, data, (u_int)size);
737 } else if (com & IOC_OUT) {
739 * Zero the buffer so the user always
740 * gets back something deterministic.
745 error = kern_ioctl(td, uap->fd, com, data);
747 if (error == 0 && (com & IOC_OUT))
748 error = copyout(data, uap->data, (u_int)size);
751 if (size > SYS_IOCTL_SMALL_SIZE)
752 free(data, M_IOCTLOPS);
757 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
760 struct filedesc *fdp;
764 int error, tmp, locked;
769 fdp = td->td_proc->p_fd;
782 locked = LA_UNLOCKED;
788 if ((fp = fget_locked(fdp, fd)) == NULL) {
792 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
793 fp = NULL; /* fhold() was not called yet */
797 if (locked == LA_SLOCKED) {
798 FILEDESC_SUNLOCK(fdp);
799 locked = LA_UNLOCKED;
802 error = fget(td, fd, cap_rights_init(&rights, CAP_IOCTL), &fp);
808 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
815 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
818 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
821 if ((tmp = *(int *)data))
822 atomic_set_int(&fp->f_flag, FNONBLOCK);
824 atomic_clear_int(&fp->f_flag, FNONBLOCK);
828 if ((tmp = *(int *)data))
829 atomic_set_int(&fp->f_flag, FASYNC);
831 atomic_clear_int(&fp->f_flag, FASYNC);
836 error = fo_ioctl(fp, com, data, td->td_ucred, td);
840 FILEDESC_XUNLOCK(fdp);
844 FILEDESC_SUNLOCK(fdp);
848 FILEDESC_UNLOCK_ASSERT(fdp);
857 poll_no_poll(int events)
860 * Return true for read/write. If the user asked for something
861 * special, return POLLNVAL, so that clients have a way of
862 * determining reliably whether or not the extended
863 * functionality is present without hard-coding knowledge
864 * of specific filesystem implementations.
866 if (events & ~POLLSTANDARD)
869 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
873 sys_pselect(struct thread *td, struct pselect_args *uap)
876 struct timeval tv, *tvp;
880 if (uap->ts != NULL) {
881 error = copyin(uap->ts, &ts, sizeof(ts));
884 TIMESPEC_TO_TIMEVAL(&tv, &ts);
888 if (uap->sm != NULL) {
889 error = copyin(uap->sm, &set, sizeof(set));
895 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
900 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
901 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
906 error = kern_sigprocmask(td, SIG_SETMASK, uset,
907 &td->td_oldsigmask, 0);
910 td->td_pflags |= TDP_OLDMASK;
912 * Make sure that ast() is called on return to
913 * usermode and TDP_OLDMASK is cleared, restoring old
917 td->td_flags |= TDF_ASTPENDING;
920 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
924 #ifndef _SYS_SYSPROTO_H_
927 fd_set *in, *ou, *ex;
932 sys_select(struct thread *td, struct select_args *uap)
934 struct timeval tv, *tvp;
937 if (uap->tv != NULL) {
938 error = copyin(uap->tv, &tv, sizeof(tv));
945 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
950 * In the unlikely case when user specified n greater then the last
951 * open file descriptor, check that no bits are set after the last
952 * valid fd. We must return EBADF if any is set.
954 * There are applications that rely on the behaviour.
956 * nd is fd_lastfile + 1.
959 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
965 if (nd >= ndu || fd_in == NULL)
969 bits = 0; /* silence gcc */
970 for (i = nd; i < ndu; i++) {
972 #if BYTE_ORDER == LITTLE_ENDIAN
973 addr = (char *)fd_in + b;
975 addr = (char *)fd_in;
976 if (abi_nfdbits == NFDBITS) {
977 addr += rounddown(b, sizeof(fd_mask)) +
978 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
980 addr += rounddown(b, sizeof(uint32_t)) +
981 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
991 if ((bits & (1 << (i % NBBY))) != 0)
998 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
999 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
1001 struct filedesc *fdp;
1003 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
1004 * infds with the new FD_SETSIZE of 1024, and more than enough for
1005 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
1008 fd_mask s_selbits[howmany(2048, NFDBITS)];
1009 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
1011 sbintime_t asbt, precision, rsbt;
1012 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
1017 fdp = td->td_proc->p_fd;
1019 lf = fdp->fd_lastfile;
1023 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1026 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1029 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1034 * Allocate just enough bits for the non-null fd_sets. Use the
1035 * preallocated auto buffer if possible.
1037 nfdbits = roundup(nd, NFDBITS);
1038 ncpbytes = nfdbits / NBBY;
1039 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1042 nbufbytes += 2 * ncpbytes;
1044 nbufbytes += 2 * ncpbytes;
1046 nbufbytes += 2 * ncpbytes;
1047 if (nbufbytes <= sizeof s_selbits)
1048 selbits = &s_selbits[0];
1050 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1053 * Assign pointers into the bit buffers and fetch the input bits.
1054 * Put the output buffers together so that they can be bzeroed
1058 #define getbits(name, x) \
1060 if (name == NULL) { \
1064 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1066 sbp += ncpbytes / sizeof *sbp; \
1067 error = copyin(name, ibits[x], ncpubytes); \
1070 bzero((char *)ibits[x] + ncpubytes, \
1071 ncpbytes - ncpubytes); \
1079 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1081 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1082 * we are running under 32-bit emulation. This should be more
1085 #define swizzle_fdset(bits) \
1086 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1088 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1089 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1092 #define swizzle_fdset(bits)
1095 /* Make sure the bit order makes it through an ABI transition */
1096 swizzle_fdset(ibits[0]);
1097 swizzle_fdset(ibits[1]);
1098 swizzle_fdset(ibits[2]);
1101 bzero(selbits, nbufbytes / 2);
1106 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1107 rtv.tv_usec >= 1000000) {
1111 if (!timevalisset(&rtv))
1113 else if (rtv.tv_sec <= INT32_MAX) {
1114 rsbt = tvtosbt(rtv);
1116 precision >>= tc_precexp;
1117 if (TIMESEL(&asbt, rsbt))
1118 asbt += tc_tick_sbt;
1119 if (asbt <= SBT_MAX - rsbt)
1128 /* Iterate until the timeout expires or descriptors become ready. */
1130 error = selscan(td, ibits, obits, nd);
1131 if (error || td->td_retval[0] != 0)
1133 error = seltdwait(td, asbt, precision);
1136 error = selrescan(td, ibits, obits);
1137 if (error || td->td_retval[0] != 0)
1143 /* select is not restarted after signals... */
1144 if (error == ERESTART)
1146 if (error == EWOULDBLOCK)
1149 /* swizzle bit order back, if necessary */
1150 swizzle_fdset(obits[0]);
1151 swizzle_fdset(obits[1]);
1152 swizzle_fdset(obits[2]);
1153 #undef swizzle_fdset
1155 #define putbits(name, x) \
1156 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1166 if (selbits != &s_selbits[0])
1167 free(selbits, M_SELECT);
1172 * Convert a select bit set to poll flags.
1174 * The backend always returns POLLHUP/POLLERR if appropriate and we
1175 * return this as a set bit in any set.
1177 static int select_flags[3] = {
1178 POLLRDNORM | POLLHUP | POLLERR,
1179 POLLWRNORM | POLLHUP | POLLERR,
1180 POLLRDBAND | POLLERR
1184 * Compute the fo_poll flags required for a fd given by the index and
1185 * bit position in the fd_mask array.
1188 selflags(fd_mask **ibits, int idx, fd_mask bit)
1194 for (msk = 0; msk < 3; msk++) {
1195 if (ibits[msk] == NULL)
1197 if ((ibits[msk][idx] & bit) == 0)
1199 flags |= select_flags[msk];
1205 * Set the appropriate output bits given a mask of fired events and the
1206 * input bits originally requested.
1209 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1215 for (msk = 0; msk < 3; msk++) {
1216 if ((events & select_flags[msk]) == 0)
1218 if (ibits[msk] == NULL)
1220 if ((ibits[msk][idx] & bit) == 0)
1223 * XXX Check for a duplicate set. This can occur because a
1224 * socket calls selrecord() twice for each poll() call
1225 * resulting in two selfds per real fd. selrescan() will
1226 * call selsetbits twice as a result.
1228 if ((obits[msk][idx] & bit) != 0)
1230 obits[msk][idx] |= bit;
1238 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1240 cap_rights_t rights;
1242 cap_rights_init(&rights, CAP_EVENT);
1244 return (fget_unlocked(fdp, fd, &rights, fpp, NULL));
1248 * Traverse the list of fds attached to this thread's seltd and check for
1252 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1254 struct filedesc *fdp;
1264 fdp = td->td_proc->p_fd;
1267 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1268 fd = (int)(uintptr_t)sfp->sf_cookie;
1270 selfdfree(stp, sfp);
1271 /* If the selinfo wasn't cleared the event didn't fire. */
1274 error = getselfd_cap(fdp, fd, &fp);
1278 bit = (fd_mask)1 << (fd % NFDBITS);
1279 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1282 n += selsetbits(ibits, obits, idx, bit, ev);
1285 td->td_retval[0] = n;
1290 * Perform the initial filedescriptor scan and register ourselves with
1294 selscan(td, ibits, obits, nfd)
1296 fd_mask **ibits, **obits;
1299 struct filedesc *fdp;
1302 int ev, flags, end, fd;
1306 fdp = td->td_proc->p_fd;
1308 for (idx = 0, fd = 0; fd < nfd; idx++) {
1309 end = imin(fd + NFDBITS, nfd);
1310 for (bit = 1; fd < end; bit <<= 1, fd++) {
1311 /* Compute the list of events we're interested in. */
1312 flags = selflags(ibits, idx, bit);
1315 error = getselfd_cap(fdp, fd, &fp);
1318 selfdalloc(td, (void *)(uintptr_t)fd);
1319 ev = fo_poll(fp, flags, td->td_ucred, td);
1322 n += selsetbits(ibits, obits, idx, bit, ev);
1326 td->td_retval[0] = n;
1331 sys_poll(struct thread *td, struct poll_args *uap)
1333 struct timespec ts, *tsp;
1335 if (uap->timeout != INFTIM) {
1336 if (uap->timeout < 0)
1338 ts.tv_sec = uap->timeout / 1000;
1339 ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1344 return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1348 kern_poll(struct thread *td, struct pollfd *fds, u_int nfds,
1349 struct timespec *tsp, sigset_t *uset)
1351 struct pollfd *bits;
1352 struct pollfd smallbits[32];
1353 sbintime_t sbt, precision, tmp;
1361 if (tsp->tv_sec < 0)
1363 if (tsp->tv_nsec < 0 || tsp->tv_nsec >= 1000000000)
1365 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1369 if (ts.tv_sec > INT32_MAX / 2) {
1370 over = ts.tv_sec - INT32_MAX / 2;
1376 precision >>= tc_precexp;
1377 if (TIMESEL(&sbt, tmp))
1384 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1386 ni = nfds * sizeof(struct pollfd);
1387 if (ni > sizeof(smallbits))
1388 bits = malloc(ni, M_TEMP, M_WAITOK);
1391 error = copyin(fds, bits, ni);
1396 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1397 &td->td_oldsigmask, 0);
1400 td->td_pflags |= TDP_OLDMASK;
1402 * Make sure that ast() is called on return to
1403 * usermode and TDP_OLDMASK is cleared, restoring old
1407 td->td_flags |= TDF_ASTPENDING;
1412 /* Iterate until the timeout expires or descriptors become ready. */
1414 error = pollscan(td, bits, nfds);
1415 if (error || td->td_retval[0] != 0)
1417 error = seltdwait(td, sbt, precision);
1420 error = pollrescan(td);
1421 if (error || td->td_retval[0] != 0)
1427 /* poll is not restarted after signals... */
1428 if (error == ERESTART)
1430 if (error == EWOULDBLOCK)
1433 error = pollout(td, bits, fds, nfds);
1438 if (ni > sizeof(smallbits))
1444 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1446 struct timespec ts, *tsp;
1450 if (uap->ts != NULL) {
1451 error = copyin(uap->ts, &ts, sizeof(ts));
1457 if (uap->set != NULL) {
1458 error = copyin(uap->set, &set, sizeof(set));
1465 * fds is still a pointer to user space. kern_poll() will
1466 * take care of copyin that array to the kernel space.
1469 return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1473 pollrescan(struct thread *td)
1479 struct filedesc *fdp;
1483 cap_rights_t rights;
1488 fdp = td->td_proc->p_fd;
1490 FILEDESC_SLOCK(fdp);
1491 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1492 fd = (struct pollfd *)sfp->sf_cookie;
1494 selfdfree(stp, sfp);
1495 /* If the selinfo wasn't cleared the event didn't fire. */
1498 fp = fdp->fd_ofiles[fd->fd].fde_file;
1501 cap_check(cap_rights(fdp, fd->fd),
1502 cap_rights_init(&rights, CAP_EVENT)) != 0)
1507 fd->revents = POLLNVAL;
1513 * Note: backend also returns POLLHUP and
1514 * POLLERR if appropriate.
1516 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1517 if (fd->revents != 0)
1520 FILEDESC_SUNLOCK(fdp);
1522 td->td_retval[0] = n;
1528 pollout(td, fds, ufds, nfd)
1531 struct pollfd *ufds;
1538 for (i = 0; i < nfd; i++) {
1539 error = copyout(&fds->revents, &ufds->revents,
1540 sizeof(ufds->revents));
1543 if (fds->revents != 0)
1548 td->td_retval[0] = n;
1553 pollscan(td, fds, nfd)
1558 struct filedesc *fdp = td->td_proc->p_fd;
1561 cap_rights_t rights;
1565 FILEDESC_SLOCK(fdp);
1566 for (i = 0; i < nfd; i++, fds++) {
1567 if (fds->fd > fdp->fd_lastfile) {
1568 fds->revents = POLLNVAL;
1570 } else if (fds->fd < 0) {
1573 fp = fdp->fd_ofiles[fds->fd].fde_file;
1576 cap_check(cap_rights(fdp, fds->fd),
1577 cap_rights_init(&rights, CAP_EVENT)) != 0)
1582 fds->revents = POLLNVAL;
1586 * Note: backend also returns POLLHUP and
1587 * POLLERR if appropriate.
1589 selfdalloc(td, fds);
1590 fds->revents = fo_poll(fp, fds->events,
1593 * POSIX requires POLLOUT to be never
1594 * set simultaneously with POLLHUP.
1596 if ((fds->revents & POLLHUP) != 0)
1597 fds->revents &= ~POLLOUT;
1599 if (fds->revents != 0)
1604 FILEDESC_SUNLOCK(fdp);
1605 td->td_retval[0] = n;
1610 * OpenBSD poll system call.
1612 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1614 #ifndef _SYS_SYSPROTO_H_
1615 struct openbsd_poll_args {
1622 sys_openbsd_poll(td, uap)
1623 register struct thread *td;
1624 register struct openbsd_poll_args *uap;
1626 return (sys_poll(td, (struct poll_args *)uap));
1630 * XXX This was created specifically to support netncp and netsmb. This
1631 * allows the caller to specify a socket to wait for events on. It returns
1632 * 0 if any events matched and an error otherwise. There is no way to
1633 * determine which events fired.
1636 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1639 sbintime_t asbt, precision, rsbt;
1642 precision = 0; /* stupid gcc! */
1645 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1646 rtv.tv_usec >= 1000000)
1648 if (!timevalisset(&rtv))
1650 else if (rtv.tv_sec <= INT32_MAX) {
1651 rsbt = tvtosbt(rtv);
1653 precision >>= tc_precexp;
1654 if (TIMESEL(&asbt, rsbt))
1655 asbt += tc_tick_sbt;
1656 if (asbt <= SBT_MAX - rsbt)
1666 * Iterate until the timeout expires or the socket becomes ready.
1669 selfdalloc(td, NULL);
1670 error = sopoll(so, events, NULL, td);
1671 /* error here is actually the ready events. */
1674 error = seltdwait(td, asbt, precision);
1679 /* XXX Duplicates ncp/smb behavior. */
1680 if (error == ERESTART)
1686 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1687 * have two select sets, one for read and another for write.
1690 selfdalloc(struct thread *td, void *cookie)
1695 if (stp->st_free1 == NULL)
1696 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1697 stp->st_free1->sf_td = stp;
1698 stp->st_free1->sf_cookie = cookie;
1699 if (stp->st_free2 == NULL)
1700 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1701 stp->st_free2->sf_td = stp;
1702 stp->st_free2->sf_cookie = cookie;
1706 selfdfree(struct seltd *stp, struct selfd *sfp)
1708 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1709 if (sfp->sf_si != NULL) {
1710 mtx_lock(sfp->sf_mtx);
1711 if (sfp->sf_si != NULL) {
1712 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1713 refcount_release(&sfp->sf_refs);
1715 mtx_unlock(sfp->sf_mtx);
1717 if (refcount_release(&sfp->sf_refs))
1718 uma_zfree(selfd_zone, sfp);
1721 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1724 struct selinfo *sip;
1728 * This feature is already provided by doselwakeup(), thus it is
1729 * enough to go for it.
1730 * Eventually, the context, should take care to avoid races
1731 * between thread calling select()/poll() and file descriptor
1732 * detaching, but, again, the races are just the same as
1735 doselwakeup(sip, -1);
1739 * Record a select request.
1742 selrecord(selector, sip)
1743 struct thread *selector;
1744 struct selinfo *sip;
1750 stp = selector->td_sel;
1752 * Don't record when doing a rescan.
1754 if (stp->st_flags & SELTD_RESCAN)
1757 * Grab one of the preallocated descriptors.
1760 if ((sfp = stp->st_free1) != NULL)
1761 stp->st_free1 = NULL;
1762 else if ((sfp = stp->st_free2) != NULL)
1763 stp->st_free2 = NULL;
1765 panic("selrecord: No free selfd on selq");
1768 mtxp = mtx_pool_find(mtxpool_select, sip);
1770 * Initialize the sfp and queue it in the thread.
1774 refcount_init(&sfp->sf_refs, 2);
1775 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1777 * Now that we've locked the sip, check for initialization.
1780 if (sip->si_mtx == NULL) {
1782 TAILQ_INIT(&sip->si_tdlist);
1785 * Add this thread to the list of selfds listening on this selinfo.
1787 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1788 mtx_unlock(sip->si_mtx);
1791 /* Wake up a selecting thread. */
1794 struct selinfo *sip;
1796 doselwakeup(sip, -1);
1799 /* Wake up a selecting thread, and set its priority. */
1801 selwakeuppri(sip, pri)
1802 struct selinfo *sip;
1805 doselwakeup(sip, pri);
1809 * Do a wakeup when a selectable event occurs.
1812 doselwakeup(sip, pri)
1813 struct selinfo *sip;
1820 /* If it's not initialized there can't be any waiters. */
1821 if (sip->si_mtx == NULL)
1824 * Locking the selinfo locks all selfds associated with it.
1826 mtx_lock(sip->si_mtx);
1827 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1829 * Once we remove this sfp from the list and clear the
1830 * sf_si seltdclear will know to ignore this si.
1832 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1835 mtx_lock(&stp->st_mtx);
1836 stp->st_flags |= SELTD_PENDING;
1837 cv_broadcastpri(&stp->st_wait, pri);
1838 mtx_unlock(&stp->st_mtx);
1839 if (refcount_release(&sfp->sf_refs))
1840 uma_zfree(selfd_zone, sfp);
1842 mtx_unlock(sip->si_mtx);
1846 seltdinit(struct thread *td)
1850 if ((stp = td->td_sel) != NULL)
1852 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1853 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1854 cv_init(&stp->st_wait, "select");
1857 STAILQ_INIT(&stp->st_selq);
1861 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1868 * An event of interest may occur while we do not hold the seltd
1869 * locked so check the pending flag before we sleep.
1871 mtx_lock(&stp->st_mtx);
1873 * Any further calls to selrecord will be a rescan.
1875 stp->st_flags |= SELTD_RESCAN;
1876 if (stp->st_flags & SELTD_PENDING) {
1877 mtx_unlock(&stp->st_mtx);
1881 error = EWOULDBLOCK;
1883 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1884 sbt, precision, C_ABSOLUTE);
1886 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1887 mtx_unlock(&stp->st_mtx);
1893 seltdfini(struct thread *td)
1901 uma_zfree(selfd_zone, stp->st_free1);
1903 uma_zfree(selfd_zone, stp->st_free2);
1905 cv_destroy(&stp->st_wait);
1906 mtx_destroy(&stp->st_mtx);
1907 free(stp, M_SELECT);
1911 * Remove the references to the thread from all of the objects we were
1915 seltdclear(struct thread *td)
1922 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1923 selfdfree(stp, sfp);
1927 static void selectinit(void *);
1928 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1930 selectinit(void *dummy __unused)
1933 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1934 NULL, NULL, UMA_ALIGN_PTR, 0);
1935 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1939 * Set up a syscall return value that follows the convention specified for
1940 * posix_* functions.
1943 kern_posix_error(struct thread *td, int error)
1948 td->td_errno = error;
1949 td->td_pflags |= TDP_NERRNO;
1950 td->td_retval[0] = error;