1 /* $NetBSD: sys_select.c,v 1.20 2009/12/12 17:47:05 dsl Exp $ */
4 * Copyright (c) 2007, 2008, 2009 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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.
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.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
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.
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
65 * @(#)sys_generic.c 8.9 (Berkeley) 2/14/95
69 * System calls of synchronous I/O multiplexing subsystem.
73 * Two locks are used: <object-lock> and selcpu_t::sc_lock.
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.
86 #include <sys/cdefs.h>
87 __KERNEL_RCSID(0, "$NetBSD: sys_select.c,v 1.20 2009/12/12 17:47:05 dsl Exp $");
89 #include <sys/param.h>
90 #include <sys/systm.h>
91 #include <sys/filedesc.h>
92 #include <sys/ioctl.h>
95 #include <sys/socketvar.h>
96 #include <sys/signalvar.h>
98 #include <sys/kernel.h>
100 #include <sys/poll.h>
101 #include <sys/vnode.h>
102 #include <sys/mount.h>
103 #include <sys/syscallargs.h>
105 #include <sys/atomic.h>
106 #include <sys/socketvar.h>
107 #include <sys/sleepq.h>
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 /* about to block on select_cv */
114 /* Per-CPU state for select()/poll(). */
116 #error adjust this code
118 typedef struct selcpu
{
125 static inline int selscan(char *, u_int
, register_t
*);
126 static inline int pollscan(struct pollfd
*, u_int
, register_t
*);
127 static void selclear(void);
129 static syncobj_t select_sobj
= {
138 * Select system call.
141 sys___pselect50(struct lwp
*l
, const struct sys___pselect50_args
*uap
,
146 syscallarg(fd_set *) in;
147 syscallarg(fd_set *) ou;
148 syscallarg(fd_set *) ex;
149 syscallarg(const struct timespec *) ts;
150 syscallarg(sigset_t *) mask;
152 struct timespec ats
, *ts
= NULL
;
153 sigset_t amask
, *mask
= NULL
;
156 if (SCARG(uap
, ts
)) {
157 error
= copyin(SCARG(uap
, ts
), &ats
, sizeof(ats
));
162 if (SCARG(uap
, mask
) != NULL
) {
163 error
= copyin(SCARG(uap
, mask
), &amask
, sizeof(amask
));
169 return selcommon(retval
, SCARG(uap
, nd
), SCARG(uap
, in
),
170 SCARG(uap
, ou
), SCARG(uap
, ex
), ts
, mask
);
174 sys___select50(struct lwp
*l
, const struct sys___select50_args
*uap
,
179 syscallarg(fd_set *) in;
180 syscallarg(fd_set *) ou;
181 syscallarg(fd_set *) ex;
182 syscallarg(struct timeval *) tv;
185 struct timespec ats
, *ts
= NULL
;
188 if (SCARG(uap
, tv
)) {
189 error
= copyin(SCARG(uap
, tv
), (void *)&atv
, sizeof(atv
));
192 TIMEVAL_TO_TIMESPEC(&atv
, &ats
);
196 return selcommon(retval
, SCARG(uap
, nd
), SCARG(uap
, in
),
197 SCARG(uap
, ou
), SCARG(uap
, ex
), ts
, NULL
);
201 * sel_do_scan: common code to perform the scan on descriptors.
204 sel_do_scan(void *fds
, u_int nfds
, struct timespec
*ts
, sigset_t
*mask
,
205 register_t
*retval
, int selpoll
)
207 lwp_t
* const l
= curlwp
;
208 proc_t
* const p
= l
->l_proc
;
212 struct timespec sleepts
;
216 if (ts
&& inittimeleft(ts
, &sleepts
) == -1) {
220 if (__predict_false(mask
)) {
221 sigminusset(&sigcantmask
, mask
);
222 mutex_enter(p
->p_lock
);
223 oldmask
= l
->l_sigmask
;
224 l
->l_sigmask
= *mask
;
225 mutex_exit(p
->p_lock
);
228 oldmask
= l
->l_sigmask
;
231 sc
= curcpu()->ci_data
.cpu_selcpu
;
234 SLIST_INIT(&l
->l_selwait
);
239 * No need to lock. If this is overwritten by another value
240 * while scanning, we will retry below. We only need to see
241 * exact state from the descriptors that we are about to poll,
242 * and lock activity resulting from fo_poll is enough to
243 * provide an up to date value for new polling activity.
245 l
->l_selflag
= SEL_SCANNING
;
246 ncoll
= sc
->sc_ncoll
;
249 error
= selscan((char *)fds
, nfds
, retval
);
251 error
= pollscan((struct pollfd
*)fds
, nfds
, retval
);
254 if (error
|| *retval
)
256 if (ts
&& (timo
= gettimeleft(ts
, &sleepts
)) <= 0)
258 mutex_spin_enter(lock
);
259 if (l
->l_selflag
!= SEL_SCANNING
|| sc
->sc_ncoll
!= ncoll
) {
260 mutex_spin_exit(lock
);
263 l
->l_selflag
= SEL_BLOCKING
;
264 l
->l_kpriority
= true;
265 sleepq_enter(&sc
->sc_sleepq
, l
, lock
);
266 sleepq_enqueue(&sc
->sc_sleepq
, sc
, "select", &select_sobj
);
267 error
= sleepq_block(timo
, true);
273 if (__predict_false(mask
)) {
274 mutex_enter(p
->p_lock
);
275 l
->l_sigmask
= oldmask
;
276 mutex_exit(p
->p_lock
);
279 /* select and poll are not restarted after signals... */
280 if (error
== ERESTART
)
282 if (error
== EWOULDBLOCK
)
288 selcommon(register_t
*retval
, int nd
, fd_set
*u_in
, fd_set
*u_ou
,
289 fd_set
*u_ex
, struct timespec
*ts
, sigset_t
*mask
)
291 char smallbits
[howmany(FD_SETSIZE
, NFDBITS
) *
292 sizeof(fd_mask
) * 6];
299 nf
= curlwp
->l_fd
->fd_dt
->dt_nfiles
;
301 /* forgiving; slightly wrong */
304 ni
= howmany(nd
, NFDBITS
) * sizeof(fd_mask
);
305 if (ni
* 6 > sizeof(smallbits
)) {
306 bits
= kmem_alloc(ni
* 6, KM_SLEEP
);
312 #define getbits(name, x) \
314 error = copyin(u_ ## name, bits + ni * x, ni); \
318 memset(bits + ni * x, 0, ni);
324 error
= sel_do_scan(bits
, nd
, ts
, mask
, retval
, 1);
325 if (error
== 0 && u_in
!= NULL
)
326 error
= copyout(bits
+ ni
* 3, u_in
, ni
);
327 if (error
== 0 && u_ou
!= NULL
)
328 error
= copyout(bits
+ ni
* 4, u_ou
, ni
);
329 if (error
== 0 && u_ex
!= NULL
)
330 error
= copyout(bits
+ ni
* 5, u_ex
, ni
);
332 if (bits
!= smallbits
)
333 kmem_free(bits
, ni
* 6);
338 selscan(char *bits
, u_int nfd
, register_t
*retval
)
340 static const int flag
[3] = { POLLRDNORM
| POLLHUP
| POLLERR
,
341 POLLWRNORM
| POLLHUP
| POLLERR
,
343 fd_mask
*ibitp
, *obitp
;
344 int msk
, i
, j
, fd
, ni
, n
;
345 fd_mask ibits
, obits
;
348 ni
= howmany(nfd
, NFDBITS
) * sizeof(fd_mask
);
349 ibitp
= (fd_mask
*)(bits
+ ni
* 0);
350 obitp
= (fd_mask
*)(bits
+ ni
* 3);
353 for (msk
= 0; msk
< 3; msk
++) {
354 for (i
= 0; i
< nfd
; i
+= NFDBITS
) {
357 while ((j
= ffs(ibits
)) && (fd
= i
+ --j
) < nfd
) {
359 if ((fp
= fd_getfile(fd
)) == NULL
)
361 if ((*fp
->f_ops
->fo_poll
)(fp
, flag
[msk
])) {
378 sys_poll(struct lwp
*l
, const struct sys_poll_args
*uap
, register_t
*retval
)
381 syscallarg(struct pollfd *) fds;
382 syscallarg(u_int) nfds;
383 syscallarg(int) timeout;
385 struct timespec ats
, *ts
= NULL
;
387 if (SCARG(uap
, timeout
) != INFTIM
) {
388 ats
.tv_sec
= SCARG(uap
, timeout
) / 1000;
389 ats
.tv_nsec
= (SCARG(uap
, timeout
) % 1000) * 1000000;
393 return pollcommon(retval
, SCARG(uap
, fds
), SCARG(uap
, nfds
), ts
, NULL
);
400 sys___pollts50(struct lwp
*l
, const struct sys___pollts50_args
*uap
,
404 syscallarg(struct pollfd *) fds;
405 syscallarg(u_int) nfds;
406 syscallarg(const struct timespec *) ts;
407 syscallarg(const sigset_t *) mask;
409 struct timespec ats
, *ts
= NULL
;
410 sigset_t amask
, *mask
= NULL
;
413 if (SCARG(uap
, ts
)) {
414 error
= copyin(SCARG(uap
, ts
), &ats
, sizeof(ats
));
419 if (SCARG(uap
, mask
)) {
420 error
= copyin(SCARG(uap
, mask
), &amask
, sizeof(amask
));
426 return pollcommon(retval
, SCARG(uap
, fds
), SCARG(uap
, nfds
), ts
, mask
);
430 pollcommon(register_t
*retval
, struct pollfd
*u_fds
, u_int nfds
,
431 struct timespec
*ts
, sigset_t
*mask
)
433 struct pollfd smallfds
[32];
438 if (nfds
> 1000 + curlwp
->l_fd
->fd_dt
->dt_nfiles
) {
440 * Either the user passed in a very sparse 'fds' or junk!
441 * The kmem_alloc() call below would be bad news.
442 * We could process the 'fds' array in chunks, but that
443 * is a lot of code that isn't normally useful.
444 * (Or just move the copyin/out into pollscan().)
445 * Historically the code silently truncated 'fds' to
446 * dt_nfiles entries - but that does cause issues.
450 ni
= nfds
* sizeof(struct pollfd
);
451 if (ni
> sizeof(smallfds
)) {
452 fds
= kmem_alloc(ni
, KM_SLEEP
);
458 error
= copyin(u_fds
, fds
, ni
);
462 error
= sel_do_scan(fds
, nfds
, ts
, mask
, retval
, 0);
464 error
= copyout(fds
, u_fds
, ni
);
472 pollscan(struct pollfd
*fds
, u_int nfd
, register_t
*retval
)
478 for (i
= 0; i
< nfd
; i
++, fds
++) {
481 } else if ((fp
= fd_getfile(fds
->fd
)) == NULL
) {
482 fds
->revents
= POLLNVAL
;
485 fds
->revents
= (*fp
->f_ops
->fo_poll
)(fp
,
486 fds
->events
| POLLERR
| POLLHUP
);
487 if (fds
->revents
!= 0)
498 seltrue(dev_t dev
, int events
, lwp_t
*l
)
501 return (events
& (POLLIN
| POLLOUT
| POLLRDNORM
| POLLWRNORM
));
505 * Record a select request. Concurrency issues:
507 * The caller holds the same lock across calls to selrecord() and
508 * selnotify(), so we don't need to consider a concurrent wakeup
509 * while in this routine.
511 * The only activity we need to guard against is selclear(), called by
512 * another thread that is exiting sel_do_scan().
513 * `sel_lwp' can only become non-NULL while the caller's lock is held,
514 * so it cannot become non-NULL due to a change made by another thread
515 * while we are in this routine. It can only become _NULL_ due to a
516 * call to selclear().
518 * If it is non-NULL and != selector there is the potential for
519 * selclear() to be called by another thread. If either of those
520 * conditions are true, we're not interested in touching the `named
521 * waiter' part of the selinfo record because we need to record a
522 * collision. Hence there is no need for additional locking in this
526 selrecord(lwp_t
*selector
, struct selinfo
*sip
)
531 KASSERT(selector
== curlwp
);
533 sc
= selector
->l_selcpu
;
534 other
= sip
->sel_lwp
;
536 if (other
== selector
) {
537 /* `selector' has already claimed it. */
538 KASSERT(sip
->sel_cpu
= sc
);
539 } else if (other
== NULL
) {
541 * First named waiter, although there may be unnamed
542 * waiters (collisions). Issue a memory barrier to
543 * ensure that we access sel_lwp (above) before other
544 * fields - this guards against a call to selclear().
547 sip
->sel_lwp
= selector
;
548 SLIST_INSERT_HEAD(&selector
->l_selwait
, sip
, sel_chain
);
549 /* Replace selinfo's lock with our chosen CPU's lock. */
552 /* Multiple waiters: record a collision. */
553 sip
->sel_collision
|= sc
->sc_mask
;
554 KASSERT(sip
->sel_cpu
!= NULL
);
559 * Do a wakeup when a selectable event occurs. Concurrency issues:
561 * As per selrecord(), the caller's object lock is held. If there
562 * is a named waiter, we must acquire the associated selcpu's lock
563 * in order to synchronize with selclear() and pollers going to sleep
566 * sip->sel_cpu cannot change at this point, as it is only changed
567 * in selrecord(), and concurrent calls to selrecord() are locked
571 selnotify(struct selinfo
*sip
, int events
, long knhint
)
579 KNOTE(&sip
->sel_klist
, knhint
);
581 if (sip
->sel_lwp
!= NULL
) {
582 /* One named LWP is waiting. */
585 mutex_spin_enter(lock
);
587 if (sip
->sel_lwp
!= NULL
) {
590 * If thread is sleeping, wake it up. If it's not
591 * yet asleep, it will notice the change in state
592 * and will re-poll the descriptors.
594 oflag
= l
->l_selflag
;
595 l
->l_selflag
= SEL_RESET
;
596 if (oflag
== SEL_BLOCKING
&& l
->l_mutex
== lock
) {
597 KASSERT(l
->l_wchan
== sc
);
598 sleepq_unsleep(l
, false);
601 mutex_spin_exit(lock
);
604 if ((mask
= sip
->sel_collision
) != 0) {
606 * There was a collision (multiple waiters): we must
607 * inform all potentially interested waiters.
609 sip
->sel_collision
= 0;
611 index
= ffs(mask
) - 1;
612 mask
&= ~(1 << index
);
613 sc
= cpu_lookup(index
)->ci_data
.cpu_selcpu
;
615 mutex_spin_enter(lock
);
617 sleepq_wake(&sc
->sc_sleepq
, sc
, (u_int
)-1, lock
);
618 } while (__predict_false(mask
!= 0));
623 * Remove an LWP from all objects that it is waiting for. Concurrency
626 * The object owner's (e.g. device driver) lock is not held here. Calls
627 * can be made to selrecord() and we do not synchronize against those
628 * directly using locks. However, we use `sel_lwp' to lock out changes.
629 * Before clearing it we must use memory barriers to ensure that we can
630 * safely traverse the list of selinfo records.
635 struct selinfo
*sip
, *next
;
644 mutex_spin_enter(lock
);
645 for (sip
= SLIST_FIRST(&l
->l_selwait
); sip
!= NULL
; sip
= next
) {
646 KASSERT(sip
->sel_lwp
== l
);
647 KASSERT(sip
->sel_cpu
== l
->l_selcpu
);
649 * Read link to next selinfo record, if any.
650 * It's no longer safe to touch `sip' after clearing
651 * `sel_lwp', so ensure that the read of `sel_chain'
652 * completes before the clearing of sel_lwp becomes
655 next
= SLIST_NEXT(sip
, sel_chain
);
657 /* Release the record for another named waiter to use. */
660 mutex_spin_exit(lock
);
664 * Initialize the select/poll system calls. Called once for each
665 * CPU in the system, as they are attached.
668 selsysinit(struct cpu_info
*ci
)
672 sc
= kmem_alloc(roundup2(sizeof(selcpu_t
), coherency_unit
) +
673 coherency_unit
, KM_SLEEP
);
674 sc
= (void *)roundup2((uintptr_t)sc
, coherency_unit
);
675 sc
->sc_lock
= mutex_obj_alloc(MUTEX_DEFAULT
, IPL_SCHED
);
676 sleepq_init(&sc
->sc_sleepq
);
678 sc
->sc_mask
= (1 << cpu_index(ci
));
679 ci
->ci_data
.cpu_selcpu
= sc
;
683 * Initialize a selinfo record.
686 selinit(struct selinfo
*sip
)
689 memset(sip
, 0, sizeof(*sip
));
693 * Destroy a selinfo record. The owning object must not gain new
694 * references while this is in progress: all activity on the record
697 * Concurrency issues: we only need guard against a call to selclear()
698 * by a thread exiting sel_do_scan(). The caller has prevented further
699 * references being made to the selinfo record via selrecord(), and it
700 * won't call selwakeup() again.
703 seldestroy(struct selinfo
*sip
)
709 if (sip
->sel_lwp
== NULL
)
713 * Lock out selclear(). The selcpu pointer can't change while
714 * we are here since it is only ever changed in selrecord(),
715 * and that will not be entered again for this record because
718 KASSERT(sip
->sel_cpu
!= NULL
);
721 mutex_spin_enter(lock
);
722 if ((l
= sip
->sel_lwp
) != NULL
) {
724 * This should rarely happen, so although SLIST_REMOVE()
725 * is slow, using it here is not a problem.
727 KASSERT(l
->l_selcpu
== sc
);
728 SLIST_REMOVE(&l
->l_selwait
, sip
, selinfo
, sel_chain
);
731 mutex_spin_exit(lock
);
735 pollsock(struct socket
*so
, const struct timespec
*tsp
, int events
)
737 int ncoll
, error
, timo
;
738 struct timespec sleepts
, ts
;
746 if (inittimeleft(&ts
, &sleepts
) == -1)
751 sc
= l
->l_cpu
->ci_data
.cpu_selcpu
;
754 SLIST_INIT(&l
->l_selwait
);
758 * No need to lock. If this is overwritten by another
759 * value while scanning, we will retry below. We only
760 * need to see exact state from the descriptors that
761 * we are about to poll, and lock activity resulting
762 * from fo_poll is enough to provide an up to date value
763 * for new polling activity.
765 ncoll
= sc
->sc_ncoll
;
766 l
->l_selflag
= SEL_SCANNING
;
767 if (sopoll(so
, events
) != 0)
769 if (tsp
&& (timo
= gettimeleft(&ts
, &sleepts
)) <= 0)
771 mutex_spin_enter(lock
);
772 if (l
->l_selflag
!= SEL_SCANNING
|| sc
->sc_ncoll
!= ncoll
) {
773 mutex_spin_exit(lock
);
776 l
->l_selflag
= SEL_BLOCKING
;
777 sleepq_enter(&sc
->sc_sleepq
, l
, lock
);
778 sleepq_enqueue(&sc
->sc_sleepq
, sc
, "pollsock", &select_sobj
);
779 error
= sleepq_block(timo
, true);
784 /* poll is not restarted after signals... */
785 if (error
== ERESTART
)
787 if (error
== EWOULDBLOCK
)