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