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