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