sys_select.c revision 1.63 1 /* $NetBSD: sys_select.c,v 1.63 2023/10/04 20:29:18 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2007, 2008, 2009, 2010, 2019, 2020, 2023
5 * The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Andrew Doran and Mindaugas Rasiukevicius.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * Copyright (c) 1982, 1986, 1989, 1993
35 * The Regents of the University of California. All rights reserved.
36 * (c) UNIX System Laboratories, Inc.
37 * All or some portions of this file are derived from material licensed
38 * to the University of California by American Telephone and Telegraph
39 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
40 * the permission of UNIX System Laboratories, Inc.
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)sys_generic.c 8.9 (Berkeley) 2/14/95
67 */
68
69 /*
70 * System calls of synchronous I/O multiplexing subsystem.
71 *
72 * Locking
73 *
74 * Two locks are used: <object-lock> and selcluster_t::sc_lock.
75 *
76 * The <object-lock> might be a device driver or another subsystem, e.g.
77 * socket or pipe. This lock is not exported, and thus invisible to this
78 * subsystem. Mainly, synchronisation between selrecord() and selnotify()
79 * routines depends on this lock, as it will be described in the comments.
80 *
81 * Lock order
82 *
83 * <object-lock> ->
84 * selcluster_t::sc_lock
85 */
86
87 #include <sys/cdefs.h>
88 __KERNEL_RCSID(0, "$NetBSD: sys_select.c,v 1.63 2023/10/04 20:29:18 ad Exp $");
89
90 #include <sys/param.h>
91 #include <sys/systm.h>
92 #include <sys/filedesc.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/lwp.h>
100 #include <sys/poll.h>
101 #include <sys/mount.h>
102 #include <sys/syscallargs.h>
103 #include <sys/cpu.h>
104 #include <sys/atomic.h>
105 #include <sys/socketvar.h>
106 #include <sys/sleepq.h>
107 #include <sys/sysctl.h>
108 #include <sys/bitops.h>
109
110 /* Flags for lwp::l_selflag. */
111 #define SEL_RESET 0 /* awoken, interrupted, or not yet polling */
112 #define SEL_SCANNING 1 /* polling descriptors */
113 #define SEL_BLOCKING 2 /* blocking and waiting for event */
114 #define SEL_EVENT 3 /* interrupted, events set directly */
115
116 /*
117 * Per-cluster state for select()/poll(). For a system with fewer
118 * than 64 CPUs, this gives us per-CPU clusters.
119 */
120 #define SELCLUSTERS 64
121 #define SELCLUSTERMASK (SELCLUSTERS - 1)
122
123 typedef struct selcluster {
124 kmutex_t *sc_lock;
125 sleepq_t sc_sleepq;
126 uint64_t sc_mask;
127 int sc_ncoll;
128 } selcluster_t;
129
130 static inline int selscan(char *, const int, const size_t, register_t *);
131 static inline int pollscan(struct pollfd *, const int, register_t *);
132 static void selclear(void);
133
134 static const int sel_flag[] = {
135 POLLRDNORM | POLLHUP | POLLERR,
136 POLLWRNORM | POLLHUP | POLLERR,
137 POLLRDBAND
138 };
139
140 /*
141 * LWPs are woken using the sleep queue only due to a collision, the case
142 * with the maximum Suck Factor. Save the cost of sorting for named waiters
143 * by inserting in LIFO order. In the future it would be preferable to not
144 * enqueue LWPs at all, unless subject to a collision.
145 */
146 syncobj_t select_sobj = {
147 .sobj_name = "select",
148 .sobj_flag = SOBJ_SLEEPQ_LIFO,
149 .sobj_boostpri = PRI_KERNEL,
150 .sobj_unsleep = sleepq_unsleep,
151 .sobj_changepri = sleepq_changepri,
152 .sobj_lendpri = sleepq_lendpri,
153 .sobj_owner = syncobj_noowner,
154 };
155
156 static selcluster_t *selcluster[SELCLUSTERS] __read_mostly;
157 static int direct_select __read_mostly = 0;
158
159 /* Operations: either select() or poll(). */
160 const char selop_select[] = "select";
161 const char selop_poll[] = "poll";
162
163 /*
164 * Select system call.
165 */
166 int
167 sys___pselect50(struct lwp *l, const struct sys___pselect50_args *uap,
168 register_t *retval)
169 {
170 /* {
171 syscallarg(int) nd;
172 syscallarg(fd_set *) in;
173 syscallarg(fd_set *) ou;
174 syscallarg(fd_set *) ex;
175 syscallarg(const struct timespec *) ts;
176 syscallarg(sigset_t *) mask;
177 } */
178 struct timespec ats, *ts = NULL;
179 sigset_t amask, *mask = NULL;
180 int error;
181
182 if (SCARG(uap, ts)) {
183 error = copyin(SCARG(uap, ts), &ats, sizeof(ats));
184 if (error)
185 return error;
186 ts = &ats;
187 }
188 if (SCARG(uap, mask) != NULL) {
189 error = copyin(SCARG(uap, mask), &amask, sizeof(amask));
190 if (error)
191 return error;
192 mask = &amask;
193 }
194
195 return selcommon(retval, SCARG(uap, nd), SCARG(uap, in),
196 SCARG(uap, ou), SCARG(uap, ex), ts, mask);
197 }
198
199 int
200 sys___select50(struct lwp *l, const struct sys___select50_args *uap,
201 register_t *retval)
202 {
203 /* {
204 syscallarg(int) nd;
205 syscallarg(fd_set *) in;
206 syscallarg(fd_set *) ou;
207 syscallarg(fd_set *) ex;
208 syscallarg(struct timeval *) tv;
209 } */
210 struct timeval atv;
211 struct timespec ats, *ts = NULL;
212 int error;
213
214 if (SCARG(uap, tv)) {
215 error = copyin(SCARG(uap, tv), (void *)&atv, sizeof(atv));
216 if (error)
217 return error;
218
219 if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
220 return EINVAL;
221
222 TIMEVAL_TO_TIMESPEC(&atv, &ats);
223 ts = &ats;
224 }
225
226 return selcommon(retval, SCARG(uap, nd), SCARG(uap, in),
227 SCARG(uap, ou), SCARG(uap, ex), ts, NULL);
228 }
229
230 /*
231 * sel_do_scan: common code to perform the scan on descriptors.
232 */
233 static int
234 sel_do_scan(const char *opname, void *fds, const int nf, const size_t ni,
235 struct timespec *ts, sigset_t *mask, register_t *retval)
236 {
237 lwp_t * const l = curlwp;
238 selcluster_t *sc;
239 kmutex_t *lock;
240 struct timespec sleepts;
241 int error, timo;
242
243 timo = 0;
244 if (ts && inittimeleft(ts, &sleepts) == -1) {
245 return EINVAL;
246 }
247
248 if (__predict_false(mask))
249 sigsuspendsetup(l, mask);
250
251 /*
252 * We may context switch during or at any time after picking a CPU
253 * and cluster to associate with, but it doesn't matter. In the
254 * unlikely event we migrate elsewhere all we risk is a little lock
255 * contention; correctness is not sacrificed.
256 */
257 sc = curcpu()->ci_data.cpu_selcluster;
258 lock = sc->sc_lock;
259 l->l_selcluster = sc;
260
261 if (opname == selop_select) {
262 l->l_selbits = fds;
263 l->l_selni = ni;
264 } else {
265 l->l_selbits = NULL;
266 }
267
268 for (;;) {
269 int ncoll;
270
271 SLIST_INIT(&l->l_selwait);
272 l->l_selret = 0;
273
274 /*
275 * No need to lock. If this is overwritten by another value
276 * while scanning, we will retry below. We only need to see
277 * exact state from the descriptors that we are about to poll,
278 * and lock activity resulting from fo_poll is enough to
279 * provide an up to date value for new polling activity.
280 */
281 if (ts && (ts->tv_sec | ts->tv_nsec | direct_select) == 0) {
282 /* Non-blocking: no need for selrecord()/selclear() */
283 l->l_selflag = SEL_RESET;
284 } else {
285 l->l_selflag = SEL_SCANNING;
286 }
287 ncoll = sc->sc_ncoll;
288 membar_release();
289
290 if (opname == selop_select) {
291 error = selscan((char *)fds, nf, ni, retval);
292 } else {
293 error = pollscan((struct pollfd *)fds, nf, retval);
294 }
295 if (error || *retval)
296 break;
297 if (ts && (timo = gettimeleft(ts, &sleepts)) <= 0)
298 break;
299 /*
300 * Acquire the lock and perform the (re)checks. Note, if
301 * collision has occurred, then our state does not matter,
302 * as we must perform re-scan. Therefore, check it first.
303 */
304 state_check:
305 mutex_spin_enter(lock);
306 if (__predict_false(sc->sc_ncoll != ncoll)) {
307 /* Collision: perform re-scan. */
308 mutex_spin_exit(lock);
309 selclear();
310 continue;
311 }
312 if (__predict_true(l->l_selflag == SEL_EVENT)) {
313 /* Events occurred, they are set directly. */
314 mutex_spin_exit(lock);
315 break;
316 }
317 if (__predict_true(l->l_selflag == SEL_RESET)) {
318 /* Events occurred, but re-scan is requested. */
319 mutex_spin_exit(lock);
320 selclear();
321 continue;
322 }
323 /* Nothing happen, therefore - sleep. */
324 l->l_selflag = SEL_BLOCKING;
325 KASSERT(l->l_blcnt == 0);
326 (void)sleepq_enter(&sc->sc_sleepq, l, lock);
327 sleepq_enqueue(&sc->sc_sleepq, sc, opname, &select_sobj, true);
328 error = sleepq_block(timo, true, &select_sobj, 0);
329 if (error != 0) {
330 break;
331 }
332 /* Awoken: need to check the state. */
333 goto state_check;
334 }
335 selclear();
336
337 /* Add direct events if any. */
338 if (l->l_selflag == SEL_EVENT) {
339 KASSERT(l->l_selret != 0);
340 *retval += l->l_selret;
341 }
342
343 if (__predict_false(mask))
344 sigsuspendteardown(l);
345
346 /* select and poll are not restarted after signals... */
347 if (error == ERESTART)
348 return EINTR;
349 if (error == EWOULDBLOCK)
350 return 0;
351 return error;
352 }
353
354 int
355 selcommon(register_t *retval, int nd, fd_set *u_in, fd_set *u_ou,
356 fd_set *u_ex, struct timespec *ts, sigset_t *mask)
357 {
358 char smallbits[howmany(FD_SETSIZE, NFDBITS) *
359 sizeof(fd_mask) * 6];
360 char *bits;
361 int error, nf;
362 size_t ni;
363
364 if (nd < 0)
365 return (EINVAL);
366 nf = atomic_load_consume(&curlwp->l_fd->fd_dt)->dt_nfiles;
367 if (nd > nf) {
368 /* forgiving; slightly wrong */
369 nd = nf;
370 }
371 ni = howmany(nd, NFDBITS) * sizeof(fd_mask);
372 if (ni * 6 > sizeof(smallbits))
373 bits = kmem_alloc(ni * 6, KM_SLEEP);
374 else
375 bits = smallbits;
376
377 #define getbits(name, x) \
378 if (u_ ## name) { \
379 error = copyin(u_ ## name, bits + ni * x, ni); \
380 if (error) \
381 goto fail; \
382 } else \
383 memset(bits + ni * x, 0, ni);
384 getbits(in, 0);
385 getbits(ou, 1);
386 getbits(ex, 2);
387 #undef getbits
388
389 error = sel_do_scan(selop_select, bits, nd, ni, ts, mask, retval);
390 if (error == 0 && u_in != NULL)
391 error = copyout(bits + ni * 3, u_in, ni);
392 if (error == 0 && u_ou != NULL)
393 error = copyout(bits + ni * 4, u_ou, ni);
394 if (error == 0 && u_ex != NULL)
395 error = copyout(bits + ni * 5, u_ex, ni);
396 fail:
397 if (bits != smallbits)
398 kmem_free(bits, ni * 6);
399 return (error);
400 }
401
402 static inline int
403 selscan(char *bits, const int nfd, const size_t ni, register_t *retval)
404 {
405 fd_mask *ibitp, *obitp;
406 int msk, i, j, fd, n;
407 file_t *fp;
408 lwp_t *l;
409
410 ibitp = (fd_mask *)(bits + ni * 0);
411 obitp = (fd_mask *)(bits + ni * 3);
412 n = 0;
413 l = curlwp;
414
415 memset(obitp, 0, ni * 3);
416 for (msk = 0; msk < 3; msk++) {
417 for (i = 0; i < nfd; i += NFDBITS) {
418 fd_mask ibits, obits;
419
420 ibits = *ibitp;
421 obits = 0;
422 while ((j = ffs(ibits)) && (fd = i + --j) < nfd) {
423 ibits &= ~(1U << j);
424 if ((fp = fd_getfile(fd)) == NULL)
425 return (EBADF);
426 /*
427 * Setup an argument to selrecord(), which is
428 * a file descriptor number.
429 */
430 l->l_selrec = fd;
431 if ((*fp->f_ops->fo_poll)(fp, sel_flag[msk])) {
432 if (!direct_select) {
433 /*
434 * Have events: do nothing in
435 * selrecord().
436 */
437 l->l_selflag = SEL_RESET;
438 }
439 obits |= (1U << j);
440 n++;
441 }
442 fd_putfile(fd);
443 }
444 if (obits != 0) {
445 if (direct_select) {
446 kmutex_t *lock;
447 lock = l->l_selcluster->sc_lock;
448 mutex_spin_enter(lock);
449 *obitp |= obits;
450 mutex_spin_exit(lock);
451 } else {
452 *obitp |= obits;
453 }
454 }
455 ibitp++;
456 obitp++;
457 }
458 }
459 *retval = n;
460 return (0);
461 }
462
463 /*
464 * Poll system call.
465 */
466 int
467 sys_poll(struct lwp *l, const struct sys_poll_args *uap, register_t *retval)
468 {
469 /* {
470 syscallarg(struct pollfd *) fds;
471 syscallarg(u_int) nfds;
472 syscallarg(int) timeout;
473 } */
474 struct timespec ats, *ts = NULL;
475
476 if (SCARG(uap, timeout) != INFTIM) {
477 ats.tv_sec = SCARG(uap, timeout) / 1000;
478 ats.tv_nsec = (SCARG(uap, timeout) % 1000) * 1000000;
479 ts = &ats;
480 }
481
482 return pollcommon(retval, SCARG(uap, fds), SCARG(uap, nfds), ts, NULL);
483 }
484
485 /*
486 * Poll system call.
487 */
488 int
489 sys___pollts50(struct lwp *l, const struct sys___pollts50_args *uap,
490 register_t *retval)
491 {
492 /* {
493 syscallarg(struct pollfd *) fds;
494 syscallarg(u_int) nfds;
495 syscallarg(const struct timespec *) ts;
496 syscallarg(const sigset_t *) mask;
497 } */
498 struct timespec ats, *ts = NULL;
499 sigset_t amask, *mask = NULL;
500 int error;
501
502 if (SCARG(uap, ts)) {
503 error = copyin(SCARG(uap, ts), &ats, sizeof(ats));
504 if (error)
505 return error;
506 ts = &ats;
507 }
508 if (SCARG(uap, mask)) {
509 error = copyin(SCARG(uap, mask), &amask, sizeof(amask));
510 if (error)
511 return error;
512 mask = &amask;
513 }
514
515 return pollcommon(retval, SCARG(uap, fds), SCARG(uap, nfds), ts, mask);
516 }
517
518 int
519 pollcommon(register_t *retval, struct pollfd *u_fds, u_int nfds,
520 struct timespec *ts, sigset_t *mask)
521 {
522 struct pollfd smallfds[32];
523 struct pollfd *fds;
524 int error;
525 size_t ni;
526
527 if (nfds > curlwp->l_proc->p_rlimit[RLIMIT_NOFILE].rlim_max + 1000) {
528 /*
529 * Prevent userland from causing over-allocation.
530 * Raising the default limit too high can still cause
531 * a lot of memory to be allocated, but this also means
532 * that the file descriptor array will also be large.
533 *
534 * To reduce the memory requirements here, we could
535 * process the 'fds' array in chunks, but that
536 * is a lot of code that isn't normally useful.
537 * (Or just move the copyin/out into pollscan().)
538 *
539 * Historically the code silently truncated 'fds' to
540 * dt_nfiles entries - but that does cause issues.
541 *
542 * Using the max limit equivalent to sysctl
543 * kern.maxfiles is the moral equivalent of OPEN_MAX
544 * as specified by POSIX.
545 *
546 * We add a slop of 1000 in case the resource limit was
547 * changed after opening descriptors or the same descriptor
548 * was specified more than once.
549 */
550 return EINVAL;
551 }
552 ni = nfds * sizeof(struct pollfd);
553 if (ni > sizeof(smallfds))
554 fds = kmem_alloc(ni, KM_SLEEP);
555 else
556 fds = smallfds;
557
558 error = copyin(u_fds, fds, ni);
559 if (error)
560 goto fail;
561
562 error = sel_do_scan(selop_poll, fds, nfds, ni, ts, mask, retval);
563 if (error == 0)
564 error = copyout(fds, u_fds, ni);
565 fail:
566 if (fds != smallfds)
567 kmem_free(fds, ni);
568 return (error);
569 }
570
571 static inline int
572 pollscan(struct pollfd *fds, const int nfd, register_t *retval)
573 {
574 file_t *fp;
575 int i, n = 0, revents;
576
577 for (i = 0; i < nfd; i++, fds++) {
578 fds->revents = 0;
579 if (fds->fd < 0) {
580 revents = 0;
581 } else if ((fp = fd_getfile(fds->fd)) == NULL) {
582 revents = POLLNVAL;
583 } else {
584 /*
585 * Perform poll: registers select request or returns
586 * the events which are set. Setup an argument for
587 * selrecord(), which is a pointer to struct pollfd.
588 */
589 curlwp->l_selrec = (uintptr_t)fds;
590 revents = (*fp->f_ops->fo_poll)(fp,
591 fds->events | POLLERR | POLLHUP);
592 fd_putfile(fds->fd);
593 }
594 if (revents) {
595 if (!direct_select) {
596 /* Have events: do nothing in selrecord(). */
597 curlwp->l_selflag = SEL_RESET;
598 }
599 fds->revents = revents;
600 n++;
601 }
602 }
603 *retval = n;
604 return (0);
605 }
606
607 int
608 seltrue(dev_t dev, int events, lwp_t *l)
609 {
610
611 return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
612 }
613
614 /*
615 * Record a select request. Concurrency issues:
616 *
617 * The caller holds the same lock across calls to selrecord() and
618 * selnotify(), so we don't need to consider a concurrent wakeup
619 * while in this routine.
620 *
621 * The only activity we need to guard against is selclear(), called by
622 * another thread that is exiting sel_do_scan().
623 * `sel_lwp' can only become non-NULL while the caller's lock is held,
624 * so it cannot become non-NULL due to a change made by another thread
625 * while we are in this routine. It can only become _NULL_ due to a
626 * call to selclear().
627 *
628 * If it is non-NULL and != selector there is the potential for
629 * selclear() to be called by another thread. If either of those
630 * conditions are true, we're not interested in touching the `named
631 * waiter' part of the selinfo record because we need to record a
632 * collision. Hence there is no need for additional locking in this
633 * routine.
634 */
635 void
636 selrecord(lwp_t *selector, struct selinfo *sip)
637 {
638 selcluster_t *sc;
639 lwp_t *other;
640
641 KASSERT(selector == curlwp);
642
643 sc = selector->l_selcluster;
644 other = sip->sel_lwp;
645
646 if (selector->l_selflag == SEL_RESET) {
647 /* 0. We're not going to block - will poll again if needed. */
648 } else if (other == selector) {
649 /* 1. We (selector) already claimed to be the first LWP. */
650 KASSERT(sip->sel_cluster == sc);
651 } else if (other == NULL) {
652 /*
653 * 2. No first LWP, therefore we (selector) are the first.
654 *
655 * There may be unnamed waiters (collisions). Issue a memory
656 * barrier to ensure that we access sel_lwp (above) before
657 * other fields - this guards against a call to selclear().
658 */
659 membar_acquire();
660 sip->sel_lwp = selector;
661 SLIST_INSERT_HEAD(&selector->l_selwait, sip, sel_chain);
662 /* Copy the argument, which is for selnotify(). */
663 sip->sel_fdinfo = selector->l_selrec;
664 /* Replace selinfo's lock with the chosen cluster's lock. */
665 sip->sel_cluster = sc;
666 } else {
667 /* 3. Multiple waiters: record a collision. */
668 sip->sel_collision |= sc->sc_mask;
669 KASSERT(sip->sel_cluster != NULL);
670 }
671 }
672
673 /*
674 * Record a knote.
675 *
676 * The caller holds the same lock as for selrecord().
677 */
678 void
679 selrecord_knote(struct selinfo *sip, struct knote *kn)
680 {
681 klist_insert(&sip->sel_klist, kn);
682 }
683
684 /*
685 * Remove a knote.
686 *
687 * The caller holds the same lock as for selrecord().
688 *
689 * Returns true if the last knote was removed and the list
690 * is now empty.
691 */
692 bool
693 selremove_knote(struct selinfo *sip, struct knote *kn)
694 {
695 return klist_remove(&sip->sel_klist, kn);
696 }
697
698 /*
699 * sel_setevents: a helper function for selnotify(), to set the events
700 * for LWP sleeping in selcommon() or pollcommon().
701 */
702 static inline bool
703 sel_setevents(lwp_t *l, struct selinfo *sip, const int events)
704 {
705 const int oflag = l->l_selflag;
706 int ret = 0;
707
708 /*
709 * If we require re-scan or it was required by somebody else,
710 * then just (re)set SEL_RESET and return.
711 */
712 if (__predict_false(events == 0 || oflag == SEL_RESET)) {
713 l->l_selflag = SEL_RESET;
714 return true;
715 }
716 /*
717 * Direct set. Note: select state of LWP is locked. First,
718 * determine whether it is selcommon() or pollcommon().
719 */
720 if (l->l_selbits != NULL) {
721 const size_t ni = l->l_selni;
722 fd_mask *fds = (fd_mask *)l->l_selbits;
723 fd_mask *ofds = (fd_mask *)((char *)fds + ni * 3);
724 const int fd = sip->sel_fdinfo, fbit = 1 << (fd & __NFDMASK);
725 const int idx = fd >> __NFDSHIFT;
726 int n;
727
728 for (n = 0; n < 3; n++) {
729 if ((fds[idx] & fbit) != 0 &&
730 (ofds[idx] & fbit) == 0 &&
731 (sel_flag[n] & events)) {
732 ofds[idx] |= fbit;
733 ret++;
734 }
735 fds = (fd_mask *)((char *)fds + ni);
736 ofds = (fd_mask *)((char *)ofds + ni);
737 }
738 } else {
739 struct pollfd *pfd = (void *)sip->sel_fdinfo;
740 int revents = events & (pfd->events | POLLERR | POLLHUP);
741
742 if (revents) {
743 if (pfd->revents == 0)
744 ret = 1;
745 pfd->revents |= revents;
746 }
747 }
748 /* Check whether there are any events to return. */
749 if (!ret) {
750 return false;
751 }
752 /* Indicate direct set and note the event (cluster lock is held). */
753 l->l_selflag = SEL_EVENT;
754 l->l_selret += ret;
755 return true;
756 }
757
758 /*
759 * Do a wakeup when a selectable event occurs. Concurrency issues:
760 *
761 * As per selrecord(), the caller's object lock is held. If there
762 * is a named waiter, we must acquire the associated selcluster's lock
763 * in order to synchronize with selclear() and pollers going to sleep
764 * in sel_do_scan().
765 *
766 * sip->sel_cluser cannot change at this point, as it is only changed
767 * in selrecord(), and concurrent calls to selrecord() are locked
768 * out by the caller.
769 */
770 void
771 selnotify(struct selinfo *sip, int events, long knhint)
772 {
773 selcluster_t *sc;
774 uint64_t mask;
775 int index, oflag;
776 lwp_t *l;
777 kmutex_t *lock;
778
779 KNOTE(&sip->sel_klist, knhint);
780
781 if (sip->sel_lwp != NULL) {
782 /* One named LWP is waiting. */
783 sc = sip->sel_cluster;
784 lock = sc->sc_lock;
785 mutex_spin_enter(lock);
786 /* Still there? */
787 if (sip->sel_lwp != NULL) {
788 /*
789 * Set the events for our LWP and indicate that.
790 * Otherwise, request for a full re-scan.
791 */
792 l = sip->sel_lwp;
793 oflag = l->l_selflag;
794
795 if (!direct_select) {
796 l->l_selflag = SEL_RESET;
797 } else if (!sel_setevents(l, sip, events)) {
798 /* No events to return. */
799 mutex_spin_exit(lock);
800 return;
801 }
802
803 /*
804 * If thread is sleeping, wake it up. If it's not
805 * yet asleep, it will notice the change in state
806 * and will re-poll the descriptors.
807 */
808 if (oflag == SEL_BLOCKING && l->l_mutex == lock) {
809 KASSERT(l->l_wchan == sc);
810 sleepq_unsleep(l, false);
811 }
812 }
813 mutex_spin_exit(lock);
814 }
815
816 if ((mask = sip->sel_collision) != 0) {
817 /*
818 * There was a collision (multiple waiters): we must
819 * inform all potentially interested waiters.
820 */
821 sip->sel_collision = 0;
822 do {
823 index = ffs64(mask) - 1;
824 mask ^= __BIT(index);
825 sc = selcluster[index];
826 lock = sc->sc_lock;
827 mutex_spin_enter(lock);
828 sc->sc_ncoll++;
829 sleepq_wake(&sc->sc_sleepq, sc, (u_int)-1, lock);
830 } while (__predict_false(mask != 0));
831 }
832 }
833
834 /*
835 * Remove an LWP from all objects that it is waiting for. Concurrency
836 * issues:
837 *
838 * The object owner's (e.g. device driver) lock is not held here. Calls
839 * can be made to selrecord() and we do not synchronize against those
840 * directly using locks. However, we use `sel_lwp' to lock out changes.
841 * Before clearing it we must use memory barriers to ensure that we can
842 * safely traverse the list of selinfo records.
843 */
844 static void
845 selclear(void)
846 {
847 struct selinfo *sip, *next;
848 selcluster_t *sc;
849 lwp_t *l;
850 kmutex_t *lock;
851
852 l = curlwp;
853 sc = l->l_selcluster;
854 lock = sc->sc_lock;
855
856 /*
857 * If the request was non-blocking, or we found events on the first
858 * descriptor, there will be no need to clear anything - avoid
859 * taking the lock.
860 */
861 if (SLIST_EMPTY(&l->l_selwait)) {
862 return;
863 }
864
865 mutex_spin_enter(lock);
866 for (sip = SLIST_FIRST(&l->l_selwait); sip != NULL; sip = next) {
867 KASSERT(sip->sel_lwp == l);
868 KASSERT(sip->sel_cluster == l->l_selcluster);
869
870 /*
871 * Read link to next selinfo record, if any.
872 * It's no longer safe to touch `sip' after clearing
873 * `sel_lwp', so ensure that the read of `sel_chain'
874 * completes before the clearing of sel_lwp becomes
875 * globally visible.
876 */
877 next = SLIST_NEXT(sip, sel_chain);
878 /* Release the record for another named waiter to use. */
879 atomic_store_release(&sip->sel_lwp, NULL);
880 }
881 mutex_spin_exit(lock);
882 }
883
884 /*
885 * Initialize the select/poll system calls. Called once for each
886 * CPU in the system, as they are attached.
887 */
888 void
889 selsysinit(struct cpu_info *ci)
890 {
891 selcluster_t *sc;
892 u_int index;
893
894 /* If already a cluster in place for this bit, re-use. */
895 index = cpu_index(ci) & SELCLUSTERMASK;
896 sc = selcluster[index];
897 if (sc == NULL) {
898 sc = kmem_alloc(roundup2(sizeof(selcluster_t),
899 coherency_unit) + coherency_unit, KM_SLEEP);
900 sc = (void *)roundup2((uintptr_t)sc, coherency_unit);
901 sc->sc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
902 sleepq_init(&sc->sc_sleepq);
903 sc->sc_ncoll = 0;
904 sc->sc_mask = __BIT(index);
905 selcluster[index] = sc;
906 }
907 ci->ci_data.cpu_selcluster = sc;
908 }
909
910 /*
911 * Initialize a selinfo record.
912 */
913 void
914 selinit(struct selinfo *sip)
915 {
916
917 memset(sip, 0, sizeof(*sip));
918 klist_init(&sip->sel_klist);
919 }
920
921 /*
922 * Destroy a selinfo record. The owning object must not gain new
923 * references while this is in progress: all activity on the record
924 * must be stopped.
925 *
926 * Concurrency issues: we only need guard against a call to selclear()
927 * by a thread exiting sel_do_scan(). The caller has prevented further
928 * references being made to the selinfo record via selrecord(), and it
929 * will not call selnotify() again.
930 */
931 void
932 seldestroy(struct selinfo *sip)
933 {
934 selcluster_t *sc;
935 kmutex_t *lock;
936 lwp_t *l;
937
938 klist_fini(&sip->sel_klist);
939
940 if (sip->sel_lwp == NULL)
941 return;
942
943 /*
944 * Lock out selclear(). The selcluster pointer can't change while
945 * we are here since it is only ever changed in selrecord(),
946 * and that will not be entered again for this record because
947 * it is dying.
948 */
949 KASSERT(sip->sel_cluster != NULL);
950 sc = sip->sel_cluster;
951 lock = sc->sc_lock;
952 mutex_spin_enter(lock);
953 if ((l = sip->sel_lwp) != NULL) {
954 /*
955 * This should rarely happen, so although SLIST_REMOVE()
956 * is slow, using it here is not a problem.
957 */
958 KASSERT(l->l_selcluster == sc);
959 SLIST_REMOVE(&l->l_selwait, sip, selinfo, sel_chain);
960 sip->sel_lwp = NULL;
961 }
962 mutex_spin_exit(lock);
963 }
964
965 /*
966 * System control nodes.
967 */
968 SYSCTL_SETUP(sysctl_select_setup, "sysctl select setup")
969 {
970
971 sysctl_createv(clog, 0, NULL, NULL,
972 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
973 CTLTYPE_INT, "direct_select",
974 SYSCTL_DESCR("Enable/disable direct select (for testing)"),
975 NULL, 0, &direct_select, 0,
976 CTL_KERN, CTL_CREATE, CTL_EOL);
977 }
978