Debian Codegraph @

ringbuf/reader.go

raw symbols SCIP
1 package ringbuf
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7 "sync"
8 "time"
9 "unsafe"
10
11 "github.com/cilium/ebpf"
12 "github.com/cilium/ebpf/internal/platform"
13 "github.com/cilium/ebpf/internal/sys"
14 )
15
16 var (
17 ErrClosed = os.ErrClosed
18 errEOR = errors.New("end of ring")
19 errBusy = errors.New("sample not committed yet")
20 )
21
22 // poller abstracts platform-specific event notification.
23 type poller interface {
24 Wait(deadline time.Time) error
25 Flush() error
26 Close() error
27 }
28
29 // eventRing abstracts platform-specific ring buffer memory access.
30 type eventRing interface {
31 size() int
32 AvailableBytes() uint64
33 readRecord(rec *Record) error
34 Close() error
35 }
36
37 // ringbufHeader from 'struct bpf_ringbuf_hdr' in kernel/bpf/ringbuf.c
38 type ringbufHeader struct {
39 Len uint32
40 _ uint32 // pg_off, only used by kernel internals
41 }
42
43 const ringbufHeaderSize = int(unsafe.Sizeof(ringbufHeader{}))
44
45 func (rh *ringbufHeader) isBusy() bool {
46 return rh.Len&sys.BPF_RINGBUF_BUSY_BIT != 0
47 }
48
49 func (rh *ringbufHeader) isDiscard() bool {
50 return rh.Len&sys.BPF_RINGBUF_DISCARD_BIT != 0
51 }
52
53 func (rh *ringbufHeader) dataLen() int {
54 return int(rh.Len & ^uint32(sys.BPF_RINGBUF_BUSY_BIT|sys.BPF_RINGBUF_DISCARD_BIT))
55 }
56
57 type Record struct {
58 RawSample []byte
59
60 // The minimum number of bytes remaining in the ring buffer after this Record has been read.
61 Remaining int
62 }
63
64 // Reader allows reading bpf_ringbuf_output
65 // from user space.
66 type Reader struct {
67 poller poller
68
69 // mu protects read/write access to the Reader structure
70 mu sync.Mutex
71 ring eventRing
72 haveData bool
73 deadline time.Time
74 bufferSize int
75 pendingErr error
76 }
77
78 // NewReader creates a new BPF ringbuf reader.
79 func NewReader(ringbufMap *ebpf.Map) (*Reader, error) {
80 if ringbufMap.Type() != ebpf.RingBuf && ringbufMap.Type() != ebpf.WindowsRingBuf {
81 return nil, fmt.Errorf("invalid Map type: %s", ringbufMap.Type())
82 }
83
84 maxEntries := int(ringbufMap.MaxEntries())
85 if maxEntries == 0 || (maxEntries&(maxEntries-1)) != 0 {
86 return nil, fmt.Errorf("ringbuffer map size %d is zero or not a power of two", maxEntries)
87 }
88
89 poller, err := newPoller(ringbufMap.FD())
90 if err != nil {
91 return nil, err
92 }
93
94 ring, err := newRingBufEventRing(ringbufMap.FD(), maxEntries)
95 if err != nil {
96 poller.Close()
97 return nil, fmt.Errorf("failed to create ringbuf ring: %w", err)
98 }
99
100 return &Reader{
101 poller: poller,
102 ring: ring,
103 bufferSize: ring.size(),
104 // On Windows, the wait handle is only set when the reader is created,
105 // so we miss any wakeups that happened before.
106 // Do an opportunistic read to get any pending samples.
107 haveData: platform.IsWindows,
108 }, nil
109 }
110
111 // Close frees resources used by the reader.
112 //
113 // It interrupts calls to Read.
114 func (r *Reader) Close() error {
115 if err := r.poller.Close(); err != nil {
116 if errors.Is(err, os.ErrClosed) {
117 return nil
118 }
119 return err
120 }
121
122 // Acquire the lock. This ensures that Read isn't running.
123 r.mu.Lock()
124 defer r.mu.Unlock()
125
126 var err error
127 if r.ring != nil {
128 err = r.ring.Close()
129 r.ring = nil
130 }
131
132 return err
133 }
134
135 // SetDeadline controls how long Read and ReadInto will block waiting for samples.
136 //
137 // Passing a zero time.Time will remove the deadline.
138 func (r *Reader) SetDeadline(t time.Time) {
139 r.mu.Lock()
140 defer r.mu.Unlock()
141
142 r.deadline = t
143 }
144
145 // Read the next record from the BPF ringbuf.
146 //
147 // Calling [Close] interrupts the method with [os.ErrClosed]. Calling [Flush]
148 // makes it return all records currently in the ring buffer, followed by [ErrFlushed].
149 //
150 // Returns [os.ErrDeadlineExceeded] if a deadline was set and after all records
151 // have been read from the ring.
152 //
153 // See [ReadInto] for a more efficient version of this method.
154 func (r *Reader) Read() (Record, error) {
155 var rec Record
156 err := r.ReadInto(&rec)
157 return rec, err
158 }
159
160 // ReadInto is like Read except that it allows reusing Record and associated buffers.
161 func (r *Reader) ReadInto(rec *Record) error {
162 r.mu.Lock()
163 defer r.mu.Unlock()
164
165 if r.ring == nil {
166 return fmt.Errorf("ringbuffer: %w", ErrClosed)
167 }
168
169 for {
170 if !r.haveData {
171 if pe := r.pendingErr; pe != nil {
172 r.pendingErr = nil
173 return pe
174 }
175
176 err := r.poller.Wait(r.deadline)
177 if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, ErrFlushed) {
178 // Ignoring this for reading a valid entry after timeout or flush.
179 // This can occur if the producer submitted to the ring buffer
180 // with BPF_RB_NO_WAKEUP.
181 r.pendingErr = err
182 } else if err != nil {
183 return err
184 }
185 r.haveData = true
186 }
187
188 for {
189 err := r.ring.readRecord(rec)
190 // Not using errors.Is which is quite a bit slower
191 // For a tight loop it might make a difference
192 if err == errBusy {
193 continue
194 }
195 if err == errEOR {
196 r.haveData = false
197 break
198 }
199 return err
200 }
201 }
202 }
203
204 // BufferSize returns the size in bytes of the ring buffer
205 func (r *Reader) BufferSize() int {
206 return r.bufferSize
207 }
208
209 // Flush unblocks Read/ReadInto and successive Read/ReadInto calls will return pending samples at this point,
210 // until you receive a ErrFlushed error.
211 func (r *Reader) Flush() error {
212 return r.poller.Flush()
213 }
214
215 // AvailableBytes returns the amount of data available to read in the ring buffer in bytes.
216 func (r *Reader) AvailableBytes() int {
217 // Don't need to acquire the lock here since the implementation of AvailableBytes
218 // performs atomic loads on the producer and consumer positions.
219 return int(r.ring.AvailableBytes())
220 }