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