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_compat.h"
41 #include "opt_ktrace.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/sysproto.h>
46 #include <sys/filedesc.h>
47 #include <sys/filio.h>
48 #include <sys/fcntl.h>
51 #include <sys/signalvar.h>
52 #include <sys/socketvar.h>
54 #include <sys/kernel.h>
56 #include <sys/limits.h>
57 #include <sys/malloc.h>
59 #include <sys/resourcevar.h>
60 #include <sys/selinfo.h>
61 #include <sys/sleepqueue.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/vnode.h>
68 #include <sys/condvar.h>
70 #include <sys/ktrace.h>
73 #include <security/audit/audit.h>
75 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
76 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
77 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
79 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
81 static int pollscan(struct thread *, struct pollfd *, u_int);
82 static int pollrescan(struct thread *);
83 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
84 static int selrescan(struct thread *, fd_mask **, fd_mask **);
85 static void selfdalloc(struct thread *, void *);
86 static void selfdfree(struct seltd *, struct selfd *);
87 static int dofileread(struct thread *, int, struct file *, struct uio *,
89 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
91 static void doselwakeup(struct selinfo *, int);
92 static void seltdinit(struct thread *);
93 static int seltdwait(struct thread *, int);
94 static void seltdclear(struct thread *);
97 * One seltd per-thread allocated on demand as needed.
99 * t - protected by st_mtx
100 * k - Only accessed by curthread or read-only
103 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
104 struct selfd *st_free1; /* (k) free fd for read set. */
105 struct selfd *st_free2; /* (k) free fd for write set. */
106 struct mtx st_mtx; /* Protects struct seltd */
107 struct cv st_wait; /* (t) Wait channel. */
108 int st_flags; /* (t) SELTD_ flags. */
111 #define SELTD_PENDING 0x0001 /* We have pending events. */
112 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
115 * One selfd allocated per-thread per-file-descriptor.
116 * f - protected by sf_mtx
119 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
120 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
121 struct selinfo *sf_si; /* (f) selinfo when linked. */
122 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
123 struct seltd *sf_td; /* (k) owning seltd. */
124 void *sf_cookie; /* (k) fd or pollfd. */
127 static uma_zone_t selfd_zone;
128 static struct mtx_pool *mtxpool_select;
130 #ifndef _SYS_SYSPROTO_H_
140 struct read_args *uap;
146 if (uap->nbyte > INT_MAX)
148 aiov.iov_base = uap->buf;
149 aiov.iov_len = uap->nbyte;
150 auio.uio_iov = &aiov;
152 auio.uio_resid = uap->nbyte;
153 auio.uio_segflg = UIO_USERSPACE;
154 error = kern_readv(td, uap->fd, &auio);
159 * Positioned read system call
161 #ifndef _SYS_SYSPROTO_H_
173 struct pread_args *uap;
179 if (uap->nbyte > INT_MAX)
181 aiov.iov_base = uap->buf;
182 aiov.iov_len = uap->nbyte;
183 auio.uio_iov = &aiov;
185 auio.uio_resid = uap->nbyte;
186 auio.uio_segflg = UIO_USERSPACE;
187 error = kern_preadv(td, uap->fd, &auio, uap->offset);
192 freebsd6_pread(td, uap)
194 struct freebsd6_pread_args *uap;
196 struct pread_args oargs;
199 oargs.buf = uap->buf;
200 oargs.nbyte = uap->nbyte;
201 oargs.offset = uap->offset;
202 return (pread(td, &oargs));
206 * Scatter read system call.
208 #ifndef _SYS_SYSPROTO_H_
216 readv(struct thread *td, struct readv_args *uap)
221 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
224 error = kern_readv(td, uap->fd, auio);
230 kern_readv(struct thread *td, int fd, struct uio *auio)
235 error = fget_read(td, fd, &fp);
238 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
244 * Scatter positioned read system call.
246 #ifndef _SYS_SYSPROTO_H_
255 preadv(struct thread *td, struct preadv_args *uap)
260 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
263 error = kern_preadv(td, uap->fd, auio, uap->offset);
269 kern_preadv(td, fd, auio, offset)
278 error = fget_read(td, fd, &fp);
281 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
283 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
286 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
292 * Common code for readv and preadv that reads data in
293 * from a file using the passed in uio, offset, and flags.
296 dofileread(td, fd, fp, auio, offset, flags)
307 struct uio *ktruio = NULL;
310 /* Finish zero length reads right here */
311 if (auio->uio_resid == 0) {
312 td->td_retval[0] = 0;
315 auio->uio_rw = UIO_READ;
316 auio->uio_offset = offset;
319 if (KTRPOINT(td, KTR_GENIO))
320 ktruio = cloneuio(auio);
322 cnt = auio->uio_resid;
323 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
324 if (auio->uio_resid != cnt && (error == ERESTART ||
325 error == EINTR || error == EWOULDBLOCK))
328 cnt -= auio->uio_resid;
330 if (ktruio != NULL) {
331 ktruio->uio_resid = cnt;
332 ktrgenio(fd, UIO_READ, ktruio, error);
335 td->td_retval[0] = cnt;
339 #ifndef _SYS_SYSPROTO_H_
349 struct write_args *uap;
355 if (uap->nbyte > INT_MAX)
357 aiov.iov_base = (void *)(uintptr_t)uap->buf;
358 aiov.iov_len = uap->nbyte;
359 auio.uio_iov = &aiov;
361 auio.uio_resid = uap->nbyte;
362 auio.uio_segflg = UIO_USERSPACE;
363 error = kern_writev(td, uap->fd, &auio);
368 * Positioned write system call.
370 #ifndef _SYS_SYSPROTO_H_
382 struct pwrite_args *uap;
388 if (uap->nbyte > INT_MAX)
390 aiov.iov_base = (void *)(uintptr_t)uap->buf;
391 aiov.iov_len = uap->nbyte;
392 auio.uio_iov = &aiov;
394 auio.uio_resid = uap->nbyte;
395 auio.uio_segflg = UIO_USERSPACE;
396 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
401 freebsd6_pwrite(td, uap)
403 struct freebsd6_pwrite_args *uap;
405 struct pwrite_args oargs;
408 oargs.buf = uap->buf;
409 oargs.nbyte = uap->nbyte;
410 oargs.offset = uap->offset;
411 return (pwrite(td, &oargs));
415 * Gather write system call.
417 #ifndef _SYS_SYSPROTO_H_
425 writev(struct thread *td, struct writev_args *uap)
430 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
433 error = kern_writev(td, uap->fd, auio);
439 kern_writev(struct thread *td, int fd, struct uio *auio)
444 error = fget_write(td, fd, &fp);
447 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
453 * Gather positioned write system call.
455 #ifndef _SYS_SYSPROTO_H_
456 struct pwritev_args {
464 pwritev(struct thread *td, struct pwritev_args *uap)
469 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
472 error = kern_pwritev(td, uap->fd, auio, uap->offset);
478 kern_pwritev(td, fd, auio, offset)
487 error = fget_write(td, fd, &fp);
490 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
492 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
495 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
501 * Common code for writev and pwritev that writes data to
502 * a file using the passed in uio, offset, and flags.
505 dofilewrite(td, fd, fp, auio, offset, flags)
516 struct uio *ktruio = NULL;
519 auio->uio_rw = UIO_WRITE;
521 auio->uio_offset = offset;
523 if (KTRPOINT(td, KTR_GENIO))
524 ktruio = cloneuio(auio);
526 cnt = auio->uio_resid;
527 if (fp->f_type == DTYPE_VNODE)
529 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
530 if (auio->uio_resid != cnt && (error == ERESTART ||
531 error == EINTR || error == EWOULDBLOCK))
533 /* Socket layer is responsible for issuing SIGPIPE. */
534 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
535 PROC_LOCK(td->td_proc);
536 tdksignal(td, SIGPIPE, NULL);
537 PROC_UNLOCK(td->td_proc);
540 cnt -= auio->uio_resid;
542 if (ktruio != NULL) {
543 ktruio->uio_resid = cnt;
544 ktrgenio(fd, UIO_WRITE, ktruio, error);
547 td->td_retval[0] = cnt;
552 * Truncate a file given a file descriptor.
554 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
555 * descriptor isn't writable.
558 kern_ftruncate(td, fd, length)
569 error = fget(td, fd, &fp);
572 AUDIT_ARG_FILE(td->td_proc, fp);
573 if (!(fp->f_flag & FWRITE)) {
577 error = fo_truncate(fp, length, td->td_ucred, td);
582 #ifndef _SYS_SYSPROTO_H_
583 struct ftruncate_args {
592 struct ftruncate_args *uap;
595 return (kern_ftruncate(td, uap->fd, uap->length));
598 #if defined(COMPAT_43)
599 #ifndef _SYS_SYSPROTO_H_
600 struct oftruncate_args {
608 struct oftruncate_args *uap;
611 return (kern_ftruncate(td, uap->fd, uap->length));
613 #endif /* COMPAT_43 */
615 #ifndef _SYS_SYSPROTO_H_
624 ioctl(struct thread *td, struct ioctl_args *uap)
631 if (uap->com > 0xffffffff) {
633 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
634 td->td_proc->p_pid, td->td_name, uap->com);
635 uap->com &= 0xffffffff;
640 * Interpret high order word to find amount of data to be
641 * copied to/from the user's address space.
643 size = IOCPARM_LEN(com);
644 if ((size > IOCPARM_MAX) ||
645 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
646 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
647 ((com & IOC_OUT) && size == 0) ||
649 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
651 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
655 if (com & IOC_VOID) {
656 /* Integer argument. */
657 arg = (intptr_t)uap->data;
661 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
663 data = (void *)&uap->data;
665 error = copyin(uap->data, data, (u_int)size);
668 free(data, M_IOCTLOPS);
671 } else if (com & IOC_OUT) {
673 * Zero the buffer so the user always
674 * gets back something deterministic.
679 error = kern_ioctl(td, uap->fd, com, data);
681 if (error == 0 && (com & IOC_OUT))
682 error = copyout(data, uap->data, (u_int)size);
685 free(data, M_IOCTLOPS);
690 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
693 struct filedesc *fdp;
699 if ((error = fget(td, fd, &fp)) != 0)
701 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
705 fdp = td->td_proc->p_fd;
709 fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
710 FILEDESC_XUNLOCK(fdp);
714 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
715 FILEDESC_XUNLOCK(fdp);
718 if ((tmp = *(int *)data))
719 atomic_set_int(&fp->f_flag, FNONBLOCK);
721 atomic_clear_int(&fp->f_flag, FNONBLOCK);
725 if ((tmp = *(int *)data))
726 atomic_set_int(&fp->f_flag, FASYNC);
728 atomic_clear_int(&fp->f_flag, FASYNC);
733 error = fo_ioctl(fp, com, data, td->td_ucred, td);
740 poll_no_poll(int events)
743 * Return true for read/write. If the user asked for something
744 * special, return POLLNVAL, so that clients have a way of
745 * determining reliably whether or not the extended
746 * functionality is present without hard-coding knowledge
747 * of specific filesystem implementations.
749 if (events & ~POLLSTANDARD)
752 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
756 pselect(struct thread *td, struct pselect_args *uap)
759 struct timeval tv, *tvp;
763 if (uap->ts != NULL) {
764 error = copyin(uap->ts, &ts, sizeof(ts));
767 TIMESPEC_TO_TIMEVAL(&tv, &ts);
771 if (uap->sm != NULL) {
772 error = copyin(uap->sm, &set, sizeof(set));
778 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
783 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
784 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
789 error = kern_sigprocmask(td, SIG_SETMASK, uset,
790 &td->td_oldsigmask, 0);
793 td->td_pflags |= TDP_OLDMASK;
795 * Make sure that ast() is called on return to
796 * usermode and TDP_OLDMASK is cleared, restoring old
800 td->td_flags |= TDF_ASTPENDING;
803 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
807 #ifndef _SYS_SYSPROTO_H_
810 fd_set *in, *ou, *ex;
815 select(struct thread *td, struct select_args *uap)
817 struct timeval tv, *tvp;
820 if (uap->tv != NULL) {
821 error = copyin(uap->tv, &tv, sizeof(tv));
828 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
833 * In the unlikely case when user specified n greater then the last
834 * open file descriptor, check that no bits are set after the last
835 * valid fd. We must return EBADF if any is set.
837 * There are applications that rely on the behaviour.
839 * nd is fd_lastfile + 1.
842 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
848 if (nd >= ndu || fd_in == NULL)
852 bits = 0; /* silence gcc */
853 for (i = nd; i < ndu; i++) {
855 #if BYTE_ORDER == LITTLE_ENDIAN
856 addr = (char *)fd_in + b;
858 addr = (char *)fd_in;
859 if (abi_nfdbits == NFDBITS) {
860 addr += rounddown(b, sizeof(fd_mask)) +
861 sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
863 addr += rounddown(b, sizeof(uint32_t)) +
864 sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
874 if ((bits & (1 << (i % NBBY))) != 0)
881 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
882 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
884 struct filedesc *fdp;
886 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
887 * infds with the new FD_SETSIZE of 1024, and more than enough for
888 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
891 fd_mask s_selbits[howmany(2048, NFDBITS)];
892 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
893 struct timeval atv, rtv, ttv;
894 int error, lf, ndu, timo;
895 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
899 fdp = td->td_proc->p_fd;
901 lf = fdp->fd_lastfile;
905 error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
908 error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
911 error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
916 * Allocate just enough bits for the non-null fd_sets. Use the
917 * preallocated auto buffer if possible.
919 nfdbits = roundup(nd, NFDBITS);
920 ncpbytes = nfdbits / NBBY;
921 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
924 nbufbytes += 2 * ncpbytes;
926 nbufbytes += 2 * ncpbytes;
928 nbufbytes += 2 * ncpbytes;
929 if (nbufbytes <= sizeof s_selbits)
930 selbits = &s_selbits[0];
932 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
935 * Assign pointers into the bit buffers and fetch the input bits.
936 * Put the output buffers together so that they can be bzeroed
940 #define getbits(name, x) \
942 if (name == NULL) { \
946 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
948 sbp += ncpbytes / sizeof *sbp; \
949 error = copyin(name, ibits[x], ncpubytes); \
952 bzero((char *)ibits[x] + ncpubytes, \
953 ncpbytes - ncpubytes); \
961 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
963 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
964 * we are running under 32-bit emulation. This should be more
967 #define swizzle_fdset(bits) \
968 if (abi_nfdbits != NFDBITS && bits != NULL) { \
970 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
971 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
974 #define swizzle_fdset(bits)
977 /* Make sure the bit order makes it through an ABI transition */
978 swizzle_fdset(ibits[0]);
979 swizzle_fdset(ibits[1]);
980 swizzle_fdset(ibits[2]);
983 bzero(selbits, nbufbytes / 2);
987 if (itimerfix(&atv)) {
991 getmicrouptime(&rtv);
992 timevaladd(&atv, &rtv);
999 /* Iterate until the timeout expires or descriptors become ready. */
1001 error = selscan(td, ibits, obits, nd);
1002 if (error || td->td_retval[0] != 0)
1004 if (atv.tv_sec || atv.tv_usec) {
1005 getmicrouptime(&rtv);
1006 if (timevalcmp(&rtv, &atv, >=))
1009 timevalsub(&ttv, &rtv);
1010 timo = ttv.tv_sec > 24 * 60 * 60 ?
1011 24 * 60 * 60 * hz : tvtohz(&ttv);
1013 error = seltdwait(td, timo);
1016 error = selrescan(td, ibits, obits);
1017 if (error || td->td_retval[0] != 0)
1023 /* select is not restarted after signals... */
1024 if (error == ERESTART)
1026 if (error == EWOULDBLOCK)
1029 /* swizzle bit order back, if necessary */
1030 swizzle_fdset(obits[0]);
1031 swizzle_fdset(obits[1]);
1032 swizzle_fdset(obits[2]);
1033 #undef swizzle_fdset
1035 #define putbits(name, x) \
1036 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1046 if (selbits != &s_selbits[0])
1047 free(selbits, M_SELECT);
1052 * Convert a select bit set to poll flags.
1054 * The backend always returns POLLHUP/POLLERR if appropriate and we
1055 * return this as a set bit in any set.
1057 static int select_flags[3] = {
1058 POLLRDNORM | POLLHUP | POLLERR,
1059 POLLWRNORM | POLLHUP | POLLERR,
1060 POLLRDBAND | POLLERR
1064 * Compute the fo_poll flags required for a fd given by the index and
1065 * bit position in the fd_mask array.
1068 selflags(fd_mask **ibits, int idx, fd_mask bit)
1074 for (msk = 0; msk < 3; msk++) {
1075 if (ibits[msk] == NULL)
1077 if ((ibits[msk][idx] & bit) == 0)
1079 flags |= select_flags[msk];
1085 * Set the appropriate output bits given a mask of fired events and the
1086 * input bits originally requested.
1089 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1095 for (msk = 0; msk < 3; msk++) {
1096 if ((events & select_flags[msk]) == 0)
1098 if (ibits[msk] == NULL)
1100 if ((ibits[msk][idx] & bit) == 0)
1103 * XXX Check for a duplicate set. This can occur because a
1104 * socket calls selrecord() twice for each poll() call
1105 * resulting in two selfds per real fd. selrescan() will
1106 * call selsetbits twice as a result.
1108 if ((obits[msk][idx] & bit) != 0)
1110 obits[msk][idx] |= bit;
1118 * Traverse the list of fds attached to this thread's seltd and check for
1122 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1124 struct filedesc *fdp;
1133 fdp = td->td_proc->p_fd;
1136 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1137 fd = (int)(uintptr_t)sfp->sf_cookie;
1139 selfdfree(stp, sfp);
1140 /* If the selinfo wasn't cleared the event didn't fire. */
1143 if ((fp = fget_unlocked(fdp, fd)) == NULL)
1146 bit = (fd_mask)1 << (fd % NFDBITS);
1147 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1150 n += selsetbits(ibits, obits, idx, bit, ev);
1153 td->td_retval[0] = n;
1158 * Perform the initial filedescriptor scan and register ourselves with
1162 selscan(td, ibits, obits, nfd)
1164 fd_mask **ibits, **obits;
1167 struct filedesc *fdp;
1170 int ev, flags, end, fd;
1173 fdp = td->td_proc->p_fd;
1175 for (idx = 0, fd = 0; fd < nfd; idx++) {
1176 end = imin(fd + NFDBITS, nfd);
1177 for (bit = 1; fd < end; bit <<= 1, fd++) {
1178 /* Compute the list of events we're interested in. */
1179 flags = selflags(ibits, idx, bit);
1182 if ((fp = fget_unlocked(fdp, fd)) == NULL)
1184 selfdalloc(td, (void *)(uintptr_t)fd);
1185 ev = fo_poll(fp, flags, td->td_ucred, td);
1188 n += selsetbits(ibits, obits, idx, bit, ev);
1192 td->td_retval[0] = n;
1196 #ifndef _SYS_SYSPROTO_H_
1206 struct poll_args *uap;
1208 struct pollfd *bits;
1209 struct pollfd smallbits[32];
1210 struct timeval atv, rtv, ttv;
1216 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1218 ni = nfds * sizeof(struct pollfd);
1219 if (ni > sizeof(smallbits))
1220 bits = malloc(ni, M_TEMP, M_WAITOK);
1223 error = copyin(uap->fds, bits, ni);
1226 if (uap->timeout != INFTIM) {
1227 atv.tv_sec = uap->timeout / 1000;
1228 atv.tv_usec = (uap->timeout % 1000) * 1000;
1229 if (itimerfix(&atv)) {
1233 getmicrouptime(&rtv);
1234 timevaladd(&atv, &rtv);
1241 /* Iterate until the timeout expires or descriptors become ready. */
1243 error = pollscan(td, bits, nfds);
1244 if (error || td->td_retval[0] != 0)
1246 if (atv.tv_sec || atv.tv_usec) {
1247 getmicrouptime(&rtv);
1248 if (timevalcmp(&rtv, &atv, >=))
1251 timevalsub(&ttv, &rtv);
1252 timo = ttv.tv_sec > 24 * 60 * 60 ?
1253 24 * 60 * 60 * hz : tvtohz(&ttv);
1255 error = seltdwait(td, timo);
1258 error = pollrescan(td);
1259 if (error || td->td_retval[0] != 0)
1265 /* poll is not restarted after signals... */
1266 if (error == ERESTART)
1268 if (error == EWOULDBLOCK)
1271 error = pollout(td, bits, uap->fds, nfds);
1276 if (ni > sizeof(smallbits))
1282 pollrescan(struct thread *td)
1288 struct filedesc *fdp;
1294 fdp = td->td_proc->p_fd;
1296 FILEDESC_SLOCK(fdp);
1297 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1298 fd = (struct pollfd *)sfp->sf_cookie;
1300 selfdfree(stp, sfp);
1301 /* If the selinfo wasn't cleared the event didn't fire. */
1304 fp = fdp->fd_ofiles[fd->fd];
1306 fd->revents = POLLNVAL;
1311 * Note: backend also returns POLLHUP and
1312 * POLLERR if appropriate.
1314 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1315 if (fd->revents != 0)
1318 FILEDESC_SUNLOCK(fdp);
1320 td->td_retval[0] = n;
1326 pollout(td, fds, ufds, nfd)
1329 struct pollfd *ufds;
1336 for (i = 0; i < nfd; i++) {
1337 error = copyout(&fds->revents, &ufds->revents,
1338 sizeof(ufds->revents));
1341 if (fds->revents != 0)
1346 td->td_retval[0] = n;
1351 pollscan(td, fds, nfd)
1356 struct filedesc *fdp = td->td_proc->p_fd;
1361 FILEDESC_SLOCK(fdp);
1362 for (i = 0; i < nfd; i++, fds++) {
1363 if (fds->fd >= fdp->fd_nfiles) {
1364 fds->revents = POLLNVAL;
1366 } else if (fds->fd < 0) {
1369 fp = fdp->fd_ofiles[fds->fd];
1371 fds->revents = POLLNVAL;
1375 * Note: backend also returns POLLHUP and
1376 * POLLERR if appropriate.
1378 selfdalloc(td, fds);
1379 fds->revents = fo_poll(fp, fds->events,
1382 * POSIX requires POLLOUT to be never
1383 * set simultaneously with POLLHUP.
1385 if ((fds->revents & POLLHUP) != 0)
1386 fds->revents &= ~POLLOUT;
1388 if (fds->revents != 0)
1393 FILEDESC_SUNLOCK(fdp);
1394 td->td_retval[0] = n;
1399 * OpenBSD poll system call.
1401 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1403 #ifndef _SYS_SYSPROTO_H_
1404 struct openbsd_poll_args {
1411 openbsd_poll(td, uap)
1412 register struct thread *td;
1413 register struct openbsd_poll_args *uap;
1415 return (poll(td, (struct poll_args *)uap));
1419 * XXX This was created specifically to support netncp and netsmb. This
1420 * allows the caller to specify a socket to wait for events on. It returns
1421 * 0 if any events matched and an error otherwise. There is no way to
1422 * determine which events fired.
1425 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1427 struct timeval atv, rtv, ttv;
1432 if (itimerfix(&atv))
1434 getmicrouptime(&rtv);
1435 timevaladd(&atv, &rtv);
1444 * Iterate until the timeout expires or the socket becomes ready.
1447 selfdalloc(td, NULL);
1448 error = sopoll(so, events, NULL, td);
1449 /* error here is actually the ready events. */
1452 if (atv.tv_sec || atv.tv_usec) {
1453 getmicrouptime(&rtv);
1454 if (timevalcmp(&rtv, &atv, >=)) {
1456 return (EWOULDBLOCK);
1459 timevalsub(&ttv, &rtv);
1460 timo = ttv.tv_sec > 24 * 60 * 60 ?
1461 24 * 60 * 60 * hz : tvtohz(&ttv);
1463 error = seltdwait(td, timo);
1468 /* XXX Duplicates ncp/smb behavior. */
1469 if (error == ERESTART)
1475 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1476 * have two select sets, one for read and another for write.
1479 selfdalloc(struct thread *td, void *cookie)
1484 if (stp->st_free1 == NULL)
1485 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1486 stp->st_free1->sf_td = stp;
1487 stp->st_free1->sf_cookie = cookie;
1488 if (stp->st_free2 == NULL)
1489 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1490 stp->st_free2->sf_td = stp;
1491 stp->st_free2->sf_cookie = cookie;
1495 selfdfree(struct seltd *stp, struct selfd *sfp)
1497 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1498 mtx_lock(sfp->sf_mtx);
1500 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1501 mtx_unlock(sfp->sf_mtx);
1502 uma_zfree(selfd_zone, sfp);
1505 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1508 struct selinfo *sip;
1512 * This feature is already provided by doselwakeup(), thus it is
1513 * enough to go for it.
1514 * Eventually, the context, should take care to avoid races
1515 * between thread calling select()/poll() and file descriptor
1516 * detaching, but, again, the races are just the same as
1519 doselwakeup(sip, -1);
1523 * Record a select request.
1526 selrecord(selector, sip)
1527 struct thread *selector;
1528 struct selinfo *sip;
1534 stp = selector->td_sel;
1536 * Don't record when doing a rescan.
1538 if (stp->st_flags & SELTD_RESCAN)
1541 * Grab one of the preallocated descriptors.
1544 if ((sfp = stp->st_free1) != NULL)
1545 stp->st_free1 = NULL;
1546 else if ((sfp = stp->st_free2) != NULL)
1547 stp->st_free2 = NULL;
1549 panic("selrecord: No free selfd on selq");
1552 mtxp = mtx_pool_find(mtxpool_select, sip);
1554 * Initialize the sfp and queue it in the thread.
1558 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1560 * Now that we've locked the sip, check for initialization.
1563 if (sip->si_mtx == NULL) {
1565 TAILQ_INIT(&sip->si_tdlist);
1568 * Add this thread to the list of selfds listening on this selinfo.
1570 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1571 mtx_unlock(sip->si_mtx);
1574 /* Wake up a selecting thread. */
1577 struct selinfo *sip;
1579 doselwakeup(sip, -1);
1582 /* Wake up a selecting thread, and set its priority. */
1584 selwakeuppri(sip, pri)
1585 struct selinfo *sip;
1588 doselwakeup(sip, pri);
1592 * Do a wakeup when a selectable event occurs.
1595 doselwakeup(sip, pri)
1596 struct selinfo *sip;
1603 /* If it's not initialized there can't be any waiters. */
1604 if (sip->si_mtx == NULL)
1607 * Locking the selinfo locks all selfds associated with it.
1609 mtx_lock(sip->si_mtx);
1610 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1612 * Once we remove this sfp from the list and clear the
1613 * sf_si seltdclear will know to ignore this si.
1615 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1618 mtx_lock(&stp->st_mtx);
1619 stp->st_flags |= SELTD_PENDING;
1620 cv_broadcastpri(&stp->st_wait, pri);
1621 mtx_unlock(&stp->st_mtx);
1623 mtx_unlock(sip->si_mtx);
1627 seltdinit(struct thread *td)
1631 if ((stp = td->td_sel) != NULL)
1633 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1634 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1635 cv_init(&stp->st_wait, "select");
1638 STAILQ_INIT(&stp->st_selq);
1642 seltdwait(struct thread *td, int timo)
1649 * An event of interest may occur while we do not hold the seltd
1650 * locked so check the pending flag before we sleep.
1652 mtx_lock(&stp->st_mtx);
1654 * Any further calls to selrecord will be a rescan.
1656 stp->st_flags |= SELTD_RESCAN;
1657 if (stp->st_flags & SELTD_PENDING) {
1658 mtx_unlock(&stp->st_mtx);
1662 error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1664 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1665 mtx_unlock(&stp->st_mtx);
1671 seltdfini(struct thread *td)
1679 uma_zfree(selfd_zone, stp->st_free1);
1681 uma_zfree(selfd_zone, stp->st_free2);
1683 free(stp, M_SELECT);
1687 * Remove the references to the thread from all of the objects we were
1691 seltdclear(struct thread *td)
1698 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1699 selfdfree(stp, sfp);
1703 static void selectinit(void *);
1704 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1706 selectinit(void *dummy __unused)
1709 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1710 NULL, NULL, UMA_ALIGN_PTR, 0);
1711 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);