2 * Copyright (c) 1982, 1986, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)sys_generic.c 8.5 (Berkeley) 1/21/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_capsicum.h"
41 #include "opt_compat.h"
42 #include "opt_ktrace.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/capability.h>
48 #include <sys/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/fcntl.h>
53 #include <sys/signalvar.h>
54 #include <sys/socketvar.h>
56 #include <sys/kernel.h>
58 #include <sys/limits.h>
59 #include <sys/malloc.h>
61 #include <sys/resourcevar.h>
62 #include <sys/selinfo.h>
63 #include <sys/sleepqueue.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/vnode.h>
70 #include <sys/condvar.h>
72 #include <sys/ktrace.h>
75 #include <security/audit/audit.h>
77 int iosize_max_clamp = 1;
78 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
79 &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
81 * Assert that the return value of read(2) and write(2) syscalls fits
82 * into a register. If not, an architecture will need to provide the
83 * usermode wrappers to reconstruct the result.
85 CTASSERT(sizeof(register_t) >= sizeof(size_t));
87 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
88 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
89 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
91 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
93 static int pollscan(struct thread *, struct pollfd *, u_int);
94 static int pollrescan(struct thread *);
95 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
96 static int selrescan(struct thread *, fd_mask **, fd_mask **);
97 static void selfdalloc(struct thread *, void *);
98 static void selfdfree(struct seltd *, struct selfd *);
99 static int dofileread(struct thread *, int, struct file *, struct uio *,
101 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
103 static void doselwakeup(struct selinfo *, int);
104 static void seltdinit(struct thread *);
105 static int seltdwait(struct thread *, int);
106 static void seltdclear(struct thread *);
109 * One seltd per-thread allocated on demand as needed.
111 * t - protected by st_mtx
112 * k - Only accessed by curthread or read-only
115 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
116 struct selfd *st_free1; /* (k) free fd for read set. */
117 struct selfd *st_free2; /* (k) free fd for write set. */
118 struct mtx st_mtx; /* Protects struct seltd */
119 struct cv st_wait; /* (t) Wait channel. */
120 int st_flags; /* (t) SELTD_ flags. */
123 #define SELTD_PENDING 0x0001 /* We have pending events. */
124 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
127 * One selfd allocated per-thread per-file-descriptor.
128 * f - protected by sf_mtx
131 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
132 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
133 struct selinfo *sf_si; /* (f) selinfo when linked. */
134 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
135 struct seltd *sf_td; /* (k) owning seltd. */
136 void *sf_cookie; /* (k) fd or pollfd. */
139 static uma_zone_t selfd_zone;
140 static struct mtx_pool *mtxpool_select;
142 #ifndef _SYS_SYSPROTO_H_
152 struct read_args *uap;
158 if (uap->nbyte > IOSIZE_MAX)
160 aiov.iov_base = uap->buf;
161 aiov.iov_len = uap->nbyte;
162 auio.uio_iov = &aiov;
164 auio.uio_resid = uap->nbyte;
165 auio.uio_segflg = UIO_USERSPACE;
166 error = kern_readv(td, uap->fd, &auio);
171 * Positioned read system call
173 #ifndef _SYS_SYSPROTO_H_
185 struct pread_args *uap;
191 if (uap->nbyte > IOSIZE_MAX)
193 aiov.iov_base = uap->buf;
194 aiov.iov_len = uap->nbyte;
195 auio.uio_iov = &aiov;
197 auio.uio_resid = uap->nbyte;
198 auio.uio_segflg = UIO_USERSPACE;
199 error = kern_preadv(td, uap->fd, &auio, uap->offset);
204 freebsd6_pread(td, uap)
206 struct freebsd6_pread_args *uap;
208 struct pread_args oargs;
211 oargs.buf = uap->buf;
212 oargs.nbyte = uap->nbyte;
213 oargs.offset = uap->offset;
214 return (sys_pread(td, &oargs));
218 * Scatter read system call.
220 #ifndef _SYS_SYSPROTO_H_
228 sys_readv(struct thread *td, struct readv_args *uap)
233 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
236 error = kern_readv(td, uap->fd, auio);
242 kern_readv(struct thread *td, int fd, struct uio *auio)
247 error = fget_read(td, fd, CAP_READ | CAP_SEEK, &fp);
250 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
256 * Scatter positioned read system call.
258 #ifndef _SYS_SYSPROTO_H_
267 sys_preadv(struct thread *td, struct preadv_args *uap)
272 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
275 error = kern_preadv(td, uap->fd, auio, uap->offset);
281 kern_preadv(td, fd, auio, offset)
290 error = fget_read(td, fd, CAP_READ, &fp);
293 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
295 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
298 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
304 * Common code for readv and preadv that reads data in
305 * from a file using the passed in uio, offset, and flags.
308 dofileread(td, fd, fp, auio, offset, flags)
319 struct uio *ktruio = NULL;
322 /* Finish zero length reads right here */
323 if (auio->uio_resid == 0) {
324 td->td_retval[0] = 0;
327 auio->uio_rw = UIO_READ;
328 auio->uio_offset = offset;
331 if (KTRPOINT(td, KTR_GENIO))
332 ktruio = cloneuio(auio);
334 cnt = auio->uio_resid;
335 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
336 if (auio->uio_resid != cnt && (error == ERESTART ||
337 error == EINTR || error == EWOULDBLOCK))
340 cnt -= auio->uio_resid;
342 if (ktruio != NULL) {
343 ktruio->uio_resid = cnt;
344 ktrgenio(fd, UIO_READ, ktruio, error);
347 td->td_retval[0] = cnt;
351 #ifndef _SYS_SYSPROTO_H_
361 struct write_args *uap;
367 if (uap->nbyte > IOSIZE_MAX)
369 aiov.iov_base = (void *)(uintptr_t)uap->buf;
370 aiov.iov_len = uap->nbyte;
371 auio.uio_iov = &aiov;
373 auio.uio_resid = uap->nbyte;
374 auio.uio_segflg = UIO_USERSPACE;
375 error = kern_writev(td, uap->fd, &auio);
380 * Positioned write system call.
382 #ifndef _SYS_SYSPROTO_H_
394 struct pwrite_args *uap;
400 if (uap->nbyte > IOSIZE_MAX)
402 aiov.iov_base = (void *)(uintptr_t)uap->buf;
403 aiov.iov_len = uap->nbyte;
404 auio.uio_iov = &aiov;
406 auio.uio_resid = uap->nbyte;
407 auio.uio_segflg = UIO_USERSPACE;
408 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
413 freebsd6_pwrite(td, uap)
415 struct freebsd6_pwrite_args *uap;
417 struct pwrite_args oargs;
420 oargs.buf = uap->buf;
421 oargs.nbyte = uap->nbyte;
422 oargs.offset = uap->offset;
423 return (sys_pwrite(td, &oargs));
427 * Gather write system call.
429 #ifndef _SYS_SYSPROTO_H_
437 sys_writev(struct thread *td, struct writev_args *uap)
442 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
445 error = kern_writev(td, uap->fd, auio);
451 kern_writev(struct thread *td, int fd, struct uio *auio)
456 error = fget_write(td, fd, CAP_WRITE | CAP_SEEK, &fp);
459 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
465 * Gather positioned write system call.
467 #ifndef _SYS_SYSPROTO_H_
468 struct pwritev_args {
476 sys_pwritev(struct thread *td, struct pwritev_args *uap)
481 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
484 error = kern_pwritev(td, uap->fd, auio, uap->offset);
490 kern_pwritev(td, fd, auio, offset)
499 error = fget_write(td, fd, CAP_WRITE, &fp);
502 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
504 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
507 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
513 * Common code for writev and pwritev that writes data to
514 * a file using the passed in uio, offset, and flags.
517 dofilewrite(td, fd, fp, auio, offset, flags)
528 struct uio *ktruio = NULL;
531 auio->uio_rw = UIO_WRITE;
533 auio->uio_offset = offset;
535 if (KTRPOINT(td, KTR_GENIO))
536 ktruio = cloneuio(auio);
538 cnt = auio->uio_resid;
539 if (fp->f_type == DTYPE_VNODE)
541 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
542 if (auio->uio_resid != cnt && (error == ERESTART ||
543 error == EINTR || error == EWOULDBLOCK))
545 /* Socket layer is responsible for issuing SIGPIPE. */
546 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
547 PROC_LOCK(td->td_proc);
548 tdsignal(td, SIGPIPE);
549 PROC_UNLOCK(td->td_proc);
552 cnt -= auio->uio_resid;
554 if (ktruio != NULL) {
555 ktruio->uio_resid = cnt;
556 ktrgenio(fd, UIO_WRITE, ktruio, error);
559 td->td_retval[0] = cnt;
564 * Truncate a file given a file descriptor.
566 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
567 * descriptor isn't writable.
570 kern_ftruncate(td, fd, length)
581 error = fget(td, fd, CAP_FTRUNCATE, &fp);
584 AUDIT_ARG_FILE(td->td_proc, fp);
585 if (!(fp->f_flag & FWRITE)) {
589 error = fo_truncate(fp, length, td->td_ucred, td);
594 #ifndef _SYS_SYSPROTO_H_
595 struct ftruncate_args {
602 sys_ftruncate(td, uap)
604 struct ftruncate_args *uap;
607 return (kern_ftruncate(td, uap->fd, uap->length));
610 #if defined(COMPAT_43)
611 #ifndef _SYS_SYSPROTO_H_
612 struct oftruncate_args {
620 struct oftruncate_args *uap;
623 return (kern_ftruncate(td, uap->fd, uap->length));
625 #endif /* COMPAT_43 */
627 #ifndef _SYS_SYSPROTO_H_
636 sys_ioctl(struct thread *td, struct ioctl_args *uap)
643 if (uap->com > 0xffffffff) {
645 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
646 td->td_proc->p_pid, td->td_name, uap->com);
647 uap->com &= 0xffffffff;
652 * Interpret high order word to find amount of data to be
653 * copied to/from the user's address space.
655 size = IOCPARM_LEN(com);
656 if ((size > IOCPARM_MAX) ||
657 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
658 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
659 ((com & IOC_OUT) && size == 0) ||
661 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
663 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
667 if (com & IOC_VOID) {
668 /* Integer argument. */
669 arg = (intptr_t)uap->data;
673 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
675 data = (void *)&uap->data;
677 error = copyin(uap->data, data, (u_int)size);
680 free(data, M_IOCTLOPS);
683 } else if (com & IOC_OUT) {
685 * Zero the buffer so the user always
686 * gets back something deterministic.
691 error = kern_ioctl(td, uap->fd, com, data);
693 if (error == 0 && (com & IOC_OUT))
694 error = copyout(data, uap->data, (u_int)size);
697 free(data, M_IOCTLOPS);
702 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
705 struct filedesc *fdp;
711 if ((error = fget(td, fd, CAP_IOCTL, &fp)) != 0)
713 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
717 fdp = td->td_proc->p_fd;
721 fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
722 FILEDESC_XUNLOCK(fdp);
726 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
727 FILEDESC_XUNLOCK(fdp);
730 if ((tmp = *(int *)data))
731 atomic_set_int(&fp->f_flag, FNONBLOCK);
733 atomic_clear_int(&fp->f_flag, FNONBLOCK);
737 if ((tmp = *(int *)data))
738 atomic_set_int(&fp->f_flag, FASYNC);
740 atomic_clear_int(&fp->f_flag, FASYNC);
745 error = fo_ioctl(fp, com, data, td->td_ucred, td);
752 poll_no_poll(int events)
755 * Return true for read/write. If the user asked for something
756 * special, return POLLNVAL, so that clients have a way of
757 * determining reliably whether or not the extended
758 * functionality is present without hard-coding knowledge
759 * of specific filesystem implementations.
761 if (events & ~POLLSTANDARD)
764 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
768 sys_pselect(struct thread *td, struct pselect_args *uap)
771 struct timeval tv, *tvp;
775 if (uap->ts != NULL) {
776 error = copyin(uap->ts, &ts, sizeof(ts));
779 TIMESPEC_TO_TIMEVAL(&tv, &ts);
783 if (uap->sm != NULL) {
784 error = copyin(uap->sm, &set, sizeof(set));
790 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
795 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
796 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
801 error = kern_sigprocmask(td, SIG_SETMASK, uset,
802 &td->td_oldsigmask, 0);
805 td->td_pflags |= TDP_OLDMASK;
807 * Make sure that ast() is called on return to
808 * usermode and TDP_OLDMASK is cleared, restoring old
812 td->td_flags |= TDF_ASTPENDING;
815 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
819 #ifndef _SYS_SYSPROTO_H_
822 fd_set *in, *ou, *ex;
827 sys_select(struct thread *td, struct select_args *uap)
829 struct timeval tv, *tvp;
832 if (uap->tv != NULL) {
833 error = copyin(uap->tv, &tv, sizeof(tv));
840 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
845 * In the unlikely case when user specified n greater then the last
846 * open file descriptor, check that no bits are set after the last
847 * valid fd. We must return EBADF if any is set.
849 * There are applications that rely on the behaviour.
851 * nd is fd_lastfile + 1.
854 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
860 if (nd >= ndu || fd_in == NULL)
864 bits = 0; /* silence gcc */
865 for (i = nd; i < ndu; i++) {
867 #if BYTE_ORDER == LITTLE_ENDIAN
868 addr = (char *)fd_in + b;
870 addr = (char *)fd_in;
871 if (abi_nfdbits == NFDBITS) {
872 addr += rounddown(b, sizeof(fd_mask)) +
873 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
875 addr += rounddown(b, sizeof(uint32_t)) +
876 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
886 if ((bits & (1 << (i % NBBY))) != 0)
893 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
894 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
896 struct filedesc *fdp;
898 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
899 * infds with the new FD_SETSIZE of 1024, and more than enough for
900 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
903 fd_mask s_selbits[howmany(2048, NFDBITS)];
904 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
905 struct timeval atv, rtv, ttv;
906 int error, lf, ndu, timo;
907 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
911 fdp = td->td_proc->p_fd;
913 lf = fdp->fd_lastfile;
917 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
920 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
923 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
928 * Allocate just enough bits for the non-null fd_sets. Use the
929 * preallocated auto buffer if possible.
931 nfdbits = roundup(nd, NFDBITS);
932 ncpbytes = nfdbits / NBBY;
933 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
936 nbufbytes += 2 * ncpbytes;
938 nbufbytes += 2 * ncpbytes;
940 nbufbytes += 2 * ncpbytes;
941 if (nbufbytes <= sizeof s_selbits)
942 selbits = &s_selbits[0];
944 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
947 * Assign pointers into the bit buffers and fetch the input bits.
948 * Put the output buffers together so that they can be bzeroed
952 #define getbits(name, x) \
954 if (name == NULL) { \
958 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
960 sbp += ncpbytes / sizeof *sbp; \
961 error = copyin(name, ibits[x], ncpubytes); \
964 bzero((char *)ibits[x] + ncpubytes, \
965 ncpbytes - ncpubytes); \
973 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
975 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
976 * we are running under 32-bit emulation. This should be more
979 #define swizzle_fdset(bits) \
980 if (abi_nfdbits != NFDBITS && bits != NULL) { \
982 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
983 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
986 #define swizzle_fdset(bits)
989 /* Make sure the bit order makes it through an ABI transition */
990 swizzle_fdset(ibits[0]);
991 swizzle_fdset(ibits[1]);
992 swizzle_fdset(ibits[2]);
995 bzero(selbits, nbufbytes / 2);
999 if (itimerfix(&atv)) {
1003 getmicrouptime(&rtv);
1004 timevaladd(&atv, &rtv);
1011 /* Iterate until the timeout expires or descriptors become ready. */
1013 error = selscan(td, ibits, obits, nd);
1014 if (error || td->td_retval[0] != 0)
1016 if (atv.tv_sec || atv.tv_usec) {
1017 getmicrouptime(&rtv);
1018 if (timevalcmp(&rtv, &atv, >=))
1021 timevalsub(&ttv, &rtv);
1022 timo = ttv.tv_sec > 24 * 60 * 60 ?
1023 24 * 60 * 60 * hz : tvtohz(&ttv);
1025 error = seltdwait(td, timo);
1028 error = selrescan(td, ibits, obits);
1029 if (error || td->td_retval[0] != 0)
1035 /* select is not restarted after signals... */
1036 if (error == ERESTART)
1038 if (error == EWOULDBLOCK)
1041 /* swizzle bit order back, if necessary */
1042 swizzle_fdset(obits[0]);
1043 swizzle_fdset(obits[1]);
1044 swizzle_fdset(obits[2]);
1045 #undef swizzle_fdset
1047 #define putbits(name, x) \
1048 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1058 if (selbits != &s_selbits[0])
1059 free(selbits, M_SELECT);
1064 * Convert a select bit set to poll flags.
1066 * The backend always returns POLLHUP/POLLERR if appropriate and we
1067 * return this as a set bit in any set.
1069 static int select_flags[3] = {
1070 POLLRDNORM | POLLHUP | POLLERR,
1071 POLLWRNORM | POLLHUP | POLLERR,
1072 POLLRDBAND | POLLERR
1076 * Compute the fo_poll flags required for a fd given by the index and
1077 * bit position in the fd_mask array.
1080 selflags(fd_mask **ibits, int idx, fd_mask bit)
1086 for (msk = 0; msk < 3; msk++) {
1087 if (ibits[msk] == NULL)
1089 if ((ibits[msk][idx] & bit) == 0)
1091 flags |= select_flags[msk];
1097 * Set the appropriate output bits given a mask of fired events and the
1098 * input bits originally requested.
1101 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1107 for (msk = 0; msk < 3; msk++) {
1108 if ((events & select_flags[msk]) == 0)
1110 if (ibits[msk] == NULL)
1112 if ((ibits[msk][idx] & bit) == 0)
1115 * XXX Check for a duplicate set. This can occur because a
1116 * socket calls selrecord() twice for each poll() call
1117 * resulting in two selfds per real fd. selrescan() will
1118 * call selsetbits twice as a result.
1120 if ((obits[msk][idx] & bit) != 0)
1122 obits[msk][idx] |= bit;
1130 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1134 struct file *fp_fromcap;
1138 if ((fp = fget_unlocked(fdp, fd)) == NULL)
1142 * If the file descriptor is for a capability, test rights and use
1143 * the file descriptor references by the capability.
1145 error = cap_funwrap(fp, CAP_POLL_EVENT, &fp_fromcap);
1147 fdrop(fp, curthread);
1150 if (fp != fp_fromcap) {
1152 fdrop(fp, curthread);
1155 #endif /* CAPABILITIES */
1161 * Traverse the list of fds attached to this thread's seltd and check for
1165 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1167 struct filedesc *fdp;
1177 fdp = td->td_proc->p_fd;
1180 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1181 fd = (int)(uintptr_t)sfp->sf_cookie;
1183 selfdfree(stp, sfp);
1184 /* If the selinfo wasn't cleared the event didn't fire. */
1187 error = getselfd_cap(fdp, fd, &fp);
1191 bit = (fd_mask)1 << (fd % NFDBITS);
1192 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1195 n += selsetbits(ibits, obits, idx, bit, ev);
1198 td->td_retval[0] = n;
1203 * Perform the initial filedescriptor scan and register ourselves with
1207 selscan(td, ibits, obits, nfd)
1209 fd_mask **ibits, **obits;
1212 struct filedesc *fdp;
1215 int ev, flags, end, fd;
1219 fdp = td->td_proc->p_fd;
1221 for (idx = 0, fd = 0; fd < nfd; idx++) {
1222 end = imin(fd + NFDBITS, nfd);
1223 for (bit = 1; fd < end; bit <<= 1, fd++) {
1224 /* Compute the list of events we're interested in. */
1225 flags = selflags(ibits, idx, bit);
1228 error = getselfd_cap(fdp, fd, &fp);
1231 selfdalloc(td, (void *)(uintptr_t)fd);
1232 ev = fo_poll(fp, flags, td->td_ucred, td);
1235 n += selsetbits(ibits, obits, idx, bit, ev);
1239 td->td_retval[0] = n;
1243 #ifndef _SYS_SYSPROTO_H_
1253 struct poll_args *uap;
1255 struct pollfd *bits;
1256 struct pollfd smallbits[32];
1257 struct timeval atv, rtv, ttv;
1263 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1265 ni = nfds * sizeof(struct pollfd);
1266 if (ni > sizeof(smallbits))
1267 bits = malloc(ni, M_TEMP, M_WAITOK);
1270 error = copyin(uap->fds, bits, ni);
1273 if (uap->timeout != INFTIM) {
1274 atv.tv_sec = uap->timeout / 1000;
1275 atv.tv_usec = (uap->timeout % 1000) * 1000;
1276 if (itimerfix(&atv)) {
1280 getmicrouptime(&rtv);
1281 timevaladd(&atv, &rtv);
1288 /* Iterate until the timeout expires or descriptors become ready. */
1290 error = pollscan(td, bits, nfds);
1291 if (error || td->td_retval[0] != 0)
1293 if (atv.tv_sec || atv.tv_usec) {
1294 getmicrouptime(&rtv);
1295 if (timevalcmp(&rtv, &atv, >=))
1298 timevalsub(&ttv, &rtv);
1299 timo = ttv.tv_sec > 24 * 60 * 60 ?
1300 24 * 60 * 60 * hz : tvtohz(&ttv);
1302 error = seltdwait(td, timo);
1305 error = pollrescan(td);
1306 if (error || td->td_retval[0] != 0)
1312 /* poll is not restarted after signals... */
1313 if (error == ERESTART)
1315 if (error == EWOULDBLOCK)
1318 error = pollout(td, bits, uap->fds, nfds);
1323 if (ni > sizeof(smallbits))
1329 pollrescan(struct thread *td)
1335 struct filedesc *fdp;
1341 fdp = td->td_proc->p_fd;
1343 FILEDESC_SLOCK(fdp);
1344 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1345 fd = (struct pollfd *)sfp->sf_cookie;
1347 selfdfree(stp, sfp);
1348 /* If the selinfo wasn't cleared the event didn't fire. */
1351 fp = fdp->fd_ofiles[fd->fd];
1354 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1358 fd->revents = POLLNVAL;
1364 * Note: backend also returns POLLHUP and
1365 * POLLERR if appropriate.
1367 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1368 if (fd->revents != 0)
1371 FILEDESC_SUNLOCK(fdp);
1373 td->td_retval[0] = n;
1379 pollout(td, fds, ufds, nfd)
1382 struct pollfd *ufds;
1389 for (i = 0; i < nfd; i++) {
1390 error = copyout(&fds->revents, &ufds->revents,
1391 sizeof(ufds->revents));
1394 if (fds->revents != 0)
1399 td->td_retval[0] = n;
1404 pollscan(td, fds, nfd)
1409 struct filedesc *fdp = td->td_proc->p_fd;
1414 FILEDESC_SLOCK(fdp);
1415 for (i = 0; i < nfd; i++, fds++) {
1416 if (fds->fd >= fdp->fd_nfiles) {
1417 fds->revents = POLLNVAL;
1419 } else if (fds->fd < 0) {
1422 fp = fdp->fd_ofiles[fds->fd];
1425 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1429 fds->revents = POLLNVAL;
1433 * Note: backend also returns POLLHUP and
1434 * POLLERR if appropriate.
1436 selfdalloc(td, fds);
1437 fds->revents = fo_poll(fp, fds->events,
1440 * POSIX requires POLLOUT to be never
1441 * set simultaneously with POLLHUP.
1443 if ((fds->revents & POLLHUP) != 0)
1444 fds->revents &= ~POLLOUT;
1446 if (fds->revents != 0)
1451 FILEDESC_SUNLOCK(fdp);
1452 td->td_retval[0] = n;
1457 * OpenBSD poll system call.
1459 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1461 #ifndef _SYS_SYSPROTO_H_
1462 struct openbsd_poll_args {
1469 sys_openbsd_poll(td, uap)
1470 register struct thread *td;
1471 register struct openbsd_poll_args *uap;
1473 return (sys_poll(td, (struct poll_args *)uap));
1477 * XXX This was created specifically to support netncp and netsmb. This
1478 * allows the caller to specify a socket to wait for events on. It returns
1479 * 0 if any events matched and an error otherwise. There is no way to
1480 * determine which events fired.
1483 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1485 struct timeval atv, rtv, ttv;
1490 if (itimerfix(&atv))
1492 getmicrouptime(&rtv);
1493 timevaladd(&atv, &rtv);
1502 * Iterate until the timeout expires or the socket becomes ready.
1505 selfdalloc(td, NULL);
1506 error = sopoll(so, events, NULL, td);
1507 /* error here is actually the ready events. */
1510 if (atv.tv_sec || atv.tv_usec) {
1511 getmicrouptime(&rtv);
1512 if (timevalcmp(&rtv, &atv, >=)) {
1514 return (EWOULDBLOCK);
1517 timevalsub(&ttv, &rtv);
1518 timo = ttv.tv_sec > 24 * 60 * 60 ?
1519 24 * 60 * 60 * hz : tvtohz(&ttv);
1521 error = seltdwait(td, timo);
1526 /* XXX Duplicates ncp/smb behavior. */
1527 if (error == ERESTART)
1533 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1534 * have two select sets, one for read and another for write.
1537 selfdalloc(struct thread *td, void *cookie)
1542 if (stp->st_free1 == NULL)
1543 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1544 stp->st_free1->sf_td = stp;
1545 stp->st_free1->sf_cookie = cookie;
1546 if (stp->st_free2 == NULL)
1547 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1548 stp->st_free2->sf_td = stp;
1549 stp->st_free2->sf_cookie = cookie;
1553 selfdfree(struct seltd *stp, struct selfd *sfp)
1555 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1556 mtx_lock(sfp->sf_mtx);
1558 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1559 mtx_unlock(sfp->sf_mtx);
1560 uma_zfree(selfd_zone, sfp);
1563 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1566 struct selinfo *sip;
1570 * This feature is already provided by doselwakeup(), thus it is
1571 * enough to go for it.
1572 * Eventually, the context, should take care to avoid races
1573 * between thread calling select()/poll() and file descriptor
1574 * detaching, but, again, the races are just the same as
1577 doselwakeup(sip, -1);
1581 * Record a select request.
1584 selrecord(selector, sip)
1585 struct thread *selector;
1586 struct selinfo *sip;
1592 stp = selector->td_sel;
1594 * Don't record when doing a rescan.
1596 if (stp->st_flags & SELTD_RESCAN)
1599 * Grab one of the preallocated descriptors.
1602 if ((sfp = stp->st_free1) != NULL)
1603 stp->st_free1 = NULL;
1604 else if ((sfp = stp->st_free2) != NULL)
1605 stp->st_free2 = NULL;
1607 panic("selrecord: No free selfd on selq");
1610 mtxp = mtx_pool_find(mtxpool_select, sip);
1612 * Initialize the sfp and queue it in the thread.
1616 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1618 * Now that we've locked the sip, check for initialization.
1621 if (sip->si_mtx == NULL) {
1623 TAILQ_INIT(&sip->si_tdlist);
1626 * Add this thread to the list of selfds listening on this selinfo.
1628 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1629 mtx_unlock(sip->si_mtx);
1632 /* Wake up a selecting thread. */
1635 struct selinfo *sip;
1637 doselwakeup(sip, -1);
1640 /* Wake up a selecting thread, and set its priority. */
1642 selwakeuppri(sip, pri)
1643 struct selinfo *sip;
1646 doselwakeup(sip, pri);
1650 * Do a wakeup when a selectable event occurs.
1653 doselwakeup(sip, pri)
1654 struct selinfo *sip;
1661 /* If it's not initialized there can't be any waiters. */
1662 if (sip->si_mtx == NULL)
1665 * Locking the selinfo locks all selfds associated with it.
1667 mtx_lock(sip->si_mtx);
1668 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1670 * Once we remove this sfp from the list and clear the
1671 * sf_si seltdclear will know to ignore this si.
1673 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1676 mtx_lock(&stp->st_mtx);
1677 stp->st_flags |= SELTD_PENDING;
1678 cv_broadcastpri(&stp->st_wait, pri);
1679 mtx_unlock(&stp->st_mtx);
1681 mtx_unlock(sip->si_mtx);
1685 seltdinit(struct thread *td)
1689 if ((stp = td->td_sel) != NULL)
1691 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1692 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1693 cv_init(&stp->st_wait, "select");
1696 STAILQ_INIT(&stp->st_selq);
1700 seltdwait(struct thread *td, int timo)
1707 * An event of interest may occur while we do not hold the seltd
1708 * locked so check the pending flag before we sleep.
1710 mtx_lock(&stp->st_mtx);
1712 * Any further calls to selrecord will be a rescan.
1714 stp->st_flags |= SELTD_RESCAN;
1715 if (stp->st_flags & SELTD_PENDING) {
1716 mtx_unlock(&stp->st_mtx);
1720 error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1722 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1723 mtx_unlock(&stp->st_mtx);
1729 seltdfini(struct thread *td)
1737 uma_zfree(selfd_zone, stp->st_free1);
1739 uma_zfree(selfd_zone, stp->st_free2);
1741 free(stp, M_SELECT);
1745 * Remove the references to the thread from all of the objects we were
1749 seltdclear(struct thread *td)
1756 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1757 selfdfree(stp, sfp);
1761 static void selectinit(void *);
1762 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1764 selectinit(void *dummy __unused)
1767 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1768 NULL, NULL, UMA_ALIGN_PTR, 0);
1769 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);