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 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
78 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
79 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
81 static int pollout(struct thread *, struct pollfd *, struct pollfd *,
83 static int pollscan(struct thread *, struct pollfd *, u_int);
84 static int pollrescan(struct thread *);
85 static int selscan(struct thread *, fd_mask **, fd_mask **, int);
86 static int selrescan(struct thread *, fd_mask **, fd_mask **);
87 static void selfdalloc(struct thread *, void *);
88 static void selfdfree(struct seltd *, struct selfd *);
89 static int dofileread(struct thread *, int, struct file *, struct uio *,
91 static int dofilewrite(struct thread *, int, struct file *, struct uio *,
93 static void doselwakeup(struct selinfo *, int);
94 static void seltdinit(struct thread *);
95 static int seltdwait(struct thread *, int);
96 static void seltdclear(struct thread *);
99 * One seltd per-thread allocated on demand as needed.
101 * t - protected by st_mtx
102 * k - Only accessed by curthread or read-only
105 STAILQ_HEAD(, selfd) st_selq; /* (k) List of selfds. */
106 struct selfd *st_free1; /* (k) free fd for read set. */
107 struct selfd *st_free2; /* (k) free fd for write set. */
108 struct mtx st_mtx; /* Protects struct seltd */
109 struct cv st_wait; /* (t) Wait channel. */
110 int st_flags; /* (t) SELTD_ flags. */
113 #define SELTD_PENDING 0x0001 /* We have pending events. */
114 #define SELTD_RESCAN 0x0002 /* Doing a rescan. */
117 * One selfd allocated per-thread per-file-descriptor.
118 * f - protected by sf_mtx
121 STAILQ_ENTRY(selfd) sf_link; /* (k) fds owned by this td. */
122 TAILQ_ENTRY(selfd) sf_threads; /* (f) fds on this selinfo. */
123 struct selinfo *sf_si; /* (f) selinfo when linked. */
124 struct mtx *sf_mtx; /* Pointer to selinfo mtx. */
125 struct seltd *sf_td; /* (k) owning seltd. */
126 void *sf_cookie; /* (k) fd or pollfd. */
129 static uma_zone_t selfd_zone;
130 static struct mtx_pool *mtxpool_select;
132 #ifndef _SYS_SYSPROTO_H_
142 struct read_args *uap;
148 if (uap->nbyte > INT_MAX)
150 aiov.iov_base = uap->buf;
151 aiov.iov_len = uap->nbyte;
152 auio.uio_iov = &aiov;
154 auio.uio_resid = uap->nbyte;
155 auio.uio_segflg = UIO_USERSPACE;
156 error = kern_readv(td, uap->fd, &auio);
161 * Positioned read system call
163 #ifndef _SYS_SYSPROTO_H_
175 struct pread_args *uap;
181 if (uap->nbyte > INT_MAX)
183 aiov.iov_base = uap->buf;
184 aiov.iov_len = uap->nbyte;
185 auio.uio_iov = &aiov;
187 auio.uio_resid = uap->nbyte;
188 auio.uio_segflg = UIO_USERSPACE;
189 error = kern_preadv(td, uap->fd, &auio, uap->offset);
194 freebsd6_pread(td, uap)
196 struct freebsd6_pread_args *uap;
198 struct pread_args oargs;
201 oargs.buf = uap->buf;
202 oargs.nbyte = uap->nbyte;
203 oargs.offset = uap->offset;
204 return (sys_pread(td, &oargs));
208 * Scatter read system call.
210 #ifndef _SYS_SYSPROTO_H_
218 sys_readv(struct thread *td, struct readv_args *uap)
223 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
226 error = kern_readv(td, uap->fd, auio);
232 kern_readv(struct thread *td, int fd, struct uio *auio)
237 error = fget_read(td, fd, CAP_READ | CAP_SEEK, &fp);
240 error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
246 * Scatter positioned read system call.
248 #ifndef _SYS_SYSPROTO_H_
257 sys_preadv(struct thread *td, struct preadv_args *uap)
262 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
265 error = kern_preadv(td, uap->fd, auio, uap->offset);
271 kern_preadv(td, fd, auio, offset)
280 error = fget_read(td, fd, CAP_READ, &fp);
283 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
285 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
288 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
294 * Common code for readv and preadv that reads data in
295 * from a file using the passed in uio, offset, and flags.
298 dofileread(td, fd, fp, auio, offset, flags)
309 struct uio *ktruio = NULL;
312 /* Finish zero length reads right here */
313 if (auio->uio_resid == 0) {
314 td->td_retval[0] = 0;
317 auio->uio_rw = UIO_READ;
318 auio->uio_offset = offset;
321 if (KTRPOINT(td, KTR_GENIO))
322 ktruio = cloneuio(auio);
324 cnt = auio->uio_resid;
325 if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
326 if (auio->uio_resid != cnt && (error == ERESTART ||
327 error == EINTR || error == EWOULDBLOCK))
330 cnt -= auio->uio_resid;
332 if (ktruio != NULL) {
333 ktruio->uio_resid = cnt;
334 ktrgenio(fd, UIO_READ, ktruio, error);
337 td->td_retval[0] = cnt;
341 #ifndef _SYS_SYSPROTO_H_
351 struct write_args *uap;
357 if (uap->nbyte > INT_MAX)
359 aiov.iov_base = (void *)(uintptr_t)uap->buf;
360 aiov.iov_len = uap->nbyte;
361 auio.uio_iov = &aiov;
363 auio.uio_resid = uap->nbyte;
364 auio.uio_segflg = UIO_USERSPACE;
365 error = kern_writev(td, uap->fd, &auio);
370 * Positioned write system call.
372 #ifndef _SYS_SYSPROTO_H_
384 struct pwrite_args *uap;
390 if (uap->nbyte > INT_MAX)
392 aiov.iov_base = (void *)(uintptr_t)uap->buf;
393 aiov.iov_len = uap->nbyte;
394 auio.uio_iov = &aiov;
396 auio.uio_resid = uap->nbyte;
397 auio.uio_segflg = UIO_USERSPACE;
398 error = kern_pwritev(td, uap->fd, &auio, uap->offset);
403 freebsd6_pwrite(td, uap)
405 struct freebsd6_pwrite_args *uap;
407 struct pwrite_args oargs;
410 oargs.buf = uap->buf;
411 oargs.nbyte = uap->nbyte;
412 oargs.offset = uap->offset;
413 return (sys_pwrite(td, &oargs));
417 * Gather write system call.
419 #ifndef _SYS_SYSPROTO_H_
427 sys_writev(struct thread *td, struct writev_args *uap)
432 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
435 error = kern_writev(td, uap->fd, auio);
441 kern_writev(struct thread *td, int fd, struct uio *auio)
446 error = fget_write(td, fd, CAP_WRITE | CAP_SEEK, &fp);
449 error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
455 * Gather positioned write system call.
457 #ifndef _SYS_SYSPROTO_H_
458 struct pwritev_args {
466 sys_pwritev(struct thread *td, struct pwritev_args *uap)
471 error = copyinuio(uap->iovp, uap->iovcnt, &auio);
474 error = kern_pwritev(td, uap->fd, auio, uap->offset);
480 kern_pwritev(td, fd, auio, offset)
489 error = fget_write(td, fd, CAP_WRITE, &fp);
492 if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
494 else if (offset < 0 && fp->f_vnode->v_type != VCHR)
497 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
503 * Common code for writev and pwritev that writes data to
504 * a file using the passed in uio, offset, and flags.
507 dofilewrite(td, fd, fp, auio, offset, flags)
518 struct uio *ktruio = NULL;
521 auio->uio_rw = UIO_WRITE;
523 auio->uio_offset = offset;
525 if (KTRPOINT(td, KTR_GENIO))
526 ktruio = cloneuio(auio);
528 cnt = auio->uio_resid;
529 if (fp->f_type == DTYPE_VNODE)
531 if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
532 if (auio->uio_resid != cnt && (error == ERESTART ||
533 error == EINTR || error == EWOULDBLOCK))
535 /* Socket layer is responsible for issuing SIGPIPE. */
536 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
537 PROC_LOCK(td->td_proc);
538 tdsignal(td, SIGPIPE);
539 PROC_UNLOCK(td->td_proc);
542 cnt -= auio->uio_resid;
544 if (ktruio != NULL) {
545 ktruio->uio_resid = cnt;
546 ktrgenio(fd, UIO_WRITE, ktruio, error);
549 td->td_retval[0] = cnt;
554 * Truncate a file given a file descriptor.
556 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
557 * descriptor isn't writable.
560 kern_ftruncate(td, fd, length)
571 error = fget(td, fd, CAP_FTRUNCATE, &fp);
574 AUDIT_ARG_FILE(td->td_proc, fp);
575 if (!(fp->f_flag & FWRITE)) {
579 error = fo_truncate(fp, length, td->td_ucred, td);
584 #ifndef _SYS_SYSPROTO_H_
585 struct ftruncate_args {
592 sys_ftruncate(td, uap)
594 struct ftruncate_args *uap;
597 return (kern_ftruncate(td, uap->fd, uap->length));
600 #if defined(COMPAT_43)
601 #ifndef _SYS_SYSPROTO_H_
602 struct oftruncate_args {
610 struct oftruncate_args *uap;
613 return (kern_ftruncate(td, uap->fd, uap->length));
615 #endif /* COMPAT_43 */
617 #ifndef _SYS_SYSPROTO_H_
626 sys_ioctl(struct thread *td, struct ioctl_args *uap)
633 if (uap->com > 0xffffffff) {
635 "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
636 td->td_proc->p_pid, td->td_name, uap->com);
637 uap->com &= 0xffffffff;
642 * Interpret high order word to find amount of data to be
643 * copied to/from the user's address space.
645 size = IOCPARM_LEN(com);
646 if ((size > IOCPARM_MAX) ||
647 ((com & (IOC_VOID | IOC_IN | IOC_OUT)) == 0) ||
648 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
649 ((com & IOC_OUT) && size == 0) ||
651 ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
653 ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
657 if (com & IOC_VOID) {
658 /* Integer argument. */
659 arg = (intptr_t)uap->data;
663 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
665 data = (void *)&uap->data;
667 error = copyin(uap->data, data, (u_int)size);
670 free(data, M_IOCTLOPS);
673 } else if (com & IOC_OUT) {
675 * Zero the buffer so the user always
676 * gets back something deterministic.
681 error = kern_ioctl(td, uap->fd, com, data);
683 if (error == 0 && (com & IOC_OUT))
684 error = copyout(data, uap->data, (u_int)size);
687 free(data, M_IOCTLOPS);
692 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
695 struct filedesc *fdp;
701 if ((error = fget(td, fd, CAP_IOCTL, &fp)) != 0)
703 if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
707 fdp = td->td_proc->p_fd;
711 fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
712 FILEDESC_XUNLOCK(fdp);
716 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
717 FILEDESC_XUNLOCK(fdp);
720 if ((tmp = *(int *)data))
721 atomic_set_int(&fp->f_flag, FNONBLOCK);
723 atomic_clear_int(&fp->f_flag, FNONBLOCK);
727 if ((tmp = *(int *)data))
728 atomic_set_int(&fp->f_flag, FASYNC);
730 atomic_clear_int(&fp->f_flag, FASYNC);
735 error = fo_ioctl(fp, com, data, td->td_ucred, td);
742 poll_no_poll(int events)
745 * Return true for read/write. If the user asked for something
746 * special, return POLLNVAL, so that clients have a way of
747 * determining reliably whether or not the extended
748 * functionality is present without hard-coding knowledge
749 * of specific filesystem implementations.
751 if (events & ~POLLSTANDARD)
754 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
758 sys_pselect(struct thread *td, struct pselect_args *uap)
761 struct timeval tv, *tvp;
765 if (uap->ts != NULL) {
766 error = copyin(uap->ts, &ts, sizeof(ts));
769 TIMESPEC_TO_TIMEVAL(&tv, &ts);
773 if (uap->sm != NULL) {
774 error = copyin(uap->sm, &set, sizeof(set));
780 return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
785 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
786 struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
791 error = kern_sigprocmask(td, SIG_SETMASK, uset,
792 &td->td_oldsigmask, 0);
795 td->td_pflags |= TDP_OLDMASK;
797 * Make sure that ast() is called on return to
798 * usermode and TDP_OLDMASK is cleared, restoring old
802 td->td_flags |= TDF_ASTPENDING;
805 error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
809 #ifndef _SYS_SYSPROTO_H_
812 fd_set *in, *ou, *ex;
817 sys_select(struct thread *td, struct select_args *uap)
819 struct timeval tv, *tvp;
822 if (uap->tv != NULL) {
823 error = copyin(uap->tv, &tv, sizeof(tv));
830 return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
835 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
836 fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
838 struct filedesc *fdp;
840 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
841 * infds with the new FD_SETSIZE of 1024, and more than enough for
842 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
845 fd_mask s_selbits[howmany(2048, NFDBITS)];
846 fd_mask *ibits[3], *obits[3], *selbits, *sbp;
847 struct timeval atv, rtv, ttv;
849 u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
853 fdp = td->td_proc->p_fd;
854 if (nd > fdp->fd_lastfile + 1)
855 nd = fdp->fd_lastfile + 1;
858 * Allocate just enough bits for the non-null fd_sets. Use the
859 * preallocated auto buffer if possible.
861 nfdbits = roundup(nd, NFDBITS);
862 ncpbytes = nfdbits / NBBY;
863 ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
866 nbufbytes += 2 * ncpbytes;
868 nbufbytes += 2 * ncpbytes;
870 nbufbytes += 2 * ncpbytes;
871 if (nbufbytes <= sizeof s_selbits)
872 selbits = &s_selbits[0];
874 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
877 * Assign pointers into the bit buffers and fetch the input bits.
878 * Put the output buffers together so that they can be bzeroed
882 #define getbits(name, x) \
884 if (name == NULL) { \
888 ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp; \
890 sbp += ncpbytes / sizeof *sbp; \
891 error = copyin(name, ibits[x], ncpubytes); \
894 bzero((char *)ibits[x] + ncpubytes, \
895 ncpbytes - ncpubytes); \
903 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
905 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
906 * we are running under 32-bit emulation. This should be more
909 #define swizzle_fdset(bits) \
910 if (abi_nfdbits != NFDBITS && bits != NULL) { \
912 for (i = 0; i < ncpbytes / sizeof *sbp; i++) \
913 bits[i] = (bits[i] >> 32) | (bits[i] << 32); \
916 #define swizzle_fdset(bits)
919 /* Make sure the bit order makes it through an ABI transition */
920 swizzle_fdset(ibits[0]);
921 swizzle_fdset(ibits[1]);
922 swizzle_fdset(ibits[2]);
925 bzero(selbits, nbufbytes / 2);
929 if (itimerfix(&atv)) {
933 getmicrouptime(&rtv);
934 timevaladd(&atv, &rtv);
941 /* Iterate until the timeout expires or descriptors become ready. */
943 error = selscan(td, ibits, obits, nd);
944 if (error || td->td_retval[0] != 0)
946 if (atv.tv_sec || atv.tv_usec) {
947 getmicrouptime(&rtv);
948 if (timevalcmp(&rtv, &atv, >=))
951 timevalsub(&ttv, &rtv);
952 timo = ttv.tv_sec > 24 * 60 * 60 ?
953 24 * 60 * 60 * hz : tvtohz(&ttv);
955 error = seltdwait(td, timo);
958 error = selrescan(td, ibits, obits);
959 if (error || td->td_retval[0] != 0)
965 /* select is not restarted after signals... */
966 if (error == ERESTART)
968 if (error == EWOULDBLOCK)
971 /* swizzle bit order back, if necessary */
972 swizzle_fdset(obits[0]);
973 swizzle_fdset(obits[1]);
974 swizzle_fdset(obits[2]);
977 #define putbits(name, x) \
978 if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
988 if (selbits != &s_selbits[0])
989 free(selbits, M_SELECT);
994 * Convert a select bit set to poll flags.
996 * The backend always returns POLLHUP/POLLERR if appropriate and we
997 * return this as a set bit in any set.
999 static int select_flags[3] = {
1000 POLLRDNORM | POLLHUP | POLLERR,
1001 POLLWRNORM | POLLHUP | POLLERR,
1002 POLLRDBAND | POLLERR
1006 * Compute the fo_poll flags required for a fd given by the index and
1007 * bit position in the fd_mask array.
1010 selflags(fd_mask **ibits, int idx, fd_mask bit)
1016 for (msk = 0; msk < 3; msk++) {
1017 if (ibits[msk] == NULL)
1019 if ((ibits[msk][idx] & bit) == 0)
1021 flags |= select_flags[msk];
1027 * Set the appropriate output bits given a mask of fired events and the
1028 * input bits originally requested.
1031 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1037 for (msk = 0; msk < 3; msk++) {
1038 if ((events & select_flags[msk]) == 0)
1040 if (ibits[msk] == NULL)
1042 if ((ibits[msk][idx] & bit) == 0)
1045 * XXX Check for a duplicate set. This can occur because a
1046 * socket calls selrecord() twice for each poll() call
1047 * resulting in two selfds per real fd. selrescan() will
1048 * call selsetbits twice as a result.
1050 if ((obits[msk][idx] & bit) != 0)
1052 obits[msk][idx] |= bit;
1060 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1064 struct file *fp_fromcap;
1068 if ((fp = fget_unlocked(fdp, fd)) == NULL)
1072 * If the file descriptor is for a capability, test rights and use
1073 * the file descriptor references by the capability.
1075 error = cap_funwrap(fp, CAP_POLL_EVENT, &fp_fromcap);
1077 fdrop(fp, curthread);
1080 if (fp != fp_fromcap) {
1082 fdrop(fp, curthread);
1085 #endif /* CAPABILITIES */
1091 * Traverse the list of fds attached to this thread's seltd and check for
1095 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1097 struct filedesc *fdp;
1107 fdp = td->td_proc->p_fd;
1110 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1111 fd = (int)(uintptr_t)sfp->sf_cookie;
1113 selfdfree(stp, sfp);
1114 /* If the selinfo wasn't cleared the event didn't fire. */
1117 error = getselfd_cap(fdp, fd, &fp);
1121 bit = (fd_mask)1 << (fd % NFDBITS);
1122 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1125 n += selsetbits(ibits, obits, idx, bit, ev);
1128 td->td_retval[0] = n;
1133 * Perform the initial filedescriptor scan and register ourselves with
1137 selscan(td, ibits, obits, nfd)
1139 fd_mask **ibits, **obits;
1142 struct filedesc *fdp;
1145 int ev, flags, end, fd;
1149 fdp = td->td_proc->p_fd;
1151 for (idx = 0, fd = 0; fd < nfd; idx++) {
1152 end = imin(fd + NFDBITS, nfd);
1153 for (bit = 1; fd < end; bit <<= 1, fd++) {
1154 /* Compute the list of events we're interested in. */
1155 flags = selflags(ibits, idx, bit);
1158 error = getselfd_cap(fdp, fd, &fp);
1161 selfdalloc(td, (void *)(uintptr_t)fd);
1162 ev = fo_poll(fp, flags, td->td_ucred, td);
1165 n += selsetbits(ibits, obits, idx, bit, ev);
1169 td->td_retval[0] = n;
1173 #ifndef _SYS_SYSPROTO_H_
1183 struct poll_args *uap;
1185 struct pollfd *bits;
1186 struct pollfd smallbits[32];
1187 struct timeval atv, rtv, ttv;
1188 int error = 0, timo;
1193 if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1195 ni = nfds * sizeof(struct pollfd);
1196 if (ni > sizeof(smallbits))
1197 bits = malloc(ni, M_TEMP, M_WAITOK);
1200 error = copyin(uap->fds, bits, ni);
1203 if (uap->timeout != INFTIM) {
1204 atv.tv_sec = uap->timeout / 1000;
1205 atv.tv_usec = (uap->timeout % 1000) * 1000;
1206 if (itimerfix(&atv)) {
1210 getmicrouptime(&rtv);
1211 timevaladd(&atv, &rtv);
1218 /* Iterate until the timeout expires or descriptors become ready. */
1220 error = pollscan(td, bits, nfds);
1221 if (error || td->td_retval[0] != 0)
1223 if (atv.tv_sec || atv.tv_usec) {
1224 getmicrouptime(&rtv);
1225 if (timevalcmp(&rtv, &atv, >=))
1228 timevalsub(&ttv, &rtv);
1229 timo = ttv.tv_sec > 24 * 60 * 60 ?
1230 24 * 60 * 60 * hz : tvtohz(&ttv);
1232 error = seltdwait(td, timo);
1235 error = pollrescan(td);
1236 if (error || td->td_retval[0] != 0)
1242 /* poll is not restarted after signals... */
1243 if (error == ERESTART)
1245 if (error == EWOULDBLOCK)
1248 error = pollout(td, bits, uap->fds, nfds);
1253 if (ni > sizeof(smallbits))
1259 pollrescan(struct thread *td)
1265 struct filedesc *fdp;
1271 fdp = td->td_proc->p_fd;
1273 FILEDESC_SLOCK(fdp);
1274 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1275 fd = (struct pollfd *)sfp->sf_cookie;
1277 selfdfree(stp, sfp);
1278 /* If the selinfo wasn't cleared the event didn't fire. */
1281 fp = fdp->fd_ofiles[fd->fd];
1284 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1288 fd->revents = POLLNVAL;
1294 * Note: backend also returns POLLHUP and
1295 * POLLERR if appropriate.
1297 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1298 if (fd->revents != 0)
1301 FILEDESC_SUNLOCK(fdp);
1303 td->td_retval[0] = n;
1309 pollout(td, fds, ufds, nfd)
1312 struct pollfd *ufds;
1319 for (i = 0; i < nfd; i++) {
1320 error = copyout(&fds->revents, &ufds->revents,
1321 sizeof(ufds->revents));
1324 if (fds->revents != 0)
1329 td->td_retval[0] = n;
1334 pollscan(td, fds, nfd)
1339 struct filedesc *fdp = td->td_proc->p_fd;
1344 FILEDESC_SLOCK(fdp);
1345 for (i = 0; i < nfd; i++, fds++) {
1346 if (fds->fd >= fdp->fd_nfiles) {
1347 fds->revents = POLLNVAL;
1349 } else if (fds->fd < 0) {
1352 fp = fdp->fd_ofiles[fds->fd];
1355 || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1359 fds->revents = POLLNVAL;
1363 * Note: backend also returns POLLHUP and
1364 * POLLERR if appropriate.
1366 selfdalloc(td, fds);
1367 fds->revents = fo_poll(fp, fds->events,
1370 * POSIX requires POLLOUT to be never
1371 * set simultaneously with POLLHUP.
1373 if ((fds->revents & POLLHUP) != 0)
1374 fds->revents &= ~POLLOUT;
1376 if (fds->revents != 0)
1381 FILEDESC_SUNLOCK(fdp);
1382 td->td_retval[0] = n;
1387 * OpenBSD poll system call.
1389 * XXX this isn't quite a true representation.. OpenBSD uses select ops.
1391 #ifndef _SYS_SYSPROTO_H_
1392 struct openbsd_poll_args {
1399 sys_openbsd_poll(td, uap)
1400 register struct thread *td;
1401 register struct openbsd_poll_args *uap;
1403 return (sys_poll(td, (struct poll_args *)uap));
1407 * XXX This was created specifically to support netncp and netsmb. This
1408 * allows the caller to specify a socket to wait for events on. It returns
1409 * 0 if any events matched and an error otherwise. There is no way to
1410 * determine which events fired.
1413 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1415 struct timeval atv, rtv, ttv;
1420 if (itimerfix(&atv))
1422 getmicrouptime(&rtv);
1423 timevaladd(&atv, &rtv);
1432 * Iterate until the timeout expires or the socket becomes ready.
1435 selfdalloc(td, NULL);
1436 error = sopoll(so, events, NULL, td);
1437 /* error here is actually the ready events. */
1440 if (atv.tv_sec || atv.tv_usec) {
1441 getmicrouptime(&rtv);
1442 if (timevalcmp(&rtv, &atv, >=)) {
1444 return (EWOULDBLOCK);
1447 timevalsub(&ttv, &rtv);
1448 timo = ttv.tv_sec > 24 * 60 * 60 ?
1449 24 * 60 * 60 * hz : tvtohz(&ttv);
1451 error = seltdwait(td, timo);
1456 /* XXX Duplicates ncp/smb behavior. */
1457 if (error == ERESTART)
1463 * Preallocate two selfds associated with 'cookie'. Some fo_poll routines
1464 * have two select sets, one for read and another for write.
1467 selfdalloc(struct thread *td, void *cookie)
1472 if (stp->st_free1 == NULL)
1473 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1474 stp->st_free1->sf_td = stp;
1475 stp->st_free1->sf_cookie = cookie;
1476 if (stp->st_free2 == NULL)
1477 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1478 stp->st_free2->sf_td = stp;
1479 stp->st_free2->sf_cookie = cookie;
1483 selfdfree(struct seltd *stp, struct selfd *sfp)
1485 STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1486 mtx_lock(sfp->sf_mtx);
1488 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1489 mtx_unlock(sfp->sf_mtx);
1490 uma_zfree(selfd_zone, sfp);
1493 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1496 struct selinfo *sip;
1500 * This feature is already provided by doselwakeup(), thus it is
1501 * enough to go for it.
1502 * Eventually, the context, should take care to avoid races
1503 * between thread calling select()/poll() and file descriptor
1504 * detaching, but, again, the races are just the same as
1507 doselwakeup(sip, -1);
1511 * Record a select request.
1514 selrecord(selector, sip)
1515 struct thread *selector;
1516 struct selinfo *sip;
1522 stp = selector->td_sel;
1524 * Don't record when doing a rescan.
1526 if (stp->st_flags & SELTD_RESCAN)
1529 * Grab one of the preallocated descriptors.
1532 if ((sfp = stp->st_free1) != NULL)
1533 stp->st_free1 = NULL;
1534 else if ((sfp = stp->st_free2) != NULL)
1535 stp->st_free2 = NULL;
1537 panic("selrecord: No free selfd on selq");
1540 mtxp = mtx_pool_find(mtxpool_select, sip);
1542 * Initialize the sfp and queue it in the thread.
1546 STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1548 * Now that we've locked the sip, check for initialization.
1551 if (sip->si_mtx == NULL) {
1553 TAILQ_INIT(&sip->si_tdlist);
1556 * Add this thread to the list of selfds listening on this selinfo.
1558 TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1559 mtx_unlock(sip->si_mtx);
1562 /* Wake up a selecting thread. */
1565 struct selinfo *sip;
1567 doselwakeup(sip, -1);
1570 /* Wake up a selecting thread, and set its priority. */
1572 selwakeuppri(sip, pri)
1573 struct selinfo *sip;
1576 doselwakeup(sip, pri);
1580 * Do a wakeup when a selectable event occurs.
1583 doselwakeup(sip, pri)
1584 struct selinfo *sip;
1591 /* If it's not initialized there can't be any waiters. */
1592 if (sip->si_mtx == NULL)
1595 * Locking the selinfo locks all selfds associated with it.
1597 mtx_lock(sip->si_mtx);
1598 TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1600 * Once we remove this sfp from the list and clear the
1601 * sf_si seltdclear will know to ignore this si.
1603 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1606 mtx_lock(&stp->st_mtx);
1607 stp->st_flags |= SELTD_PENDING;
1608 cv_broadcastpri(&stp->st_wait, pri);
1609 mtx_unlock(&stp->st_mtx);
1611 mtx_unlock(sip->si_mtx);
1615 seltdinit(struct thread *td)
1619 if ((stp = td->td_sel) != NULL)
1621 td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1622 mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1623 cv_init(&stp->st_wait, "select");
1626 STAILQ_INIT(&stp->st_selq);
1630 seltdwait(struct thread *td, int timo)
1637 * An event of interest may occur while we do not hold the seltd
1638 * locked so check the pending flag before we sleep.
1640 mtx_lock(&stp->st_mtx);
1642 * Any further calls to selrecord will be a rescan.
1644 stp->st_flags |= SELTD_RESCAN;
1645 if (stp->st_flags & SELTD_PENDING) {
1646 mtx_unlock(&stp->st_mtx);
1650 error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1652 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1653 mtx_unlock(&stp->st_mtx);
1659 seltdfini(struct thread *td)
1667 uma_zfree(selfd_zone, stp->st_free1);
1669 uma_zfree(selfd_zone, stp->st_free2);
1671 free(stp, M_SELECT);
1675 * Remove the references to the thread from all of the objects we were
1679 seltdclear(struct thread *td)
1686 STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1687 selfdfree(stp, sfp);
1691 static void selectinit(void *);
1692 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1694 selectinit(void *dummy __unused)
1697 selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1698 NULL, NULL, UMA_ALIGN_PTR, 0);
1699 mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);