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