Home | History | Annotate | Line # | Download | only in kern
sys_select.c revision 1.48
      1 /*	$NetBSD: sys_select.c,v 1.48 2019/09/20 15:00:47 kamil 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.48 2019/09/20 15:00:47 kamil 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 
    209 		if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
    210 			return EINVAL;
    211 
    212 		TIMEVAL_TO_TIMESPEC(&atv, &ats);
    213 		ts = &ats;
    214 	}
    215 
    216 	return selcommon(retval, SCARG(uap, nd), SCARG(uap, in),
    217 	    SCARG(uap, ou), SCARG(uap, ex), ts, NULL);
    218 }
    219 
    220 /*
    221  * sel_do_scan: common code to perform the scan on descriptors.
    222  */
    223 static int
    224 sel_do_scan(const int op, void *fds, const int nf, const size_t ni,
    225     struct timespec *ts, sigset_t *mask, register_t *retval)
    226 {
    227 	lwp_t		* const l = curlwp;
    228 	selcluster_t	*sc;
    229 	kmutex_t	*lock;
    230 	struct timespec	sleepts;
    231 	int		error, timo;
    232 
    233 	timo = 0;
    234 	if (ts && inittimeleft(ts, &sleepts) == -1) {
    235 		return EINVAL;
    236 	}
    237 
    238 	if (__predict_false(mask))
    239 		sigsuspendsetup(l, mask);
    240 
    241 	sc = curcpu()->ci_data.cpu_selcluster;
    242 	lock = sc->sc_lock;
    243 	l->l_selcluster = sc;
    244 	if (op == SELOP_SELECT) {
    245 		l->l_selbits = fds;
    246 		l->l_selni = ni;
    247 	} else {
    248 		l->l_selbits = NULL;
    249 	}
    250 
    251 	for (;;) {
    252 		int ncoll;
    253 
    254 		SLIST_INIT(&l->l_selwait);
    255 		l->l_selret = 0;
    256 
    257 		/*
    258 		 * No need to lock.  If this is overwritten by another value
    259 		 * while scanning, we will retry below.  We only need to see
    260 		 * exact state from the descriptors that we are about to poll,
    261 		 * and lock activity resulting from fo_poll is enough to
    262 		 * provide an up to date value for new polling activity.
    263 		 */
    264 		l->l_selflag = SEL_SCANNING;
    265 		ncoll = sc->sc_ncoll;
    266 
    267 		if (op == SELOP_SELECT) {
    268 			error = selscan((char *)fds, nf, ni, retval);
    269 		} else {
    270 			error = pollscan((struct pollfd *)fds, nf, retval);
    271 		}
    272 		if (error || *retval)
    273 			break;
    274 		if (ts && (timo = gettimeleft(ts, &sleepts)) <= 0)
    275 			break;
    276 		/*
    277 		 * Acquire the lock and perform the (re)checks.  Note, if
    278 		 * collision has occured, then our state does not matter,
    279 		 * as we must perform re-scan.  Therefore, check it first.
    280 		 */
    281 state_check:
    282 		mutex_spin_enter(lock);
    283 		if (__predict_false(sc->sc_ncoll != ncoll)) {
    284 			/* Collision: perform re-scan. */
    285 			mutex_spin_exit(lock);
    286 			selclear();
    287 			continue;
    288 		}
    289 		if (__predict_true(l->l_selflag == SEL_EVENT)) {
    290 			/* Events occured, they are set directly. */
    291 			mutex_spin_exit(lock);
    292 			break;
    293 		}
    294 		if (__predict_true(l->l_selflag == SEL_RESET)) {
    295 			/* Events occured, but re-scan is requested. */
    296 			mutex_spin_exit(lock);
    297 			selclear();
    298 			continue;
    299 		}
    300 		/* Nothing happen, therefore - sleep. */
    301 		l->l_selflag = SEL_BLOCKING;
    302 		l->l_kpriority = true;
    303 		sleepq_enter(&sc->sc_sleepq, l, lock);
    304 		sleepq_enqueue(&sc->sc_sleepq, sc, "select", &select_sobj);
    305 		error = sleepq_block(timo, true);
    306 		if (error != 0) {
    307 			break;
    308 		}
    309 		/* Awoken: need to check the state. */
    310 		goto state_check;
    311 	}
    312 	selclear();
    313 
    314 	/* Add direct events if any. */
    315 	if (l->l_selflag == SEL_EVENT) {
    316 		KASSERT(l->l_selret != 0);
    317 		*retval += l->l_selret;
    318 	}
    319 
    320 	if (__predict_false(mask))
    321 		sigsuspendteardown(l);
    322 
    323 	/* select and poll are not restarted after signals... */
    324 	if (error == ERESTART)
    325 		return EINTR;
    326 	if (error == EWOULDBLOCK)
    327 		return 0;
    328 	return error;
    329 }
    330 
    331 int
    332 selcommon(register_t *retval, int nd, fd_set *u_in, fd_set *u_ou,
    333     fd_set *u_ex, struct timespec *ts, sigset_t *mask)
    334 {
    335 	char		smallbits[howmany(FD_SETSIZE, NFDBITS) *
    336 			    sizeof(fd_mask) * 6];
    337 	char 		*bits;
    338 	int		error, nf;
    339 	size_t		ni;
    340 
    341 	if (nd < 0)
    342 		return (EINVAL);
    343 	nf = curlwp->l_fd->fd_dt->dt_nfiles;
    344 	if (nd > nf) {
    345 		/* forgiving; slightly wrong */
    346 		nd = nf;
    347 	}
    348 	ni = howmany(nd, NFDBITS) * sizeof(fd_mask);
    349 	if (ni * 6 > sizeof(smallbits))
    350 		bits = kmem_alloc(ni * 6, KM_SLEEP);
    351 	else
    352 		bits = smallbits;
    353 
    354 #define	getbits(name, x)						\
    355 	if (u_ ## name) {						\
    356 		error = copyin(u_ ## name, bits + ni * x, ni);		\
    357 		if (error)						\
    358 			goto fail;					\
    359 	} else								\
    360 		memset(bits + ni * x, 0, ni);
    361 	getbits(in, 0);
    362 	getbits(ou, 1);
    363 	getbits(ex, 2);
    364 #undef	getbits
    365 
    366 	error = sel_do_scan(SELOP_SELECT, bits, nd, ni, ts, mask, retval);
    367 	if (error == 0 && u_in != NULL)
    368 		error = copyout(bits + ni * 3, u_in, ni);
    369 	if (error == 0 && u_ou != NULL)
    370 		error = copyout(bits + ni * 4, u_ou, ni);
    371 	if (error == 0 && u_ex != NULL)
    372 		error = copyout(bits + ni * 5, u_ex, ni);
    373  fail:
    374 	if (bits != smallbits)
    375 		kmem_free(bits, ni * 6);
    376 	return (error);
    377 }
    378 
    379 static inline int
    380 selscan(char *bits, const int nfd, const size_t ni, register_t *retval)
    381 {
    382 	fd_mask *ibitp, *obitp;
    383 	int msk, i, j, fd, n;
    384 	file_t *fp;
    385 
    386 	ibitp = (fd_mask *)(bits + ni * 0);
    387 	obitp = (fd_mask *)(bits + ni * 3);
    388 	n = 0;
    389 
    390 	memset(obitp, 0, ni * 3);
    391 	for (msk = 0; msk < 3; msk++) {
    392 		for (i = 0; i < nfd; i += NFDBITS) {
    393 			fd_mask ibits, obits;
    394 
    395 			ibits = *ibitp;
    396 			obits = 0;
    397 			while ((j = ffs(ibits)) && (fd = i + --j) < nfd) {
    398 				ibits &= ~(1U << j);
    399 				if ((fp = fd_getfile(fd)) == NULL)
    400 					return (EBADF);
    401 				/*
    402 				 * Setup an argument to selrecord(), which is
    403 				 * a file descriptor number.
    404 				 */
    405 				curlwp->l_selrec = fd;
    406 				if ((*fp->f_ops->fo_poll)(fp, sel_flag[msk])) {
    407 					obits |= (1U << j);
    408 					n++;
    409 				}
    410 				fd_putfile(fd);
    411 			}
    412 			if (obits != 0) {
    413 				if (direct_select) {
    414 					kmutex_t *lock;
    415 					lock = curlwp->l_selcluster->sc_lock;
    416 					mutex_spin_enter(lock);
    417 					*obitp |= obits;
    418 					mutex_spin_exit(lock);
    419 				} else {
    420 					*obitp |= obits;
    421 				}
    422 			}
    423 			ibitp++;
    424 			obitp++;
    425 		}
    426 	}
    427 	*retval = n;
    428 	return (0);
    429 }
    430 
    431 /*
    432  * Poll system call.
    433  */
    434 int
    435 sys_poll(struct lwp *l, const struct sys_poll_args *uap, register_t *retval)
    436 {
    437 	/* {
    438 		syscallarg(struct pollfd *)	fds;
    439 		syscallarg(u_int)		nfds;
    440 		syscallarg(int)			timeout;
    441 	} */
    442 	struct timespec	ats, *ts = NULL;
    443 
    444 	if (SCARG(uap, timeout) != INFTIM) {
    445 		ats.tv_sec = SCARG(uap, timeout) / 1000;
    446 		ats.tv_nsec = (SCARG(uap, timeout) % 1000) * 1000000;
    447 		ts = &ats;
    448 	}
    449 
    450 	return pollcommon(retval, SCARG(uap, fds), SCARG(uap, nfds), ts, NULL);
    451 }
    452 
    453 /*
    454  * Poll system call.
    455  */
    456 int
    457 sys___pollts50(struct lwp *l, const struct sys___pollts50_args *uap,
    458     register_t *retval)
    459 {
    460 	/* {
    461 		syscallarg(struct pollfd *)		fds;
    462 		syscallarg(u_int)			nfds;
    463 		syscallarg(const struct timespec *)	ts;
    464 		syscallarg(const sigset_t *)		mask;
    465 	} */
    466 	struct timespec	ats, *ts = NULL;
    467 	sigset_t	amask, *mask = NULL;
    468 	int		error;
    469 
    470 	if (SCARG(uap, ts)) {
    471 		error = copyin(SCARG(uap, ts), &ats, sizeof(ats));
    472 		if (error)
    473 			return error;
    474 		ts = &ats;
    475 	}
    476 	if (SCARG(uap, mask)) {
    477 		error = copyin(SCARG(uap, mask), &amask, sizeof(amask));
    478 		if (error)
    479 			return error;
    480 		mask = &amask;
    481 	}
    482 
    483 	return pollcommon(retval, SCARG(uap, fds), SCARG(uap, nfds), ts, mask);
    484 }
    485 
    486 int
    487 pollcommon(register_t *retval, struct pollfd *u_fds, u_int nfds,
    488     struct timespec *ts, sigset_t *mask)
    489 {
    490 	struct pollfd	smallfds[32];
    491 	struct pollfd	*fds;
    492 	int		error;
    493 	size_t		ni;
    494 
    495 	if (nfds > curlwp->l_proc->p_rlimit[RLIMIT_NOFILE].rlim_max + 1000) {
    496 		/*
    497 		 * Prevent userland from causing over-allocation.
    498 		 * Raising the default limit too high can still cause
    499 		 * a lot of memory to be allocated, but this also means
    500 		 * that the file descriptor array will also be large.
    501 		 *
    502 		 * To reduce the memory requirements here, we could
    503 		 * process the 'fds' array in chunks, but that
    504 		 * is a lot of code that isn't normally useful.
    505 		 * (Or just move the copyin/out into pollscan().)
    506 		 *
    507 		 * Historically the code silently truncated 'fds' to
    508 		 * dt_nfiles entries - but that does cause issues.
    509 		 *
    510 		 * Using the max limit equivalent to sysctl
    511 		 * kern.maxfiles is the moral equivalent of OPEN_MAX
    512 		 * as specified by POSIX.
    513 		 *
    514 		 * We add a slop of 1000 in case the resource limit was
    515 		 * changed after opening descriptors or the same descriptor
    516 		 * was specified more than once.
    517 		 */
    518 		return EINVAL;
    519 	}
    520 	ni = nfds * sizeof(struct pollfd);
    521 	if (ni > sizeof(smallfds))
    522 		fds = kmem_alloc(ni, KM_SLEEP);
    523 	else
    524 		fds = smallfds;
    525 
    526 	error = copyin(u_fds, fds, ni);
    527 	if (error)
    528 		goto fail;
    529 
    530 	error = sel_do_scan(SELOP_POLL, fds, nfds, ni, ts, mask, retval);
    531 	if (error == 0)
    532 		error = copyout(fds, u_fds, ni);
    533  fail:
    534 	if (fds != smallfds)
    535 		kmem_free(fds, ni);
    536 	return (error);
    537 }
    538 
    539 static inline int
    540 pollscan(struct pollfd *fds, const int nfd, register_t *retval)
    541 {
    542 	file_t *fp;
    543 	int i, n = 0, revents;
    544 
    545 	for (i = 0; i < nfd; i++, fds++) {
    546 		fds->revents = 0;
    547 		if (fds->fd < 0) {
    548 			revents = 0;
    549 		} else if ((fp = fd_getfile(fds->fd)) == NULL) {
    550 			revents = POLLNVAL;
    551 		} else {
    552 			/*
    553 			 * Perform poll: registers select request or returns
    554 			 * the events which are set.  Setup an argument for
    555 			 * selrecord(), which is a pointer to struct pollfd.
    556 			 */
    557 			curlwp->l_selrec = (uintptr_t)fds;
    558 			revents = (*fp->f_ops->fo_poll)(fp,
    559 			    fds->events | POLLERR | POLLHUP);
    560 			fd_putfile(fds->fd);
    561 		}
    562 		if (revents) {
    563 			fds->revents = revents;
    564 			n++;
    565 		}
    566 	}
    567 	*retval = n;
    568 	return (0);
    569 }
    570 
    571 int
    572 seltrue(dev_t dev, int events, lwp_t *l)
    573 {
    574 
    575 	return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
    576 }
    577 
    578 /*
    579  * Record a select request.  Concurrency issues:
    580  *
    581  * The caller holds the same lock across calls to selrecord() and
    582  * selnotify(), so we don't need to consider a concurrent wakeup
    583  * while in this routine.
    584  *
    585  * The only activity we need to guard against is selclear(), called by
    586  * another thread that is exiting sel_do_scan().
    587  * `sel_lwp' can only become non-NULL while the caller's lock is held,
    588  * so it cannot become non-NULL due to a change made by another thread
    589  * while we are in this routine.  It can only become _NULL_ due to a
    590  * call to selclear().
    591  *
    592  * If it is non-NULL and != selector there is the potential for
    593  * selclear() to be called by another thread.  If either of those
    594  * conditions are true, we're not interested in touching the `named
    595  * waiter' part of the selinfo record because we need to record a
    596  * collision.  Hence there is no need for additional locking in this
    597  * routine.
    598  */
    599 void
    600 selrecord(lwp_t *selector, struct selinfo *sip)
    601 {
    602 	selcluster_t *sc;
    603 	lwp_t *other;
    604 
    605 	KASSERT(selector == curlwp);
    606 
    607 	sc = selector->l_selcluster;
    608 	other = sip->sel_lwp;
    609 
    610 	if (other == selector) {
    611 		/* 1. We (selector) already claimed to be the first LWP. */
    612 		KASSERT(sip->sel_cluster == sc);
    613 	} else if (other == NULL) {
    614 		/*
    615 		 * 2. No first LWP, therefore we (selector) are the first.
    616 		 *
    617 		 * There may be unnamed waiters (collisions).  Issue a memory
    618 		 * barrier to ensure that we access sel_lwp (above) before
    619 		 * other fields - this guards against a call to selclear().
    620 		 */
    621 		membar_enter();
    622 		sip->sel_lwp = selector;
    623 		SLIST_INSERT_HEAD(&selector->l_selwait, sip, sel_chain);
    624 		/* Copy the argument, which is for selnotify(). */
    625 		sip->sel_fdinfo = selector->l_selrec;
    626 		/* Replace selinfo's lock with the chosen cluster's lock. */
    627 		sip->sel_cluster = sc;
    628 	} else {
    629 		/* 3. Multiple waiters: record a collision. */
    630 		sip->sel_collision |= sc->sc_mask;
    631 		KASSERT(sip->sel_cluster != NULL);
    632 	}
    633 }
    634 
    635 /*
    636  * sel_setevents: a helper function for selnotify(), to set the events
    637  * for LWP sleeping in selcommon() or pollcommon().
    638  */
    639 static inline bool
    640 sel_setevents(lwp_t *l, struct selinfo *sip, const int events)
    641 {
    642 	const int oflag = l->l_selflag;
    643 	int ret = 0;
    644 
    645 	/*
    646 	 * If we require re-scan or it was required by somebody else,
    647 	 * then just (re)set SEL_RESET and return.
    648 	 */
    649 	if (__predict_false(events == 0 || oflag == SEL_RESET)) {
    650 		l->l_selflag = SEL_RESET;
    651 		return true;
    652 	}
    653 	/*
    654 	 * Direct set.  Note: select state of LWP is locked.  First,
    655 	 * determine whether it is selcommon() or pollcommon().
    656 	 */
    657 	if (l->l_selbits != NULL) {
    658 		const size_t ni = l->l_selni;
    659 		fd_mask *fds = (fd_mask *)l->l_selbits;
    660 		fd_mask *ofds = (fd_mask *)((char *)fds + ni * 3);
    661 		const int fd = sip->sel_fdinfo, fbit = 1 << (fd & __NFDMASK);
    662 		const int idx = fd >> __NFDSHIFT;
    663 		int n;
    664 
    665 		for (n = 0; n < 3; n++) {
    666 			if ((fds[idx] & fbit) != 0 &&
    667 			    (ofds[idx] & fbit) == 0 &&
    668 			    (sel_flag[n] & events)) {
    669 				ofds[idx] |= fbit;
    670 				ret++;
    671 			}
    672 			fds = (fd_mask *)((char *)fds + ni);
    673 			ofds = (fd_mask *)((char *)ofds + ni);
    674 		}
    675 	} else {
    676 		struct pollfd *pfd = (void *)sip->sel_fdinfo;
    677 		int revents = events & (pfd->events | POLLERR | POLLHUP);
    678 
    679 		if (revents) {
    680 			if (pfd->revents == 0)
    681 				ret = 1;
    682 			pfd->revents |= revents;
    683 		}
    684 	}
    685 	/* Check whether there are any events to return. */
    686 	if (!ret) {
    687 		return false;
    688 	}
    689 	/* Indicate direct set and note the event (cluster lock is held). */
    690 	l->l_selflag = SEL_EVENT;
    691 	l->l_selret += ret;
    692 	return true;
    693 }
    694 
    695 /*
    696  * Do a wakeup when a selectable event occurs.  Concurrency issues:
    697  *
    698  * As per selrecord(), the caller's object lock is held.  If there
    699  * is a named waiter, we must acquire the associated selcluster's lock
    700  * in order to synchronize with selclear() and pollers going to sleep
    701  * in sel_do_scan().
    702  *
    703  * sip->sel_cluser cannot change at this point, as it is only changed
    704  * in selrecord(), and concurrent calls to selrecord() are locked
    705  * out by the caller.
    706  */
    707 void
    708 selnotify(struct selinfo *sip, int events, long knhint)
    709 {
    710 	selcluster_t *sc;
    711 	uint32_t mask;
    712 	int index, oflag;
    713 	lwp_t *l;
    714 	kmutex_t *lock;
    715 
    716 	KNOTE(&sip->sel_klist, knhint);
    717 
    718 	if (sip->sel_lwp != NULL) {
    719 		/* One named LWP is waiting. */
    720 		sc = sip->sel_cluster;
    721 		lock = sc->sc_lock;
    722 		mutex_spin_enter(lock);
    723 		/* Still there? */
    724 		if (sip->sel_lwp != NULL) {
    725 			/*
    726 			 * Set the events for our LWP and indicate that.
    727 			 * Otherwise, request for a full re-scan.
    728 			 */
    729 			l = sip->sel_lwp;
    730 			oflag = l->l_selflag;
    731 
    732 			if (!direct_select) {
    733 				l->l_selflag = SEL_RESET;
    734 			} else if (!sel_setevents(l, sip, events)) {
    735 				/* No events to return. */
    736 				mutex_spin_exit(lock);
    737 				return;
    738 			}
    739 
    740 			/*
    741 			 * If thread is sleeping, wake it up.  If it's not
    742 			 * yet asleep, it will notice the change in state
    743 			 * and will re-poll the descriptors.
    744 			 */
    745 			if (oflag == SEL_BLOCKING && l->l_mutex == lock) {
    746 				KASSERT(l->l_wchan == sc);
    747 				sleepq_unsleep(l, false);
    748 			}
    749 		}
    750 		mutex_spin_exit(lock);
    751 	}
    752 
    753 	if ((mask = sip->sel_collision) != 0) {
    754 		/*
    755 		 * There was a collision (multiple waiters): we must
    756 		 * inform all potentially interested waiters.
    757 		 */
    758 		sip->sel_collision = 0;
    759 		do {
    760 			index = ffs(mask) - 1;
    761 			mask &= ~(1U << index);
    762 			sc = selcluster[index];
    763 			lock = sc->sc_lock;
    764 			mutex_spin_enter(lock);
    765 			sc->sc_ncoll++;
    766 			sleepq_wake(&sc->sc_sleepq, sc, (u_int)-1, lock);
    767 		} while (__predict_false(mask != 0));
    768 	}
    769 }
    770 
    771 /*
    772  * Remove an LWP from all objects that it is waiting for.  Concurrency
    773  * issues:
    774  *
    775  * The object owner's (e.g. device driver) lock is not held here.  Calls
    776  * can be made to selrecord() and we do not synchronize against those
    777  * directly using locks.  However, we use `sel_lwp' to lock out changes.
    778  * Before clearing it we must use memory barriers to ensure that we can
    779  * safely traverse the list of selinfo records.
    780  */
    781 static void
    782 selclear(void)
    783 {
    784 	struct selinfo *sip, *next;
    785 	selcluster_t *sc;
    786 	lwp_t *l;
    787 	kmutex_t *lock;
    788 
    789 	l = curlwp;
    790 	sc = l->l_selcluster;
    791 	lock = sc->sc_lock;
    792 
    793 	mutex_spin_enter(lock);
    794 	for (sip = SLIST_FIRST(&l->l_selwait); sip != NULL; sip = next) {
    795 		KASSERT(sip->sel_lwp == l);
    796 		KASSERT(sip->sel_cluster == l->l_selcluster);
    797 
    798 		/*
    799 		 * Read link to next selinfo record, if any.
    800 		 * It's no longer safe to touch `sip' after clearing
    801 		 * `sel_lwp', so ensure that the read of `sel_chain'
    802 		 * completes before the clearing of sel_lwp becomes
    803 		 * globally visible.
    804 		 */
    805 		next = SLIST_NEXT(sip, sel_chain);
    806 		membar_exit();
    807 		/* Release the record for another named waiter to use. */
    808 		sip->sel_lwp = NULL;
    809 	}
    810 	mutex_spin_exit(lock);
    811 }
    812 
    813 /*
    814  * Initialize the select/poll system calls.  Called once for each
    815  * CPU in the system, as they are attached.
    816  */
    817 void
    818 selsysinit(struct cpu_info *ci)
    819 {
    820 	selcluster_t *sc;
    821 	u_int index;
    822 
    823 	/* If already a cluster in place for this bit, re-use. */
    824 	index = cpu_index(ci) & SELCLUSTERMASK;
    825 	sc = selcluster[index];
    826 	if (sc == NULL) {
    827 		sc = kmem_alloc(roundup2(sizeof(selcluster_t),
    828 		    coherency_unit) + coherency_unit, KM_SLEEP);
    829 		sc = (void *)roundup2((uintptr_t)sc, coherency_unit);
    830 		sc->sc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
    831 		sleepq_init(&sc->sc_sleepq);
    832 		sc->sc_ncoll = 0;
    833 		sc->sc_mask = __BIT(index);
    834 		selcluster[index] = sc;
    835 	}
    836 	ci->ci_data.cpu_selcluster = sc;
    837 }
    838 
    839 /*
    840  * Initialize a selinfo record.
    841  */
    842 void
    843 selinit(struct selinfo *sip)
    844 {
    845 
    846 	memset(sip, 0, sizeof(*sip));
    847 }
    848 
    849 /*
    850  * Destroy a selinfo record.  The owning object must not gain new
    851  * references while this is in progress: all activity on the record
    852  * must be stopped.
    853  *
    854  * Concurrency issues: we only need guard against a call to selclear()
    855  * by a thread exiting sel_do_scan().  The caller has prevented further
    856  * references being made to the selinfo record via selrecord(), and it
    857  * will not call selnotify() again.
    858  */
    859 void
    860 seldestroy(struct selinfo *sip)
    861 {
    862 	selcluster_t *sc;
    863 	kmutex_t *lock;
    864 	lwp_t *l;
    865 
    866 	if (sip->sel_lwp == NULL)
    867 		return;
    868 
    869 	/*
    870 	 * Lock out selclear().  The selcluster pointer can't change while
    871 	 * we are here since it is only ever changed in selrecord(),
    872 	 * and that will not be entered again for this record because
    873 	 * it is dying.
    874 	 */
    875 	KASSERT(sip->sel_cluster != NULL);
    876 	sc = sip->sel_cluster;
    877 	lock = sc->sc_lock;
    878 	mutex_spin_enter(lock);
    879 	if ((l = sip->sel_lwp) != NULL) {
    880 		/*
    881 		 * This should rarely happen, so although SLIST_REMOVE()
    882 		 * is slow, using it here is not a problem.
    883 		 */
    884 		KASSERT(l->l_selcluster == sc);
    885 		SLIST_REMOVE(&l->l_selwait, sip, selinfo, sel_chain);
    886 		sip->sel_lwp = NULL;
    887 	}
    888 	mutex_spin_exit(lock);
    889 }
    890 
    891 /*
    892  * System control nodes.
    893  */
    894 SYSCTL_SETUP(sysctl_select_setup, "sysctl select setup")
    895 {
    896 
    897 	sysctl_createv(clog, 0, NULL, NULL,
    898 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    899 		CTLTYPE_INT, "direct_select",
    900 		SYSCTL_DESCR("Enable/disable direct select (for testing)"),
    901 		NULL, 0, &direct_select, 0,
    902 		CTL_KERN, CTL_CREATE, CTL_EOL);
    903 }
    904