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