Home | History | Annotate | Line # | Download | only in kern
sys_select.c revision 1.46.2.2
      1 /*	$NetBSD: sys_select.c,v 1.46.2.2 2024/11/20 14:09:10 martin Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2007, 2008, 2009, 2010 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran and Mindaugas Rasiukevicius.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     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  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1982, 1986, 1989, 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  * (c) UNIX System Laboratories, Inc.
     36  * All or some portions of this file are derived from material licensed
     37  * to the University of California by American Telephone and Telegraph
     38  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     39  * the permission of UNIX System Laboratories, Inc.
     40  *
     41  * Redistribution and use in source and binary forms, with or without
     42  * modification, are permitted provided that the following conditions
     43  * are met:
     44  * 1. Redistributions of source code must retain the above copyright
     45  *    notice, this list of conditions and the following disclaimer.
     46  * 2. Redistributions in binary form must reproduce the above copyright
     47  *    notice, this list of conditions and the following disclaimer in the
     48  *    documentation and/or other materials provided with the distribution.
     49  * 3. Neither the name of the University nor the names of its contributors
     50  *    may be used to endorse or promote products derived from this software
     51  *    without specific prior written permission.
     52  *
     53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     63  * SUCH DAMAGE.
     64  *
     65  *	@(#)sys_generic.c	8.9 (Berkeley) 2/14/95
     66  */
     67 
     68 /*
     69  * System calls of synchronous I/O multiplexing subsystem.
     70  *
     71  * Locking
     72  *
     73  * Two locks are used: <object-lock> and selcluster_t::sc_lock.
     74  *
     75  * The <object-lock> might be a device driver or another subsystem, e.g.
     76  * socket or pipe.  This lock is not exported, and thus invisible to this
     77  * subsystem.  Mainly, synchronisation between selrecord() and selnotify()
     78  * routines depends on this lock, as it will be described in the comments.
     79  *
     80  * Lock order
     81  *
     82  *	<object-lock> ->
     83  *		selcluster_t::sc_lock
     84  */
     85 
     86 #include <sys/cdefs.h>
     87 __KERNEL_RCSID(0, "$NetBSD: sys_select.c,v 1.46.2.2 2024/11/20 14:09:10 martin Exp $");
     88 
     89 #include <sys/param.h>
     90 #include <sys/systm.h>
     91 #include <sys/filedesc.h>
     92 #include <sys/file.h>
     93 #include <sys/proc.h>
     94 #include <sys/socketvar.h>
     95 #include <sys/signalvar.h>
     96 #include <sys/uio.h>
     97 #include <sys/kernel.h>
     98 #include <sys/lwp.h>
     99 #include <sys/poll.h>
    100 #include <sys/mount.h>
    101 #include <sys/syscallargs.h>
    102 #include <sys/cpu.h>
    103 #include <sys/atomic.h>
    104 #include <sys/socketvar.h>
    105 #include <sys/sleepq.h>
    106 #include <sys/sysctl.h>
    107 
    108 /* Flags for lwp::l_selflag. */
    109 #define	SEL_RESET	0	/* awoken, interrupted, or not yet polling */
    110 #define	SEL_SCANNING	1	/* polling descriptors */
    111 #define	SEL_BLOCKING	2	/* blocking and waiting for event */
    112 #define	SEL_EVENT	3	/* interrupted, events set directly */
    113 
    114 /* Operations: either select() or poll(). */
    115 #define	SELOP_SELECT	1
    116 #define	SELOP_POLL	2
    117 
    118 /*
    119  * Per-cluster state for select()/poll().  For a system with fewer
    120  * than 32 CPUs, this gives us per-CPU clusters.
    121  */
    122 #define	SELCLUSTERS	32
    123 #define	SELCLUSTERMASK	(SELCLUSTERS - 1)
    124 
    125 typedef struct selcluster {
    126 	kmutex_t	*sc_lock;
    127 	sleepq_t	sc_sleepq;
    128 	int		sc_ncoll;
    129 	uint32_t	sc_mask;
    130 } selcluster_t;
    131 
    132 static inline int	selscan(char *, const int, const size_t, register_t *);
    133 static inline int	pollscan(struct pollfd *, const int, register_t *);
    134 static void		selclear(void);
    135 
    136 static const int sel_flag[] = {
    137 	POLLRDNORM | POLLHUP | POLLERR,
    138 	POLLWRNORM | POLLHUP | POLLERR,
    139 	POLLRDBAND
    140 };
    141 
    142 static syncobj_t select_sobj = {
    143 	.sobj_flag	= SOBJ_SLEEPQ_FIFO,
    144 	.sobj_unsleep	= sleepq_unsleep,
    145 	.sobj_changepri	= sleepq_changepri,
    146 	.sobj_lendpri	= sleepq_lendpri,
    147 	.sobj_owner	= syncobj_noowner,
    148 };
    149 
    150 static selcluster_t	*selcluster[SELCLUSTERS] __read_mostly;
    151 static int		direct_select __read_mostly = 0;
    152 
    153 /*
    154  * Select system call.
    155  */
    156 int
    157 sys___pselect50(struct lwp *l, const struct sys___pselect50_args *uap,
    158     register_t *retval)
    159 {
    160 	/* {
    161 		syscallarg(int)				nd;
    162 		syscallarg(fd_set *)			in;
    163 		syscallarg(fd_set *)			ou;
    164 		syscallarg(fd_set *)			ex;
    165 		syscallarg(const struct timespec *)	ts;
    166 		syscallarg(sigset_t *)			mask;
    167 	} */
    168 	struct timespec	ats, *ts = NULL;
    169 	sigset_t	amask, *mask = NULL;
    170 	int		error;
    171 
    172 	if (SCARG(uap, ts)) {
    173 		error = copyin(SCARG(uap, ts), &ats, sizeof(ats));
    174 		if (error)
    175 			return error;
    176 		ts = &ats;
    177 	}
    178 	if (SCARG(uap, mask) != NULL) {
    179 		error = copyin(SCARG(uap, mask), &amask, sizeof(amask));
    180 		if (error)
    181 			return error;
    182 		mask = &amask;
    183 	}
    184 
    185 	return selcommon(retval, SCARG(uap, nd), SCARG(uap, in),
    186 	    SCARG(uap, ou), SCARG(uap, ex), ts, mask);
    187 }
    188 
    189 int
    190 sys___select50(struct lwp *l, const struct sys___select50_args *uap,
    191     register_t *retval)
    192 {
    193 	/* {
    194 		syscallarg(int)			nd;
    195 		syscallarg(fd_set *)		in;
    196 		syscallarg(fd_set *)		ou;
    197 		syscallarg(fd_set *)		ex;
    198 		syscallarg(struct timeval *)	tv;
    199 	} */
    200 	struct timeval atv;
    201 	struct timespec ats, *ts = NULL;
    202 	int error;
    203 
    204 	if (SCARG(uap, tv)) {
    205 		error = copyin(SCARG(uap, tv), (void *)&atv, sizeof(atv));
    206 		if (error)
    207 			return error;
    208 		TIMEVAL_TO_TIMESPEC(&atv, &ats);
    209 		ts = &ats;
    210 	}
    211 
    212 	return selcommon(retval, SCARG(uap, nd), SCARG(uap, in),
    213 	    SCARG(uap, ou), SCARG(uap, ex), ts, NULL);
    214 }
    215 
    216 /*
    217  * sel_do_scan: common code to perform the scan on descriptors.
    218  */
    219 static int
    220 sel_do_scan(const int op, void *fds, const int nf, const size_t ni,
    221     struct timespec *ts, sigset_t *mask, register_t *retval)
    222 {
    223 	lwp_t		* const l = curlwp;
    224 	selcluster_t	*sc;
    225 	kmutex_t	*lock;
    226 	struct timespec	sleepts;
    227 	int		error, timo;
    228 
    229 	timo = 0;
    230 	if (ts && inittimeleft(ts, &sleepts) == -1) {
    231 		return EINVAL;
    232 	}
    233 
    234 	if (__predict_false(mask))
    235 		sigsuspendsetup(l, mask);
    236 
    237 	sc = curcpu()->ci_data.cpu_selcluster;
    238 	lock = sc->sc_lock;
    239 	l->l_selcluster = sc;
    240 	if (op == SELOP_SELECT) {
    241 		l->l_selbits = fds;
    242 		l->l_selni = ni;
    243 	} else {
    244 		l->l_selbits = NULL;
    245 	}
    246 
    247 	for (;;) {
    248 		int ncoll;
    249 
    250 		SLIST_INIT(&l->l_selwait);
    251 		l->l_selret = 0;
    252 
    253 		/*
    254 		 * No need to lock.  If this is overwritten by another value
    255 		 * while scanning, we will retry below.  We only need to see
    256 		 * exact state from the descriptors that we are about to poll,
    257 		 * and lock activity resulting from fo_poll is enough to
    258 		 * provide an up to date value for new polling activity.
    259 		 */
    260 		l->l_selflag = SEL_SCANNING;
    261 		ncoll = sc->sc_ncoll;
    262 
    263 		if (op == SELOP_SELECT) {
    264 			error = selscan((char *)fds, nf, ni, retval);
    265 		} else {
    266 			error = pollscan((struct pollfd *)fds, nf, retval);
    267 		}
    268 		if (error || *retval)
    269 			break;
    270 		if (ts && (timo = gettimeleft(ts, &sleepts)) <= 0)
    271 			break;
    272 		/*
    273 		 * Acquire the lock and perform the (re)checks.  Note, if
    274 		 * collision has occured, then our state does not matter,
    275 		 * as we must perform re-scan.  Therefore, check it first.
    276 		 */
    277 state_check:
    278 		mutex_spin_enter(lock);
    279 		if (__predict_false(sc->sc_ncoll != ncoll)) {
    280 			/* Collision: perform re-scan. */
    281 			mutex_spin_exit(lock);
    282 			selclear();
    283 			continue;
    284 		}
    285 		if (__predict_true(l->l_selflag == SEL_EVENT)) {
    286 			/* Events occured, they are set directly. */
    287 			mutex_spin_exit(lock);
    288 			break;
    289 		}
    290 		if (__predict_true(l->l_selflag == SEL_RESET)) {
    291 			/* Events occured, but re-scan is requested. */
    292 			mutex_spin_exit(lock);
    293 			selclear();
    294 			continue;
    295 		}
    296 		/* Nothing happen, therefore - sleep. */
    297 		l->l_selflag = SEL_BLOCKING;
    298 		l->l_kpriority = true;
    299 		sleepq_enter(&sc->sc_sleepq, l, lock);
    300 		sleepq_enqueue(&sc->sc_sleepq, sc, "select", &select_sobj);
    301 		error = sleepq_block(timo, true);
    302 		if (error != 0) {
    303 			break;
    304 		}
    305 		/* Awoken: need to check the state. */
    306 		goto state_check;
    307 	}
    308 	selclear();
    309 
    310 	/* Add direct events if any. */
    311 	if (l->l_selflag == SEL_EVENT) {
    312 		KASSERT(l->l_selret != 0);
    313 		*retval += l->l_selret;
    314 	}
    315 
    316 	if (__predict_false(mask))
    317 		sigsuspendteardown(l);
    318 
    319 	/* select and poll are not restarted after signals... */
    320 	if (error == ERESTART)
    321 		return EINTR;
    322 	if (error == EWOULDBLOCK)
    323 		return 0;
    324 	return error;
    325 }
    326 
    327 /* designed to be compatible with FD_SET() FD_ISSET() ... */
    328 static int
    329 anyset(void *p, size_t nbits)
    330 {
    331 	size_t nwords;
    332 	__fd_mask mask;
    333 	__fd_mask *f = (__fd_mask *)p;
    334 
    335 	nwords = nbits / __NFDBITS;
    336 
    337 	while (nwords-- > 0)
    338 		if (*f++ != 0)
    339 			return 1;
    340 
    341 	nbits &= __NFDMASK;
    342 	if (nbits != 0) {
    343 		mask = (1U << nbits) - 1;
    344 		if ((*f & mask) != 0)
    345 			return 1;
    346 	}
    347 	return 0;
    348 }
    349 
    350 int
    351 selcommon(register_t *retval, int nd, fd_set *u_in, fd_set *u_ou,
    352     fd_set *u_ex, struct timespec *ts, sigset_t *mask)
    353 {
    354 	char		smallbits[howmany(FD_SETSIZE, NFDBITS) *
    355 			    sizeof(fd_mask) * 6];
    356 	char 		*bits;
    357 	int		error, nf, fb, db;
    358 	size_t		ni;
    359 
    360 	if (nd < 0)
    361 		return EINVAL;
    362 
    363 	nf = atomic_load_consume(&curlwp->l_fd->fd_dt)->dt_nfiles;
    364 
    365 	/*
    366 	 * Don't allow absurdly large numbers of fds to be selected.
    367 	 * (used to silently truncate, naughty naughty, no more ...)
    368 	 *
    369 	 * The additional FD_SETSISE allows for cases where the limit
    370 	 * is not a round binary number, but the fd_set wants to
    371 	 * include all the possible fds, as fd_sets are always
    372 	 * multiples of 32 bits (__NFDBITS extra would be enough).
    373 	 *
    374 	 * The first test handles the case where the res limit has been
    375 	 * set lower after some fds were opened, we always allow selecting
    376 	 * up to the highest currently open fd.
    377 	 */
    378 	if (nd > nf + FD_SETSIZE &&
    379 	    nd > curlwp->l_proc->p_rlimit[RLIMIT_NOFILE].rlim_max + FD_SETSIZE)
    380 		return EINVAL;
    381 
    382 	fb = howmany(nf, __NFDBITS);		/* how many fd_masks */
    383 	db = howmany(nd, __NFDBITS);
    384 
    385 	if (db > fb) {
    386 		size_t off;
    387 
    388 		/*
    389 		 * the application wants to supply more fd masks than can
    390 		 * possibly represent valid file descriptors.
    391 		 *
    392 		 * Check the excess fd_masks, if any bits are set in them
    393 		 * that must be an error (cannot represent valid fd).
    394 		 *
    395 		 * Supplying lots of extra cleared fd_masks is dumb,
    396 		 * but harmless, so allow that.
    397 		 */
    398 		ni = (db - fb) * sizeof(fd_mask);	/* excess bytes */
    399 		bits = smallbits;
    400 
    401 		/* skip over the valid fd_masks, those will be checked below */
    402 		off = howmany(nf, __NFDBITS) * sizeof(__fd_mask);
    403 
    404 		nd -= fb * NFDBITS;	/* the number of excess fds */
    405 
    406 #define checkbits(name, o, sz, fds)					\
    407 		do {							\
    408 		    if (u_ ## name != NULL) {				\
    409 			error = copyin((char *)u_ ## name + o,		\
    410 					bits, sz);			\
    411 			if (error)					\
    412 			    goto fail;					\
    413 			if (anyset(bits, (fds) ?			\
    414 				 (size_t)(fds) : CHAR_BIT * (sz))) {	\
    415 			    error = EBADF;				\
    416 			    goto fail;					\
    417 			}						\
    418 		    }							\
    419 		} while (0)
    420 
    421 		while (ni > sizeof(smallbits)) {
    422 			checkbits(in, off, sizeof(smallbits), 0);
    423 			checkbits(ou, off, sizeof(smallbits), 0);
    424 			checkbits(ex, off, sizeof(smallbits), 0);
    425 
    426 			off += sizeof(smallbits);
    427 			ni -= sizeof(smallbits);
    428 			nd -= sizeof(smallbits) * CHAR_BIT;
    429 		}
    430 		checkbits(in, off, ni, nd);
    431 		checkbits(ou, off, ni, nd);
    432 		checkbits(ex, off, ni, nd);
    433 #undef checkbits
    434 
    435 		db = fb;	/* now just check the plausible fds */
    436 		nd = db * __NFDBITS;
    437 	}
    438 
    439 	ni = db * sizeof(fd_mask);
    440 	if (ni * 6 > sizeof(smallbits))
    441 		bits = kmem_alloc(ni * 6, KM_SLEEP);
    442 	else
    443 		bits = smallbits;
    444 
    445 #define	getbits(name, x)						\
    446 	do {								\
    447 		if (u_ ## name) {					\
    448 			error = copyin(u_ ## name, bits + ni * x, ni);	\
    449 			if (error)					\
    450 				goto fail;				\
    451 		} else							\
    452 			memset(bits + ni * x, 0, ni);			\
    453 	} while (0)
    454 
    455 	getbits(in, 0);
    456 	getbits(ou, 1);
    457 	getbits(ex, 2);
    458 #undef	getbits
    459 
    460 	error = sel_do_scan(SELOP_SELECT, bits, nd, ni, ts, mask, retval);
    461 
    462 #define copyback(name, x)						\
    463 		do {							\
    464 			if (error == 0 && u_ ## name != NULL)		\
    465 				error = copyout(bits + ni * x,		\
    466 						u_ ## name, ni);	\
    467 		} while (0)
    468 
    469 	copyback(in, 3);
    470 	copyback(ou, 4);
    471 	copyback(ex, 5);
    472 #undef copyback
    473 
    474  fail:
    475 	if (bits != smallbits)
    476 		kmem_free(bits, ni * 6);
    477 	return (error);
    478 }
    479 
    480 static inline int
    481 selscan(char *bits, const int nfd, const size_t ni, register_t *retval)
    482 {
    483 	fd_mask *ibitp, *obitp;
    484 	int msk, i, j, fd, n;
    485 	file_t *fp;
    486 
    487 	ibitp = (fd_mask *)(bits + ni * 0);
    488 	obitp = (fd_mask *)(bits + ni * 3);
    489 	n = 0;
    490 
    491 	memset(obitp, 0, ni * 3);
    492 	for (msk = 0; msk < 3; msk++) {
    493 		for (i = 0; i < nfd; i += NFDBITS) {
    494 			fd_mask ibits, obits;
    495 
    496 			ibits = *ibitp;
    497 			obits = 0;
    498 			while ((j = ffs(ibits)) && (fd = i + --j) < nfd) {
    499 				ibits &= ~(1 << j);
    500 				if ((fp = fd_getfile(fd)) == NULL)
    501 					return (EBADF);
    502 				/*
    503 				 * Setup an argument to selrecord(), which is
    504 				 * a file descriptor number.
    505 				 */
    506 				curlwp->l_selrec = fd;
    507 				if ((*fp->f_ops->fo_poll)(fp, sel_flag[msk])) {
    508 					obits |= (1 << j);
    509 					n++;
    510 				}
    511 				fd_putfile(fd);
    512 			}
    513 			if (obits != 0) {
    514 				if (direct_select) {
    515 					kmutex_t *lock;
    516 					lock = curlwp->l_selcluster->sc_lock;
    517 					mutex_spin_enter(lock);
    518 					*obitp |= obits;
    519 					mutex_spin_exit(lock);
    520 				} else {
    521 					*obitp |= obits;
    522 				}
    523 			}
    524 			ibitp++;
    525 			obitp++;
    526 		}
    527 	}
    528 	*retval = n;
    529 	return (0);
    530 }
    531 
    532 /*
    533  * Poll system call.
    534  */
    535 int
    536 sys_poll(struct lwp *l, const struct sys_poll_args *uap, register_t *retval)
    537 {
    538 	/* {
    539 		syscallarg(struct pollfd *)	fds;
    540 		syscallarg(u_int)		nfds;
    541 		syscallarg(int)			timeout;
    542 	} */
    543 	struct timespec	ats, *ts = NULL;
    544 
    545 	if (SCARG(uap, timeout) != INFTIM) {
    546 		ats.tv_sec = SCARG(uap, timeout) / 1000;
    547 		ats.tv_nsec = (SCARG(uap, timeout) % 1000) * 1000000;
    548 		ts = &ats;
    549 	}
    550 
    551 	return pollcommon(retval, SCARG(uap, fds), SCARG(uap, nfds), ts, NULL);
    552 }
    553 
    554 /*
    555  * Poll system call.
    556  */
    557 int
    558 sys___pollts50(struct lwp *l, const struct sys___pollts50_args *uap,
    559     register_t *retval)
    560 {
    561 	/* {
    562 		syscallarg(struct pollfd *)		fds;
    563 		syscallarg(u_int)			nfds;
    564 		syscallarg(const struct timespec *)	ts;
    565 		syscallarg(const sigset_t *)		mask;
    566 	} */
    567 	struct timespec	ats, *ts = NULL;
    568 	sigset_t	amask, *mask = NULL;
    569 	int		error;
    570 
    571 	if (SCARG(uap, ts)) {
    572 		error = copyin(SCARG(uap, ts), &ats, sizeof(ats));
    573 		if (error)
    574 			return error;
    575 		ts = &ats;
    576 	}
    577 	if (SCARG(uap, mask)) {
    578 		error = copyin(SCARG(uap, mask), &amask, sizeof(amask));
    579 		if (error)
    580 			return error;
    581 		mask = &amask;
    582 	}
    583 
    584 	return pollcommon(retval, SCARG(uap, fds), SCARG(uap, nfds), ts, mask);
    585 }
    586 
    587 int
    588 pollcommon(register_t *retval, struct pollfd *u_fds, u_int nfds,
    589     struct timespec *ts, sigset_t *mask)
    590 {
    591 	struct pollfd	smallfds[32];
    592 	struct pollfd	*fds;
    593 	int		error;
    594 	size_t		ni;
    595 
    596 	if (nfds > curlwp->l_proc->p_rlimit[RLIMIT_NOFILE].rlim_max + 1000) {
    597 		/*
    598 		 * Prevent userland from causing over-allocation.
    599 		 * Raising the default limit too high can still cause
    600 		 * a lot of memory to be allocated, but this also means
    601 		 * that the file descriptor array will also be large.
    602 		 *
    603 		 * To reduce the memory requirements here, we could
    604 		 * process the 'fds' array in chunks, but that
    605 		 * is a lot of code that isn't normally useful.
    606 		 * (Or just move the copyin/out into pollscan().)
    607 		 *
    608 		 * Historically the code silently truncated 'fds' to
    609 		 * dt_nfiles entries - but that does cause issues.
    610 		 *
    611 		 * Using the max limit equivalent to sysctl
    612 		 * kern.maxfiles is the moral equivalent of OPEN_MAX
    613 		 * as specified by POSIX.
    614 		 *
    615 		 * We add a slop of 1000 in case the resource limit was
    616 		 * changed after opening descriptors or the same descriptor
    617 		 * was specified more than once.
    618 		 */
    619 		return EINVAL;
    620 	}
    621 	ni = nfds * sizeof(struct pollfd);
    622 	if (ni > sizeof(smallfds))
    623 		fds = kmem_alloc(ni, KM_SLEEP);
    624 	else
    625 		fds = smallfds;
    626 
    627 	error = copyin(u_fds, fds, ni);
    628 	if (error)
    629 		goto fail;
    630 
    631 	error = sel_do_scan(SELOP_POLL, fds, nfds, ni, ts, mask, retval);
    632 	if (error == 0)
    633 		error = copyout(fds, u_fds, ni);
    634  fail:
    635 	if (fds != smallfds)
    636 		kmem_free(fds, ni);
    637 	return (error);
    638 }
    639 
    640 static inline int
    641 pollscan(struct pollfd *fds, const int nfd, register_t *retval)
    642 {
    643 	file_t *fp;
    644 	int i, n = 0, revents;
    645 
    646 	for (i = 0; i < nfd; i++, fds++) {
    647 		fds->revents = 0;
    648 		if (fds->fd < 0) {
    649 			revents = 0;
    650 		} else if ((fp = fd_getfile(fds->fd)) == NULL) {
    651 			revents = POLLNVAL;
    652 		} else {
    653 			/*
    654 			 * Perform poll: registers select request or returns
    655 			 * the events which are set.  Setup an argument for
    656 			 * selrecord(), which is a pointer to struct pollfd.
    657 			 */
    658 			curlwp->l_selrec = (uintptr_t)fds;
    659 			revents = (*fp->f_ops->fo_poll)(fp,
    660 			    fds->events | POLLERR | POLLHUP);
    661 			fd_putfile(fds->fd);
    662 		}
    663 		if (revents) {
    664 			fds->revents = revents;
    665 			n++;
    666 		}
    667 	}
    668 	*retval = n;
    669 	return (0);
    670 }
    671 
    672 int
    673 seltrue(dev_t dev, int events, lwp_t *l)
    674 {
    675 
    676 	return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
    677 }
    678 
    679 /*
    680  * Record a select request.  Concurrency issues:
    681  *
    682  * The caller holds the same lock across calls to selrecord() and
    683  * selnotify(), so we don't need to consider a concurrent wakeup
    684  * while in this routine.
    685  *
    686  * The only activity we need to guard against is selclear(), called by
    687  * another thread that is exiting sel_do_scan().
    688  * `sel_lwp' can only become non-NULL while the caller's lock is held,
    689  * so it cannot become non-NULL due to a change made by another thread
    690  * while we are in this routine.  It can only become _NULL_ due to a
    691  * call to selclear().
    692  *
    693  * If it is non-NULL and != selector there is the potential for
    694  * selclear() to be called by another thread.  If either of those
    695  * conditions are true, we're not interested in touching the `named
    696  * waiter' part of the selinfo record because we need to record a
    697  * collision.  Hence there is no need for additional locking in this
    698  * routine.
    699  */
    700 void
    701 selrecord(lwp_t *selector, struct selinfo *sip)
    702 {
    703 	selcluster_t *sc;
    704 	lwp_t *other;
    705 
    706 	KASSERT(selector == curlwp);
    707 
    708 	sc = selector->l_selcluster;
    709 	other = sip->sel_lwp;
    710 
    711 	if (other == selector) {
    712 		/* 1. We (selector) already claimed to be the first LWP. */
    713 		KASSERT(sip->sel_cluster == sc);
    714 	} else if (other == NULL) {
    715 		/*
    716 		 * 2. No first LWP, therefore we (selector) are the first.
    717 		 *
    718 		 * There may be unnamed waiters (collisions).  Issue a memory
    719 		 * barrier to ensure that we access sel_lwp (above) before
    720 		 * other fields - this guards against a call to selclear().
    721 		 */
    722 		membar_enter();
    723 		sip->sel_lwp = selector;
    724 		SLIST_INSERT_HEAD(&selector->l_selwait, sip, sel_chain);
    725 		/* Copy the argument, which is for selnotify(). */
    726 		sip->sel_fdinfo = selector->l_selrec;
    727 		/* Replace selinfo's lock with the chosen cluster's lock. */
    728 		sip->sel_cluster = sc;
    729 	} else {
    730 		/* 3. Multiple waiters: record a collision. */
    731 		sip->sel_collision |= sc->sc_mask;
    732 		KASSERT(sip->sel_cluster != NULL);
    733 	}
    734 }
    735 
    736 /*
    737  * sel_setevents: a helper function for selnotify(), to set the events
    738  * for LWP sleeping in selcommon() or pollcommon().
    739  */
    740 static inline bool
    741 sel_setevents(lwp_t *l, struct selinfo *sip, const int events)
    742 {
    743 	const int oflag = l->l_selflag;
    744 	int ret = 0;
    745 
    746 	/*
    747 	 * If we require re-scan or it was required by somebody else,
    748 	 * then just (re)set SEL_RESET and return.
    749 	 */
    750 	if (__predict_false(events == 0 || oflag == SEL_RESET)) {
    751 		l->l_selflag = SEL_RESET;
    752 		return true;
    753 	}
    754 	/*
    755 	 * Direct set.  Note: select state of LWP is locked.  First,
    756 	 * determine whether it is selcommon() or pollcommon().
    757 	 */
    758 	if (l->l_selbits != NULL) {
    759 		const size_t ni = l->l_selni;
    760 		fd_mask *fds = (fd_mask *)l->l_selbits;
    761 		fd_mask *ofds = (fd_mask *)((char *)fds + ni * 3);
    762 		const int fd = sip->sel_fdinfo, fbit = 1 << (fd & __NFDMASK);
    763 		const int idx = fd >> __NFDSHIFT;
    764 		int n;
    765 
    766 		for (n = 0; n < 3; n++) {
    767 			if ((fds[idx] & fbit) != 0 &&
    768 			    (ofds[idx] & fbit) == 0 &&
    769 			    (sel_flag[n] & events)) {
    770 				ofds[idx] |= fbit;
    771 				ret++;
    772 			}
    773 			fds = (fd_mask *)((char *)fds + ni);
    774 			ofds = (fd_mask *)((char *)ofds + ni);
    775 		}
    776 	} else {
    777 		struct pollfd *pfd = (void *)sip->sel_fdinfo;
    778 		int revents = events & (pfd->events | POLLERR | POLLHUP);
    779 
    780 		if (revents) {
    781 			if (pfd->revents == 0)
    782 				ret = 1;
    783 			pfd->revents |= revents;
    784 		}
    785 	}
    786 	/* Check whether there are any events to return. */
    787 	if (!ret) {
    788 		return false;
    789 	}
    790 	/* Indicate direct set and note the event (cluster lock is held). */
    791 	l->l_selflag = SEL_EVENT;
    792 	l->l_selret += ret;
    793 	return true;
    794 }
    795 
    796 /*
    797  * Do a wakeup when a selectable event occurs.  Concurrency issues:
    798  *
    799  * As per selrecord(), the caller's object lock is held.  If there
    800  * is a named waiter, we must acquire the associated selcluster's lock
    801  * in order to synchronize with selclear() and pollers going to sleep
    802  * in sel_do_scan().
    803  *
    804  * sip->sel_cluser cannot change at this point, as it is only changed
    805  * in selrecord(), and concurrent calls to selrecord() are locked
    806  * out by the caller.
    807  */
    808 void
    809 selnotify(struct selinfo *sip, int events, long knhint)
    810 {
    811 	selcluster_t *sc;
    812 	uint32_t mask;
    813 	int index, oflag;
    814 	lwp_t *l;
    815 	kmutex_t *lock;
    816 
    817 	KNOTE(&sip->sel_klist, knhint);
    818 
    819 	if (sip->sel_lwp != NULL) {
    820 		/* One named LWP is waiting. */
    821 		sc = sip->sel_cluster;
    822 		lock = sc->sc_lock;
    823 		mutex_spin_enter(lock);
    824 		/* Still there? */
    825 		if (sip->sel_lwp != NULL) {
    826 			/*
    827 			 * Set the events for our LWP and indicate that.
    828 			 * Otherwise, request for a full re-scan.
    829 			 */
    830 			l = sip->sel_lwp;
    831 			oflag = l->l_selflag;
    832 
    833 			if (!direct_select) {
    834 				l->l_selflag = SEL_RESET;
    835 			} else if (!sel_setevents(l, sip, events)) {
    836 				/* No events to return. */
    837 				mutex_spin_exit(lock);
    838 				return;
    839 			}
    840 
    841 			/*
    842 			 * If thread is sleeping, wake it up.  If it's not
    843 			 * yet asleep, it will notice the change in state
    844 			 * and will re-poll the descriptors.
    845 			 */
    846 			if (oflag == SEL_BLOCKING && l->l_mutex == lock) {
    847 				KASSERT(l->l_wchan == sc);
    848 				sleepq_unsleep(l, false);
    849 			}
    850 		}
    851 		mutex_spin_exit(lock);
    852 	}
    853 
    854 	if ((mask = sip->sel_collision) != 0) {
    855 		/*
    856 		 * There was a collision (multiple waiters): we must
    857 		 * inform all potentially interested waiters.
    858 		 */
    859 		sip->sel_collision = 0;
    860 		do {
    861 			index = ffs(mask) - 1;
    862 			mask &= ~(1 << index);
    863 			sc = selcluster[index];
    864 			lock = sc->sc_lock;
    865 			mutex_spin_enter(lock);
    866 			sc->sc_ncoll++;
    867 			sleepq_wake(&sc->sc_sleepq, sc, (u_int)-1, lock);
    868 		} while (__predict_false(mask != 0));
    869 	}
    870 }
    871 
    872 /*
    873  * Remove an LWP from all objects that it is waiting for.  Concurrency
    874  * issues:
    875  *
    876  * The object owner's (e.g. device driver) lock is not held here.  Calls
    877  * can be made to selrecord() and we do not synchronize against those
    878  * directly using locks.  However, we use `sel_lwp' to lock out changes.
    879  * Before clearing it we must use memory barriers to ensure that we can
    880  * safely traverse the list of selinfo records.
    881  */
    882 static void
    883 selclear(void)
    884 {
    885 	struct selinfo *sip, *next;
    886 	selcluster_t *sc;
    887 	lwp_t *l;
    888 	kmutex_t *lock;
    889 
    890 	l = curlwp;
    891 	sc = l->l_selcluster;
    892 	lock = sc->sc_lock;
    893 
    894 	mutex_spin_enter(lock);
    895 	for (sip = SLIST_FIRST(&l->l_selwait); sip != NULL; sip = next) {
    896 		KASSERT(sip->sel_lwp == l);
    897 		KASSERT(sip->sel_cluster == l->l_selcluster);
    898 
    899 		/*
    900 		 * Read link to next selinfo record, if any.
    901 		 * It's no longer safe to touch `sip' after clearing
    902 		 * `sel_lwp', so ensure that the read of `sel_chain'
    903 		 * completes before the clearing of sel_lwp becomes
    904 		 * globally visible.
    905 		 */
    906 		next = SLIST_NEXT(sip, sel_chain);
    907 		membar_exit();
    908 		/* Release the record for another named waiter to use. */
    909 		sip->sel_lwp = NULL;
    910 	}
    911 	mutex_spin_exit(lock);
    912 }
    913 
    914 /*
    915  * Initialize the select/poll system calls.  Called once for each
    916  * CPU in the system, as they are attached.
    917  */
    918 void
    919 selsysinit(struct cpu_info *ci)
    920 {
    921 	selcluster_t *sc;
    922 	u_int index;
    923 
    924 	/* If already a cluster in place for this bit, re-use. */
    925 	index = cpu_index(ci) & SELCLUSTERMASK;
    926 	sc = selcluster[index];
    927 	if (sc == NULL) {
    928 		sc = kmem_alloc(roundup2(sizeof(selcluster_t),
    929 		    coherency_unit) + coherency_unit, KM_SLEEP);
    930 		sc = (void *)roundup2((uintptr_t)sc, coherency_unit);
    931 		sc->sc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
    932 		sleepq_init(&sc->sc_sleepq);
    933 		sc->sc_ncoll = 0;
    934 		sc->sc_mask = __BIT(index);
    935 		selcluster[index] = sc;
    936 	}
    937 	ci->ci_data.cpu_selcluster = sc;
    938 }
    939 
    940 /*
    941  * Initialize a selinfo record.
    942  */
    943 void
    944 selinit(struct selinfo *sip)
    945 {
    946 
    947 	memset(sip, 0, sizeof(*sip));
    948 }
    949 
    950 /*
    951  * Destroy a selinfo record.  The owning object must not gain new
    952  * references while this is in progress: all activity on the record
    953  * must be stopped.
    954  *
    955  * Concurrency issues: we only need guard against a call to selclear()
    956  * by a thread exiting sel_do_scan().  The caller has prevented further
    957  * references being made to the selinfo record via selrecord(), and it
    958  * will not call selnotify() again.
    959  */
    960 void
    961 seldestroy(struct selinfo *sip)
    962 {
    963 	selcluster_t *sc;
    964 	kmutex_t *lock;
    965 	lwp_t *l;
    966 
    967 	if (sip->sel_lwp == NULL)
    968 		return;
    969 
    970 	/*
    971 	 * Lock out selclear().  The selcluster pointer can't change while
    972 	 * we are here since it is only ever changed in selrecord(),
    973 	 * and that will not be entered again for this record because
    974 	 * it is dying.
    975 	 */
    976 	KASSERT(sip->sel_cluster != NULL);
    977 	sc = sip->sel_cluster;
    978 	lock = sc->sc_lock;
    979 	mutex_spin_enter(lock);
    980 	if ((l = sip->sel_lwp) != NULL) {
    981 		/*
    982 		 * This should rarely happen, so although SLIST_REMOVE()
    983 		 * is slow, using it here is not a problem.
    984 		 */
    985 		KASSERT(l->l_selcluster == sc);
    986 		SLIST_REMOVE(&l->l_selwait, sip, selinfo, sel_chain);
    987 		sip->sel_lwp = NULL;
    988 	}
    989 	mutex_spin_exit(lock);
    990 }
    991 
    992 /*
    993  * System control nodes.
    994  */
    995 SYSCTL_SETUP(sysctl_select_setup, "sysctl select setup")
    996 {
    997 
    998 	sysctl_createv(clog, 0, NULL, NULL,
    999 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1000 		CTLTYPE_INT, "direct_select",
   1001 		SYSCTL_DESCR("Enable/disable direct select (for testing)"),
   1002 		NULL, 0, &direct_select, 0,
   1003 		CTL_KERN, CTL_CREATE, CTL_EOL);
   1004 }
   1005