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");
81 int devfs_iosize_max_clamp = 1;
82 SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
83 &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
86 * Assert that the return value of read(2) and write(2) syscalls fits
87 * into a register. If not, an architecture will need to provide the
88 * usermode wrappers to reconstruct the result.
90 CTASSERT(sizeof(register_t) >= sizeof(size_t));
92 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
93 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
94 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
96 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
98 static int pollscan(struct thread *, struct pollfd *, u_int);
99 static int pollrescan(struct thread *);
100 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
101 static int selrescan(struct thread *, fd_mask **, fd_mask **);
102 static void selfdalloc(struct thread *, void *);
103 static void selfdfree(struct seltd *, struct selfd *);
104 static int dofileread(struct thread *, int, struct file *, struct uio *,
106 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
108 static void doselwakeup(struct selinfo *, int);
109 static void seltdinit(struct thread *);
110 static int seltdwait(struct thread *, sbintime_t, sbintime_t);
111 static void seltdclear(struct thread *);
114 * One seltd per-thread allocated on demand as needed.
116 * t - protected by st_mtx
117 * k - Only accessed by curthread or read-only
120 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
121 struct selfd *st_free1; /* (k) free fd for read set. */
122 struct selfd *st_free2; /* (k) free fd for write set. */
123 struct mtx st_mtx; /* Protects struct seltd */
124 struct cv st_wait; /* (t) Wait channel. */
125 int st_flags; /* (t) SELTD_ flags. */
128 #define SELTD_PENDING 0x0001 /* We have pending events. */
129 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
132 * One selfd allocated per-thread per-file-descriptor.
133 * f - protected by sf_mtx
136 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
137 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
138 struct selinfo *sf_si; /* (f) selinfo when linked. */
139 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
140 struct seltd *sf_td; /* (k) owning seltd. */
141 void *sf_cookie; /* (k) fd or pollfd. */
144 static uma_zone_t selfd_zone;
145 static struct mtx_pool *mtxpool_select;
147 #ifndef _SYS_SYSPROTO_H_
157 struct read_args *uap;
163 if (uap->nbyte > IOSIZE_MAX)
165 aiov.iov_base = uap->buf;
166 aiov.iov_len = uap->nbyte;
167 auio.uio_iov = &aiov;
169 auio.uio_resid = uap->nbyte;
170 auio.uio_segflg = UIO_USERSPACE;
171 error = kern_readv(td, uap->fd, &auio);
176 * Positioned read system call
178 #ifndef _SYS_SYSPROTO_H_
190 struct pread_args *uap;
196 if (uap->nbyte > IOSIZE_MAX)
198 aiov.iov_base = uap->buf;
199 aiov.iov_len = uap->nbyte;
200 auio.uio_iov = &aiov;
202 auio.uio_resid = uap->nbyte;
203 auio.uio_segflg = UIO_USERSPACE;
204 error = kern_preadv(td, uap->fd, &auio, uap->offset);
209 freebsd6_pread(td, uap)
211 struct freebsd6_pread_args *uap;
213 struct pread_args oargs;
216 oargs.buf = uap->buf;
217 oargs.nbyte = uap->nbyte;
218 oargs.offset = uap->offset;
219 return (sys_pread(td, &oargs));
223 * Scatter read system call.
225 #ifndef _SYS_SYSPROTO_H_
233 sys_readv(struct thread *td, struct readv_args *uap)
238 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
241 error = kern_readv(td, uap->fd, auio);
247 kern_readv(struct thread *td, int fd, struct uio *auio)
253 error = fget_read(td, fd, cap_rights_init(&rights, CAP_READ), &fp);
256 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
262 * Scatter positioned read system call.
264 #ifndef _SYS_SYSPROTO_H_
273 sys_preadv(struct thread *td, struct preadv_args *uap)
278 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
281 error = kern_preadv(td, uap->fd, auio, uap->offset);
287 kern_preadv(td, fd, auio, offset)
297 error = fget_read(td, fd, cap_rights_init(&rights, CAP_PREAD), &fp);
300 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
302 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
305 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
311 * Common code for readv and preadv that reads data in
312 * from a file using the passed in uio, offset, and flags.
315 dofileread(td, fd, fp, auio, offset, flags)
326 struct uio *ktruio = NULL;
329 /* Finish zero length reads right here */
330 if (auio->uio_resid == 0) {
331 td->td_retval[0] = 0;
334 auio->uio_rw = UIO_READ;
335 auio->uio_offset = offset;
338 if (KTRPOINT(td, KTR_GENIO))
339 ktruio = cloneuio(auio);
341 cnt = auio->uio_resid;
342 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
343 if (auio->uio_resid != cnt && (error == ERESTART ||
344 error == EINTR || error == EWOULDBLOCK))
347 cnt -= auio->uio_resid;
349 if (ktruio != NULL) {
350 ktruio->uio_resid = cnt;
351 ktrgenio(fd, UIO_READ, ktruio, error);
354 td->td_retval[0] = cnt;
358 #ifndef _SYS_SYSPROTO_H_
368 struct write_args *uap;
374 if (uap->nbyte > IOSIZE_MAX)
376 aiov.iov_base = (void *)(uintptr_t)uap->buf;
377 aiov.iov_len = uap->nbyte;
378 auio.uio_iov = &aiov;
380 auio.uio_resid = uap->nbyte;
381 auio.uio_segflg = UIO_USERSPACE;
382 error = kern_writev(td, uap->fd, &auio);
387 * Positioned write system call.
389 #ifndef _SYS_SYSPROTO_H_
401 struct pwrite_args *uap;
407 if (uap->nbyte > IOSIZE_MAX)
409 aiov.iov_base = (void *)(uintptr_t)uap->buf;
410 aiov.iov_len = uap->nbyte;
411 auio.uio_iov = &aiov;
413 auio.uio_resid = uap->nbyte;
414 auio.uio_segflg = UIO_USERSPACE;
415 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
420 freebsd6_pwrite(td, uap)
422 struct freebsd6_pwrite_args *uap;
424 struct pwrite_args oargs;
427 oargs.buf = uap->buf;
428 oargs.nbyte = uap->nbyte;
429 oargs.offset = uap->offset;
430 return (sys_pwrite(td, &oargs));
434 * Gather write system call.
436 #ifndef _SYS_SYSPROTO_H_
444 sys_writev(struct thread *td, struct writev_args *uap)
449 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
452 error = kern_writev(td, uap->fd, auio);
458 kern_writev(struct thread *td, int fd, struct uio *auio)
464 error = fget_write(td, fd, cap_rights_init(&rights, CAP_WRITE), &fp);
467 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
473 * Gather positioned write system call.
475 #ifndef _SYS_SYSPROTO_H_
476 struct pwritev_args {
484 sys_pwritev(struct thread *td, struct pwritev_args *uap)
489 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
492 error = kern_pwritev(td, uap->fd, auio, uap->offset);
498 kern_pwritev(td, fd, auio, offset)
508 error = fget_write(td, fd, cap_rights_init(&rights, CAP_PWRITE), &fp);
511 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
513 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
516 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
522 * Common code for writev and pwritev that writes data to
523 * a file using the passed in uio, offset, and flags.
526 dofilewrite(td, fd, fp, auio, offset, flags)
537 struct uio *ktruio = NULL;
540 auio->uio_rw = UIO_WRITE;
542 auio->uio_offset = offset;
544 if (KTRPOINT(td, KTR_GENIO))
545 ktruio = cloneuio(auio);
547 cnt = auio->uio_resid;
548 if (fp->f_type == DTYPE_VNODE &&
549 (fp->f_vnread_flags & FDEVFS_VNODE) == 0)
551 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
552 if (auio->uio_resid != cnt && (error == ERESTART ||
553 error == EINTR || error == EWOULDBLOCK))
555 /* Socket layer is responsible for issuing SIGPIPE. */
556 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
557 PROC_LOCK(td->td_proc);
558 tdsignal(td, SIGPIPE);
559 PROC_UNLOCK(td->td_proc);
562 cnt -= auio->uio_resid;
564 if (ktruio != NULL) {
565 ktruio->uio_resid = cnt;
566 ktrgenio(fd, UIO_WRITE, ktruio, error);
569 td->td_retval[0] = cnt;
574 * Truncate a file given a file descriptor.
576 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
577 * descriptor isn't writable.
580 kern_ftruncate(td, fd, length)
592 error = fget(td, fd, cap_rights_init(&rights, CAP_FTRUNCATE), &fp);
595 AUDIT_ARG_FILE(td->td_proc, fp);
596 if (!(fp->f_flag & FWRITE)) {
600 error = fo_truncate(fp, length, td->td_ucred, td);
605 #ifndef _SYS_SYSPROTO_H_
606 struct ftruncate_args {
613 sys_ftruncate(td, uap)
615 struct ftruncate_args *uap;
618 return (kern_ftruncate(td, uap->fd, uap->length));
621 #if defined(COMPAT_43)
622 #ifndef _SYS_SYSPROTO_H_
623 struct oftruncate_args {
631 struct oftruncate_args *uap;
634 return (kern_ftruncate(td, uap->fd, uap->length));
636 #endif /* COMPAT_43 */
638 #ifndef _SYS_SYSPROTO_H_
647 sys_ioctl(struct thread *td, struct ioctl_args *uap)
654 if (uap->com > 0xffffffff) {
656 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
657 td->td_proc->p_pid, td->td_name, uap->com);
658 uap->com &= 0xffffffff;
663 * Interpret high order word to find amount of data to be
664 * copied to/from the user's address space.
666 size = IOCPARM_LEN(com);
667 if ((size > IOCPARM_MAX) ||
668 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
669 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
670 ((com & IOC_OUT) && size == 0) ||
672 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
674 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
678 if (com & IOC_VOID) {
679 /* Integer argument. */
680 arg = (intptr_t)uap->data;
684 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
686 data = (void *)&uap->data;
688 error = copyin(uap->data, data, (u_int)size);
691 free(data, M_IOCTLOPS);
694 } else if (com & IOC_OUT) {
696 * Zero the buffer so the user always
697 * gets back something deterministic.
702 error = kern_ioctl(td, uap->fd, com, data);
704 if (error == 0 && (com & IOC_OUT))
705 error = copyout(data, uap->data, (u_int)size);
708 free(data, M_IOCTLOPS);
713 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
716 struct filedesc *fdp;
720 int error, tmp, locked;
725 fdp = td->td_proc->p_fd;
738 locked = LA_UNLOCKED;
744 if ((fp = fget_locked(fdp, fd)) == NULL) {
748 if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
749 fp = NULL; /* fhold() was not called yet */
753 if (locked == LA_SLOCKED) {
754 FILEDESC_SUNLOCK(fdp);
755 locked = LA_UNLOCKED;
758 error = fget(td, fd, cap_rights_init(&rights, CAP_IOCTL), &fp);
764 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
771 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
774 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
777 if ((tmp = *(int *)data))
778 atomic_set_int(&fp->f_flag, FNONBLOCK);
780 atomic_clear_int(&fp->f_flag, FNONBLOCK);
784 if ((tmp = *(int *)data))
785 atomic_set_int(&fp->f_flag, FASYNC);
787 atomic_clear_int(&fp->f_flag, FASYNC);
792 error = fo_ioctl(fp, com, data, td->td_ucred, td);
796 FILEDESC_XUNLOCK(fdp);
800 FILEDESC_SUNLOCK(fdp);
804 FILEDESC_UNLOCK_ASSERT(fdp);
813 poll_no_poll(int events)
816 * Return true for read/write. If the user asked for something
817 * special, return POLLNVAL, so that clients have a way of
818 * determining reliably whether or not the extended
819 * functionality is present without hard-coding knowledge
820 * of specific filesystem implementations.
822 if (events & ~POLLSTANDARD)
825 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
829 sys_pselect(struct thread *td, struct pselect_args *uap)
832 struct timeval tv, *tvp;
836 if (uap->ts != NULL) {
837 error = copyin(uap->ts, &ts, sizeof(ts));
840 TIMESPEC_TO_TIMEVAL(&tv, &ts);
844 if (uap->sm != NULL) {
845 error = copyin(uap->sm, &set, sizeof(set));
851 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
856 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
857 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
862 error = kern_sigprocmask(td, SIG_SETMASK, uset,
863 &td->td_oldsigmask, 0);
866 td->td_pflags |= TDP_OLDMASK;
868 * Make sure that ast() is called on return to
869 * usermode and TDP_OLDMASK is cleared, restoring old
873 td->td_flags |= TDF_ASTPENDING;
876 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
880 #ifndef _SYS_SYSPROTO_H_
883 fd_set *in, *ou, *ex;
888 sys_select(struct thread *td, struct select_args *uap)
890 struct timeval tv, *tvp;
893 if (uap->tv != NULL) {
894 error = copyin(uap->tv, &tv, sizeof(tv));
901 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
906 * In the unlikely case when user specified n greater then the last
907 * open file descriptor, check that no bits are set after the last
908 * valid fd. We must return EBADF if any is set.
910 * There are applications that rely on the behaviour.
912 * nd is fd_lastfile + 1.
915 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
921 if (nd >= ndu || fd_in == NULL)
925 bits = 0; /* silence gcc */
926 for (i = nd; i < ndu; i++) {
928 #if BYTE_ORDER == LITTLE_ENDIAN
929 addr = (char *)fd_in + b;
931 addr = (char *)fd_in;
932 if (abi_nfdbits == NFDBITS) {
933 addr += rounddown(b, sizeof(fd_mask)) +
934 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
936 addr += rounddown(b, sizeof(uint32_t)) +
937 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
947 if ((bits & (1 << (i % NBBY))) != 0)
954 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
955 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
957 struct filedesc *fdp;
959 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
960 * infds with the new FD_SETSIZE of 1024, and more than enough for
961 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
964 fd_mask s_selbits[howmany(2048, NFDBITS)];
965 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
967 sbintime_t asbt, precision, rsbt;
968 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
973 fdp = td->td_proc->p_fd;
975 lf = fdp->fd_lastfile;
979 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
982 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
985 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
990 * Allocate just enough bits for the non-null fd_sets. Use the
991 * preallocated auto buffer if possible.
993 nfdbits = roundup(nd, NFDBITS);
994 ncpbytes = nfdbits / NBBY;
995 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
998 nbufbytes += 2 * ncpbytes;
1000 nbufbytes += 2 * ncpbytes;
1002 nbufbytes += 2 * ncpbytes;
1003 if (nbufbytes <= sizeof s_selbits)
1004 selbits = &s_selbits[0];
1006 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1009 * Assign pointers into the bit buffers and fetch the input bits.
1010 * Put the output buffers together so that they can be bzeroed
1014 #define getbits(name, x) \
1016 if (name == NULL) { \
1020 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
1022 sbp += ncpbytes / sizeof *sbp; \
1023 error = copyin(name, ibits[x], ncpubytes); \
1026 bzero((char *)ibits[x] + ncpubytes, \
1027 ncpbytes - ncpubytes); \
1035 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1037 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1038 * we are running under 32-bit emulation. This should be more
1041 #define swizzle_fdset(bits) \
1042 if (abi_nfdbits != NFDBITS && bits != NULL) { \
1044 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
1045 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
1048 #define swizzle_fdset(bits)
1051 /* Make sure the bit order makes it through an ABI transition */
1052 swizzle_fdset(ibits[0]);
1053 swizzle_fdset(ibits[1]);
1054 swizzle_fdset(ibits[2]);
1057 bzero(selbits, nbufbytes / 2);
1062 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1063 rtv.tv_usec >= 1000000) {
1067 if (!timevalisset(&rtv))
1069 else if (rtv.tv_sec <= INT32_MAX) {
1070 rsbt = tvtosbt(rtv);
1072 precision >>= tc_precexp;
1073 if (TIMESEL(&asbt, rsbt))
1074 asbt += tc_tick_sbt;
1075 if (asbt <= INT64_MAX - rsbt)
1084 /* Iterate until the timeout expires or descriptors become ready. */
1086 error = selscan(td, ibits, obits, nd);
1087 if (error || td->td_retval[0] != 0)
1089 error = seltdwait(td, asbt, precision);
1092 error = selrescan(td, ibits, obits);
1093 if (error || td->td_retval[0] != 0)
1099 /* select is not restarted after signals... */
1100 if (error == ERESTART)
1102 if (error == EWOULDBLOCK)
1105 /* swizzle bit order back, if necessary */
1106 swizzle_fdset(obits[0]);
1107 swizzle_fdset(obits[1]);
1108 swizzle_fdset(obits[2]);
1109 #undef swizzle_fdset
1111 #define putbits(name, x) \
1112 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1122 if (selbits != &s_selbits[0])
1123 free(selbits, M_SELECT);
1128 * Convert a select bit set to poll flags.
1130 * The backend always returns POLLHUP/POLLERR if appropriate and we
1131 * return this as a set bit in any set.
1133 static int select_flags[3] = {
1134 POLLRDNORM | POLLHUP | POLLERR,
1135 POLLWRNORM | POLLHUP | POLLERR,
1136 POLLRDBAND | POLLERR
1140 * Compute the fo_poll flags required for a fd given by the index and
1141 * bit position in the fd_mask array.
1144 selflags(fd_mask **ibits, int idx, fd_mask bit)
1150 for (msk = 0; msk < 3; msk++) {
1151 if (ibits[msk] == NULL)
1153 if ((ibits[msk][idx] & bit) == 0)
1155 flags |= select_flags[msk];
1161 * Set the appropriate output bits given a mask of fired events and the
1162 * input bits originally requested.
1165 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1171 for (msk = 0; msk < 3; msk++) {
1172 if ((events & select_flags[msk]) == 0)
1174 if (ibits[msk] == NULL)
1176 if ((ibits[msk][idx] & bit) == 0)
1179 * XXX Check for a duplicate set. This can occur because a
1180 * socket calls selrecord() twice for each poll() call
1181 * resulting in two selfds per real fd. selrescan() will
1182 * call selsetbits twice as a result.
1184 if ((obits[msk][idx] & bit) != 0)
1186 obits[msk][idx] |= bit;
1194 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1196 cap_rights_t rights;
1198 cap_rights_init(&rights, CAP_EVENT);
1200 return (fget_unlocked(fdp, fd, &rights, 0, fpp, NULL));
1204 * Traverse the list of fds attached to this thread's seltd and check for
1208 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1210 struct filedesc *fdp;
1220 fdp = td->td_proc->p_fd;
1223 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1224 fd = (int)(uintptr_t)sfp->sf_cookie;
1226 selfdfree(stp, sfp);
1227 /* If the selinfo wasn't cleared the event didn't fire. */
1230 error = getselfd_cap(fdp, fd, &fp);
1234 bit = (fd_mask)1 << (fd % NFDBITS);
1235 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1238 n += selsetbits(ibits, obits, idx, bit, ev);
1241 td->td_retval[0] = n;
1246 * Perform the initial filedescriptor scan and register ourselves with
1250 selscan(td, ibits, obits, nfd)
1252 fd_mask **ibits, **obits;
1255 struct filedesc *fdp;
1258 int ev, flags, end, fd;
1262 fdp = td->td_proc->p_fd;
1264 for (idx = 0, fd = 0; fd < nfd; idx++) {
1265 end = imin(fd + NFDBITS, nfd);
1266 for (bit = 1; fd < end; bit <<= 1, fd++) {
1267 /* Compute the list of events we're interested in. */
1268 flags = selflags(ibits, idx, bit);
1271 error = getselfd_cap(fdp, fd, &fp);
1274 selfdalloc(td, (void *)(uintptr_t)fd);
1275 ev = fo_poll(fp, flags, td->td_ucred, td);
1278 n += selsetbits(ibits, obits, idx, bit, ev);
1282 td->td_retval[0] = n;
1286 #ifndef _SYS_SYSPROTO_H_
1296 struct poll_args *uap;
1298 struct pollfd *bits;
1299 struct pollfd smallbits[32];
1300 sbintime_t asbt, precision, rsbt;
1306 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1308 ni = nfds * sizeof(struct pollfd);
1309 if (ni > sizeof(smallbits))
1310 bits = malloc(ni, M_TEMP, M_WAITOK);
1313 error = copyin(uap->fds, bits, ni);
1317 if (uap->timeout != INFTIM) {
1318 if (uap->timeout < 0) {
1322 if (uap->timeout == 0)
1325 rsbt = SBT_1MS * uap->timeout;
1327 precision >>= tc_precexp;
1328 if (TIMESEL(&asbt, rsbt))
1329 asbt += tc_tick_sbt;
1335 /* Iterate until the timeout expires or descriptors become ready. */
1337 error = pollscan(td, bits, nfds);
1338 if (error || td->td_retval[0] != 0)
1340 error = seltdwait(td, asbt, precision);
1343 error = pollrescan(td);
1344 if (error || td->td_retval[0] != 0)
1350 /* poll is not restarted after signals... */
1351 if (error == ERESTART)
1353 if (error == EWOULDBLOCK)
1356 error = pollout(td, bits, uap->fds, nfds);
1361 if (ni > sizeof(smallbits))
1367 pollrescan(struct thread *td)
1373 struct filedesc *fdp;
1377 cap_rights_t rights;
1382 fdp = td->td_proc->p_fd;
1384 FILEDESC_SLOCK(fdp);
1385 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1386 fd = (struct pollfd *)sfp->sf_cookie;
1388 selfdfree(stp, sfp);
1389 /* If the selinfo wasn't cleared the event didn't fire. */
1392 fp = fdp->fd_ofiles[fd->fd].fde_file;
1395 cap_check(cap_rights(fdp, fd->fd),
1396 cap_rights_init(&rights, CAP_EVENT)) != 0)
1401 fd->revents = POLLNVAL;
1407 * Note: backend also returns POLLHUP and
1408 * POLLERR if appropriate.
1410 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1411 if (fd->revents != 0)
1414 FILEDESC_SUNLOCK(fdp);
1416 td->td_retval[0] = n;
1422 pollout(td, fds, ufds, nfd)
1425 struct pollfd *ufds;
1432 for (i = 0; i < nfd; i++) {
1433 error = copyout(&fds->revents, &ufds->revents,
1434 sizeof(ufds->revents));
1437 if (fds->revents != 0)
1442 td->td_retval[0] = n;
1447 pollscan(td, fds, nfd)
1452 struct filedesc *fdp = td->td_proc->p_fd;
1455 cap_rights_t rights;
1459 FILEDESC_SLOCK(fdp);
1460 for (i = 0; i < nfd; i++, fds++) {
1461 if (fds->fd > fdp->fd_lastfile) {
1462 fds->revents = POLLNVAL;
1464 } else if (fds->fd < 0) {
1467 fp = fdp->fd_ofiles[fds->fd].fde_file;
1470 cap_check(cap_rights(fdp, fds->fd),
1471 cap_rights_init(&rights, CAP_EVENT)) != 0)
1476 fds->revents = POLLNVAL;
1480 * Note: backend also returns POLLHUP and
1481 * POLLERR if appropriate.
1483 selfdalloc(td, fds);
1484 fds->revents = fo_poll(fp, fds->events,
1487 * POSIX requires POLLOUT to be never
1488 * set simultaneously with POLLHUP.
1490 if ((fds->revents & POLLHUP) != 0)
1491 fds->revents &= ~POLLOUT;
1493 if (fds->revents != 0)
1498 FILEDESC_SUNLOCK(fdp);
1499 td->td_retval[0] = n;
1504 * OpenBSD poll system call.
1506 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1508 #ifndef _SYS_SYSPROTO_H_
1509 struct openbsd_poll_args {
1516 sys_openbsd_poll(td, uap)
1517 register struct thread *td;
1518 register struct openbsd_poll_args *uap;
1520 return (sys_poll(td, (struct poll_args *)uap));
1524 * XXX This was created specifically to support netncp and netsmb. This
1525 * allows the caller to specify a socket to wait for events on. It returns
1526 * 0 if any events matched and an error otherwise. There is no way to
1527 * determine which events fired.
1530 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1533 sbintime_t asbt, precision, rsbt;
1536 precision = 0; /* stupid gcc! */
1539 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1540 rtv.tv_usec >= 1000000)
1542 if (!timevalisset(&rtv))
1544 else if (rtv.tv_sec <= INT32_MAX) {
1545 rsbt = tvtosbt(rtv);
1547 precision >>= tc_precexp;
1548 if (TIMESEL(&asbt, rsbt))
1549 asbt += tc_tick_sbt;
1550 if (asbt <= INT64_MAX - rsbt)
1560 * Iterate until the timeout expires or the socket becomes ready.
1563 selfdalloc(td, NULL);
1564 error = sopoll(so, events, NULL, td);
1565 /* error here is actually the ready events. */
1568 error = seltdwait(td, asbt, precision);
1573 /* XXX Duplicates ncp/smb behavior. */
1574 if (error == ERESTART)
1580 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1581 * have two select sets, one for read and another for write.
1584 selfdalloc(struct thread *td, void *cookie)
1589 if (stp->st_free1 == NULL)
1590 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1591 stp->st_free1->sf_td = stp;
1592 stp->st_free1->sf_cookie = cookie;
1593 if (stp->st_free2 == NULL)
1594 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1595 stp->st_free2->sf_td = stp;
1596 stp->st_free2->sf_cookie = cookie;
1600 selfdfree(struct seltd *stp, struct selfd *sfp)
1602 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1603 mtx_lock(sfp->sf_mtx);
1605 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1606 mtx_unlock(sfp->sf_mtx);
1607 uma_zfree(selfd_zone, sfp);
1610 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1613 struct selinfo *sip;
1617 * This feature is already provided by doselwakeup(), thus it is
1618 * enough to go for it.
1619 * Eventually, the context, should take care to avoid races
1620 * between thread calling select()/poll() and file descriptor
1621 * detaching, but, again, the races are just the same as
1624 doselwakeup(sip, -1);
1628 * Record a select request.
1631 selrecord(selector, sip)
1632 struct thread *selector;
1633 struct selinfo *sip;
1639 stp = selector->td_sel;
1641 * Don't record when doing a rescan.
1643 if (stp->st_flags & SELTD_RESCAN)
1646 * Grab one of the preallocated descriptors.
1649 if ((sfp = stp->st_free1) != NULL)
1650 stp->st_free1 = NULL;
1651 else if ((sfp = stp->st_free2) != NULL)
1652 stp->st_free2 = NULL;
1654 panic("selrecord: No free selfd on selq");
1657 mtxp = mtx_pool_find(mtxpool_select, sip);
1659 * Initialize the sfp and queue it in the thread.
1663 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1665 * Now that we've locked the sip, check for initialization.
1668 if (sip->si_mtx == NULL) {
1670 TAILQ_INIT(&sip->si_tdlist);
1673 * Add this thread to the list of selfds listening on this selinfo.
1675 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1676 mtx_unlock(sip->si_mtx);
1679 /* Wake up a selecting thread. */
1682 struct selinfo *sip;
1684 doselwakeup(sip, -1);
1687 /* Wake up a selecting thread, and set its priority. */
1689 selwakeuppri(sip, pri)
1690 struct selinfo *sip;
1693 doselwakeup(sip, pri);
1697 * Do a wakeup when a selectable event occurs.
1700 doselwakeup(sip, pri)
1701 struct selinfo *sip;
1708 /* If it's not initialized there can't be any waiters. */
1709 if (sip->si_mtx == NULL)
1712 * Locking the selinfo locks all selfds associated with it.
1714 mtx_lock(sip->si_mtx);
1715 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1717 * Once we remove this sfp from the list and clear the
1718 * sf_si seltdclear will know to ignore this si.
1720 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1723 mtx_lock(&stp->st_mtx);
1724 stp->st_flags |= SELTD_PENDING;
1725 cv_broadcastpri(&stp->st_wait, pri);
1726 mtx_unlock(&stp->st_mtx);
1728 mtx_unlock(sip->si_mtx);
1732 seltdinit(struct thread *td)
1736 if ((stp = td->td_sel) != NULL)
1738 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1739 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1740 cv_init(&stp->st_wait, "select");
1743 STAILQ_INIT(&stp->st_selq);
1747 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1754 * An event of interest may occur while we do not hold the seltd
1755 * locked so check the pending flag before we sleep.
1757 mtx_lock(&stp->st_mtx);
1759 * Any further calls to selrecord will be a rescan.
1761 stp->st_flags |= SELTD_RESCAN;
1762 if (stp->st_flags & SELTD_PENDING) {
1763 mtx_unlock(&stp->st_mtx);
1767 error = EWOULDBLOCK;
1769 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1770 sbt, precision, C_ABSOLUTE);
1772 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1773 mtx_unlock(&stp->st_mtx);
1779 seltdfini(struct thread *td)
1787 uma_zfree(selfd_zone, stp->st_free1);
1789 uma_zfree(selfd_zone, stp->st_free2);
1791 free(stp, M_SELECT);
1795 * Remove the references to the thread from all of the objects we were
1799 seltdclear(struct thread *td)
1806 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1807 selfdfree(stp, sfp);
1811 static void selectinit(void *);
1812 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1814 selectinit(void *dummy __unused)
1817 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1818 NULL, NULL, UMA_ALIGN_PTR, 0);
1819 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);