forked from mailru/easygo
/
epoll.go
303 lines (254 loc) · 6.38 KB
/
epoll.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// +build linux
package netpoll
import (
"fmt"
"sync"
"time"
"golang.org/x/sys/unix"
)
// EpollEvent represents epoll events configuration bit mask.
type EpollEvent uint32
// EpollEvents that are mapped to epoll_event.events possible values.
const (
EPOLLIN = unix.EPOLLIN
EPOLLOUT = unix.EPOLLOUT
EPOLLRDHUP = unix.EPOLLRDHUP
EPOLLPRI = unix.EPOLLPRI
EPOLLERR = unix.EPOLLERR
EPOLLHUP = unix.EPOLLHUP
EPOLLET = unix.EPOLLET
EPOLLONESHOT = unix.EPOLLONESHOT
// _EPOLLCLOSED is a special EpollEvent value the receipt of which means
// that the epoll instance is closed.
_EPOLLCLOSED = 0x20
)
// String returns a string representation of EpollEvent.
func (evt EpollEvent) String() (str string) {
name := func(event EpollEvent, name string) {
if evt&event == 0 {
return
}
if str != "" {
str += "|"
}
str += name
}
name(EPOLLIN, "EPOLLIN")
name(EPOLLOUT, "EPOLLOUT")
name(EPOLLRDHUP, "EPOLLRDHUP")
name(EPOLLPRI, "EPOLLPRI")
name(EPOLLERR, "EPOLLERR")
name(EPOLLHUP, "EPOLLHUP")
name(EPOLLET, "EPOLLET")
name(EPOLLONESHOT, "EPOLLONESHOT")
name(_EPOLLCLOSED, "_EPOLLCLOSED")
return
}
// Epoll represents single epoll instance.
type Epoll struct {
mu sync.RWMutex
fd int
eventFd int
closed bool
waitDone chan struct{}
callbacks map[int]func(EpollEvent)
grp *Grpoolx
tkp *Taskpool
}
// EpollConfig contains options for Epoll instance configuration.
type EpollConfig struct {
// OnWaitError will be called from goroutine, waiting for events.
OnWaitError func(error)
}
func (c *EpollConfig) withDefaults() (config EpollConfig) {
if c != nil {
config = *c
}
if config.OnWaitError == nil {
config.OnWaitError = defaultOnWaitError
}
return config
}
// EpollCreate creates new epoll instance.
// It starts the wait loop in separate goroutine.
func EpollCreate(c *EpollConfig) (*Epoll, error) {
config := c.withDefaults()
fd, err := unix.EpollCreate1(0)
if err != nil {
return nil, err
}
r0, _, errno := unix.Syscall(unix.SYS_EVENTFD2, 0, 0, 0)
if errno != 0 {
return nil, errno
}
eventFd := int(r0)
// Set finalizer for write end of socket pair to avoid data races when
// closing Epoll instance and EBADF errors on writing ctl bytes from callers.
err = unix.EpollCtl(fd, unix.EPOLL_CTL_ADD, eventFd, &unix.EpollEvent{
Events: unix.EPOLLIN,
Fd: int32(eventFd),
})
if err != nil {
unix.Close(fd)
unix.Close(eventFd)
return nil, err
}
ep := &Epoll{
fd: fd,
eventFd: eventFd,
callbacks: make(map[int]func(EpollEvent)),
waitDone: make(chan struct{}),
}
// Run wait loop.
go ep.wait(config.OnWaitError)
return ep, nil
}
// closeBytes used for writing to eventfd.
var closeBytes = []byte{1, 0, 0, 0, 0, 0, 0, 0}
// Close stops wait loop and closes all underlying resources.
func (ep *Epoll) Close() (err error) {
ep.mu.Lock()
{
if ep.closed {
ep.mu.Unlock()
return ErrClosed
}
ep.closed = true
if _, err = unix.Write(ep.eventFd, closeBytes); err != nil {
ep.mu.Unlock()
return
}
}
ep.mu.Unlock()
<-ep.waitDone
if err = unix.Close(ep.eventFd); err != nil {
return
}
ep.mu.Lock()
// Set callbacks to nil preventing long mu.Lock() hold.
// This could increase the speed of retreiving ErrClosed in other calls to
// current epoll instance.
// Setting callbacks to nil is safe here because no one should read after
// closed flag is true.
callbacks := ep.callbacks
ep.callbacks = nil
ep.mu.Unlock()
for _, cb := range callbacks {
if cb != nil {
cb(_EPOLLCLOSED)
}
}
return
}
// Add adds fd to epoll set with given events.
// Callback will be called on each received event from epoll.
// Note that _EPOLLCLOSED is triggered for every cb when epoll closed.
func (ep *Epoll) Add(fd int, events EpollEvent, cb func(EpollEvent)) (err error) {
ev := &unix.EpollEvent{
Events: uint32(events),
Fd: int32(fd),
}
ep.mu.Lock()
defer ep.mu.Unlock()
if ep.closed {
return ErrClosed
}
if _, has := ep.callbacks[fd]; has {
return ErrRegistered
}
ep.callbacks[fd] = cb
return unix.EpollCtl(ep.fd, unix.EPOLL_CTL_ADD, fd, ev)
}
// Del removes fd from epoll set.
func (ep *Epoll) Del(fd int) (err error) {
ep.mu.Lock()
defer ep.mu.Unlock()
if ep.closed {
return ErrClosed
}
if _, ok := ep.callbacks[fd]; !ok {
return ErrNotRegistered
}
delete(ep.callbacks, fd)
return unix.EpollCtl(ep.fd, unix.EPOLL_CTL_DEL, fd, nil)
}
// Mod sets to listen events on fd.
func (ep *Epoll) Mod(fd int, events EpollEvent) (err error) {
ev := &unix.EpollEvent{
Events: uint32(events),
Fd: int32(fd),
}
ep.mu.RLock()
defer ep.mu.RUnlock()
if ep.closed {
return ErrClosed
}
if _, ok := ep.callbacks[fd]; !ok {
return ErrNotRegistered
}
return unix.EpollCtl(ep.fd, unix.EPOLL_CTL_MOD, fd, ev)
}
const (
maxWaitEventsBegin = 1024
maxWaitEventsStop = 32768
)
func (ep *Epoll) wait(onError func(error)) {
defer func() {
if err := unix.Close(ep.fd); err != nil {
onError(err)
}
close(ep.waitDone)
}()
var loop int64 = 0
var tstart time.Time
var twait int64 //ms
events := make([]unix.EpollEvent, maxWaitEventsBegin)
//callbacks := make([]func(EpollEvent), 0, maxWaitEventsBegin)
for ; ; loop = loop + 1 {
tstart = time.Now()
n, err := unix.EpollWait(ep.fd, events, -1)
if err != nil {
if temporaryErr(err) {
continue
}
onError(err)
return
}
twait = time.Since(tstart).Milliseconds()
tstart = time.Now()
//callbacks = callbacks[:n]
ep.mu.RLock()
for i := 0; i < n; i++ {
fd := int(events[i].Fd)
if fd == ep.eventFd { // signal to close
ep.mu.RUnlock()
return
}
//callbacks[i] = ep.callbacks[fd]
if ep.grp == nil {
go ep.callbacks[fd](EpollEvent(events[i].Events))
} else {
task := ep.tkp.Get(ep.callbacks[fd], EpollEvent(events[i].Events))
if err = ep.grp.ScheduleTimeout(10*time.Millisecond, task); err != nil {
fmt.Println("call ep.grp.ScheduleTimeout() time out in Epoll wait()", err)
}
}
}
ep.mu.RUnlock()
if loop%20 == 0 {
fmt.Printf("%s\t,loop=%d\t,count=%d\t,EpollWait(ms)=%d\t,callback(ms)=%d\n", tstart, loop, n, twait, time.Since(tstart).Milliseconds())
}
/*
for i := 0; i < n; i++ {
if cb := callbacks[i]; cb != nil {
cb(EpollEvent(events[i].Events))
callbacks[i] = nil
}
}
*/
if n == len(events) && n*2 <= maxWaitEventsStop {
events = make([]unix.EpollEvent, n*2)
//callbacks = make([]func(EpollEvent), 0, n*2)
}
}
}