1
// Copyright 2009 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
5
// Waiting for FDs via epoll(7).
15
readFlags = syscall.EPOLLIN | syscall.EPOLLRDHUP
16
writeFlags = syscall.EPOLLOUT
19
type pollster struct {
22
// Events we're already waiting for
26
func newpollster() (p *pollster, err os.Error) {
30
// The arg to epoll_create is a hint to the kernel
31
// about the number of FDs we will care about.
33
if p.epfd, e = syscall.EpollCreate(16); e != 0 {
34
return nil, os.NewSyscallError("epoll_create", e)
36
p.events = make(map[int]uint32)
40
func (p *pollster) AddFD(fd int, mode int, repeat bool) os.Error {
41
var ev syscall.EpollEvent
44
ev.Events, already = p.events[fd]
46
ev.Events |= syscall.EPOLLONESHOT
49
ev.Events |= readFlags
51
ev.Events |= writeFlags
56
op = syscall.EPOLL_CTL_MOD
58
op = syscall.EPOLL_CTL_ADD
60
if e := syscall.EpollCtl(p.epfd, op, fd, &ev); e != 0 {
61
return os.NewSyscallError("epoll_ctl", e)
63
p.events[fd] = ev.Events
67
func (p *pollster) StopWaiting(fd int, bits uint) {
68
events, already := p.events[fd]
70
print("Epoll unexpected fd=", fd, "\n")
74
// If syscall.EPOLLONESHOT is not set, the wait
75
// is a repeating wait, so don't change it.
76
if events&syscall.EPOLLONESHOT == 0 {
80
// Disable the given bits.
81
// If we're still waiting for other events, modify the fd
82
// event in the kernel. Otherwise, delete it.
83
events &= ^uint32(bits)
84
if int32(events)&^syscall.EPOLLONESHOT != 0 {
85
var ev syscall.EpollEvent
88
if e := syscall.EpollCtl(p.epfd, syscall.EPOLL_CTL_MOD, fd, &ev); e != 0 {
89
print("Epoll modify fd=", fd, ": ", os.Errno(e).String(), "\n")
93
if e := syscall.EpollCtl(p.epfd, syscall.EPOLL_CTL_DEL, fd, nil); e != 0 {
94
print("Epoll delete fd=", fd, ": ", os.Errno(e).String(), "\n")
96
p.events[fd] = 0, false
100
func (p *pollster) DelFD(fd int, mode int) {
102
p.StopWaiting(fd, readFlags)
104
p.StopWaiting(fd, writeFlags)
108
func (p *pollster) WaitFD(nsec int64) (fd int, mode int, err os.Error) {
110
var evarray [1]syscall.EpollEvent
114
msec = int((nsec + 1e6 - 1) / 1e6)
116
n, e := syscall.EpollWait(p.epfd, evarray[0:], msec)
117
for e == syscall.EAGAIN || e == syscall.EINTR {
118
n, e = syscall.EpollWait(p.epfd, evarray[0:], msec)
121
return -1, 0, os.NewSyscallError("epoll_wait", e)
128
if ev.Events&writeFlags != 0 {
129
p.StopWaiting(fd, writeFlags)
132
if ev.Events&readFlags != 0 {
133
p.StopWaiting(fd, readFlags)
137
// Other events are error conditions - wake whoever is waiting.
138
events, _ := p.events[fd]
139
if events&writeFlags != 0 {
140
p.StopWaiting(fd, writeFlags)
143
p.StopWaiting(fd, readFlags)
147
func (p *pollster) Close() os.Error {
148
return os.NewSyscallError("close", syscall.Close(p.epfd))