Debian Codegraph @

internal/epoll/poller.go

raw symbols SCIP
1 //go:build !windows
2
3 package epoll
4
5 import (
6 "errors"
7 "fmt"
8 "math"
9 "os"
10 "runtime"
11 "slices"
12 "sync"
13 "time"
14
15 "github.com/cilium/ebpf/internal"
16 "github.com/cilium/ebpf/internal/unix"
17 )
18
19 var (
20 ErrFlushed = errors.New("data was flushed")
21 errEpollWaitDeadlineExceeded = fmt.Errorf("epoll wait: %w", os.ErrDeadlineExceeded)
22 errEpollWaitClosed = fmt.Errorf("epoll wait: %w", os.ErrClosed)
23 )
24
25 // Poller waits for readiness notifications from multiple file descriptors.
26 //
27 // The wait can be interrupted by calling Close.
28 type Poller struct {
29 // mutexes protect the fields declared below them. If you need to
30 // acquire both at once you must lock epollMu before eventMu.
31 epollMu sync.Mutex
32 epollFd int
33
34 eventMu sync.Mutex
35 closeEvent *eventFd
36 flushEvent *eventFd
37 cleanup runtime.Cleanup
38 }
39
40 func New() (_ *Poller, err error) {
41 closeFDOnError := func(fd int) {
42 if err != nil {
43 unix.Close(fd)
44 }
45 }
46 closeEventFDOnError := func(e *eventFd) {
47 if err != nil {
48 e.close()
49 }
50 }
51
52 epollFd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC)
53 if err != nil {
54 return nil, fmt.Errorf("create epoll fd: %w", err)
55 }
56 defer closeFDOnError(epollFd)
57
58 p := &Poller{epollFd: epollFd}
59 p.closeEvent, err = newEventFd()
60 if err != nil {
61 return nil, err
62 }
63 defer closeEventFDOnError(p.closeEvent)
64
65 p.flushEvent, err = newEventFd()
66 if err != nil {
67 return nil, err
68 }
69 defer closeEventFDOnError(p.flushEvent)
70
71 if err := p.Add(p.closeEvent.raw, 0); err != nil {
72 return nil, fmt.Errorf("add close eventfd: %w", err)
73 }
74
75 if err := p.Add(p.flushEvent.raw, 0); err != nil {
76 return nil, fmt.Errorf("add flush eventfd: %w", err)
77 }
78
79 p.cleanup = runtime.AddCleanup(p, func(raw int) {
80 _ = unix.Close(raw)
81 }, p.epollFd)
82
83 return p, nil
84 }
85
86 // Close the poller.
87 //
88 // Interrupts any calls to Wait. Multiple calls to Close are valid, but subsequent
89 // calls will return os.ErrClosed.
90 func (p *Poller) Close() error {
91 p.cleanup.Stop()
92
93 // Interrupt Wait() via the closeEvent fd if it's currently blocked.
94 if err := p.wakeWaitForClose(); err != nil {
95 return err
96 }
97
98 // Acquire the lock. This ensures that Wait isn't running.
99 p.epollMu.Lock()
100 defer p.epollMu.Unlock()
101
102 // Prevent other calls to Close().
103 p.eventMu.Lock()
104 defer p.eventMu.Unlock()
105
106 if p.epollFd != -1 {
107 unix.Close(p.epollFd)
108 p.epollFd = -1
109 }
110
111 if p.closeEvent != nil {
112 p.closeEvent.close()
113 p.closeEvent = nil
114 }
115
116 if p.flushEvent != nil {
117 p.flushEvent.close()
118 p.flushEvent = nil
119 }
120
121 return nil
122 }
123
124 // Add an fd to the poller.
125 //
126 // id is returned by Wait in the unix.EpollEvent.Pad field any may be zero. It
127 // must not exceed math.MaxInt32.
128 //
129 // Add is blocked by Wait.
130 func (p *Poller) Add(fd int, id int) error {
131 if int64(id) > math.MaxInt32 {
132 return fmt.Errorf("unsupported id: %d", id)
133 }
134
135 p.epollMu.Lock()
136 defer p.epollMu.Unlock()
137
138 if p.epollFd == -1 {
139 return fmt.Errorf("epoll add: %w", os.ErrClosed)
140 }
141
142 // The representation of EpollEvent isn't entirely accurate.
143 // Pad is fully usable, not just padding. Hence we stuff the
144 // id in there, which allows us to identify the event later (e.g.,
145 // in case of perf events, which CPU sent it).
146 event := unix.EpollEvent{
147 Events: unix.EPOLLIN,
148 Fd: int32(fd),
149 Pad: int32(id),
150 }
151
152 if err := unix.EpollCtl(p.epollFd, unix.EPOLL_CTL_ADD, fd, &event); err != nil {
153 return fmt.Errorf("add fd to epoll: %v", err)
154 }
155
156 return nil
157 }
158
159 // Wait for events.
160 //
161 // Returns the number of pending events and any errors.
162 //
163 // - [os.ErrClosed] if interrupted by [Close].
164 // - [ErrFlushed] if interrupted by [Flush].
165 // - [os.ErrDeadlineExceeded] if deadline is reached.
166 func (p *Poller) Wait(events []unix.EpollEvent, deadline time.Time) (int, error) {
167 p.epollMu.Lock()
168 defer p.epollMu.Unlock()
169
170 if p.epollFd == -1 {
171 return 0, errEpollWaitClosed
172 }
173
174 for {
175 timeout := int(-1)
176 if !deadline.IsZero() {
177 // Ensure deadline is not in the past and not too far into the future.
178 timeout = int(internal.Between(time.Until(deadline).Milliseconds(), 0, math.MaxInt))
179 }
180
181 n, err := unix.EpollWait(p.epollFd, events, timeout)
182 if temp, ok := err.(temporaryError); ok && temp.Temporary() {
183 // Retry the syscall if we were interrupted, see https://github.com/golang/go/issues/20400
184 continue
185 }
186
187 if err != nil {
188 return 0, err
189 }
190
191 if n == 0 {
192 return 0, errEpollWaitDeadlineExceeded
193 }
194
195 for i := 0; i < n; {
196 event := events[i]
197 if int(event.Fd) == p.closeEvent.raw {
198 // Since we don't read p.closeEvent the event is never cleared and
199 // we'll keep getting this wakeup until Close() acquires the
200 // lock and sets p.epollFd = -1.
201 return 0, errEpollWaitClosed
202 }
203 if int(event.Fd) == p.flushEvent.raw {
204 // read event to prevent it from continuing to wake
205 p.flushEvent.read()
206 err = ErrFlushed
207 events = slices.Delete(events, i, i+1)
208 n -= 1
209 continue
210 }
211 i++
212 }
213
214 return n, err
215 }
216 }
217
218 type temporaryError interface {
219 Temporary() bool
220 }
221
222 // wakeWaitForClose unblocks Wait if it's epoll_wait.
223 func (p *Poller) wakeWaitForClose() error {
224 p.eventMu.Lock()
225 defer p.eventMu.Unlock()
226
227 if p.closeEvent == nil {
228 return fmt.Errorf("epoll wake: %w", os.ErrClosed)
229 }
230
231 return p.closeEvent.add(1)
232 }
233
234 // Flush unblocks Wait if it's epoll_wait, for purposes of reading pending samples
235 func (p *Poller) Flush() error {
236 p.eventMu.Lock()
237 defer p.eventMu.Unlock()
238
239 if p.flushEvent == nil {
240 return fmt.Errorf("epoll wake: %w", os.ErrClosed)
241 }
242
243 return p.flushEvent.add(1)
244 }
245
246 // eventFd wraps a Linux eventfd.
247 //
248 // An eventfd acts like a counter: writes add to the counter, reads retrieve
249 // the counter and reset it to zero. Reads also block if the counter is zero.
250 //
251 // See man 2 eventfd.
252 type eventFd struct {
253 file *os.File
254 // prefer raw over file.Fd(), since the latter puts the file into blocking
255 // mode.
256 raw int
257 }
258
259 func newEventFd() (*eventFd, error) {
260 fd, err := unix.Eventfd(0, unix.O_CLOEXEC|unix.O_NONBLOCK)
261 if err != nil {
262 return nil, err
263 }
264 file := os.NewFile(uintptr(fd), "event")
265 return &eventFd{file, fd}, nil
266 }
267
268 func (efd *eventFd) close() error {
269 return efd.file.Close()
270 }
271
272 func (efd *eventFd) add(n uint64) error {
273 var buf [8]byte
274 internal.NativeEndian.PutUint64(buf[:], n)
275 _, err := efd.file.Write(buf[:])
276 return err
277 }
278
279 func (efd *eventFd) read() (uint64, error) {
280 var buf [8]byte
281 _, err := efd.file.Read(buf[:])
282 return internal.NativeEndian.Uint64(buf[:]), err
283 }