| 1 |
package ringbuf |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"io" |
| 6 |
"sync/atomic" |
| 7 |
"unsafe" |
| 8 |
|
| 9 |
"github.com/cilium/ebpf/internal" |
| 10 |
"github.com/cilium/ebpf/internal/sys" |
| 11 |
) |
| 12 |
|
| 13 |
type ringReader struct { |
| 14 |
|
| 15 |
prod_pos, cons_pos *uintptr |
| 16 |
mask uintptr |
| 17 |
ring []byte |
| 18 |
} |
| 19 |
|
| 20 |
func newRingReader(cons_ptr, prod_ptr *uintptr, ring []byte) *ringReader { |
| 21 |
return &ringReader{ |
| 22 |
prod_pos: prod_ptr, |
| 23 |
cons_pos: cons_ptr, |
| 24 |
|
| 25 |
mask: uintptr(cap(ring)/2 - 1), |
| 26 |
ring: ring, |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
func (rr *ringReader) size() int { |
| 34 |
return cap(rr.ring) / 2 |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
func (rr *ringReader) AvailableBytes() uint64 { |
| 39 |
prod := atomic.LoadUintptr(rr.prod_pos) |
| 40 |
cons := atomic.LoadUintptr(rr.cons_pos) |
| 41 |
return uint64(prod - cons) |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
func (rr *ringReader) readRecord(rec *Record) error { |
| 46 |
prod := atomic.LoadUintptr(rr.prod_pos) |
| 47 |
cons := atomic.LoadUintptr(rr.cons_pos) |
| 48 |
|
| 49 |
for { |
| 50 |
if remaining := prod - cons; remaining == 0 { |
| 51 |
return errEOR |
| 52 |
} else if remaining < sys.BPF_RINGBUF_HDR_SZ { |
| 53 |
return fmt.Errorf("read record header: %w", io.ErrUnexpectedEOF) |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
start := cons & rr.mask |
| 61 |
len := atomic.LoadUint32((*uint32)((unsafe.Pointer)(&rr.ring[start]))) |
| 62 |
header := ringbufHeader{Len: len} |
| 63 |
|
| 64 |
if header.isBusy() { |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
return errBusy |
| 69 |
} |
| 70 |
|
| 71 |
cons += sys.BPF_RINGBUF_HDR_SZ |
| 72 |
|
| 73 |
|
| 74 |
dataLenAligned := uintptr(internal.Align(header.dataLen(), 8)) |
| 75 |
if remaining := prod - cons; remaining < dataLenAligned { |
| 76 |
return fmt.Errorf("read sample data: %w", io.ErrUnexpectedEOF) |
| 77 |
} |
| 78 |
|
| 79 |
start = cons & rr.mask |
| 80 |
cons += dataLenAligned |
| 81 |
|
| 82 |
if header.isDiscard() { |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
atomic.StoreUintptr(rr.cons_pos, cons) |
| 87 |
continue |
| 88 |
} |
| 89 |
|
| 90 |
if n := header.dataLen(); cap(rec.RawSample) < n { |
| 91 |
rec.RawSample = make([]byte, n) |
| 92 |
} else { |
| 93 |
rec.RawSample = rec.RawSample[:n] |
| 94 |
} |
| 95 |
|
| 96 |
copy(rec.RawSample, rr.ring[start:]) |
| 97 |
rec.Remaining = int(prod - cons) |
| 98 |
atomic.StoreUintptr(rr.cons_pos, cons) |
| 99 |
return nil |
| 100 |
} |
| 101 |
} |