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