· 6 years ago · Jun 17, 2019, 01:54 PM
1package bpf // import "."
2
3Package bpf provides functions that allow golang programs to interact with
4bpf maps. +groupName=pkg
5
6CONSTANTS
7
8const (
9 // BPF map type constants. Must match enum bpf_map_type from linux/bpf.h
10 BPF_MAP_TYPE_UNSPEC = 0
11 BPF_MAP_TYPE_HASH = 1
12 BPF_MAP_TYPE_ARRAY = 2
13 BPF_MAP_TYPE_PROG_ARRAY = 3
14 BPF_MAP_TYPE_PERF_EVENT_ARRAY = 4
15 BPF_MAP_TYPE_PERCPU_HASH = 5
16 BPF_MAP_TYPE_PERCPU_ARRAY = 6
17 BPF_MAP_TYPE_STACK_TRACE = 7
18 BPF_MAP_TYPE_CGROUP_ARRAY = 8
19 BPF_MAP_TYPE_LRU_HASH = 9
20 BPF_MAP_TYPE_LRU_PERCPU_HASH = 10
21 BPF_MAP_TYPE_LPM_TRIE = 11
22 BPF_MAP_TYPE_ARRAY_OF_MAPS = 12
23 BPF_MAP_TYPE_HASH_OF_MAPS = 13
24 BPF_MAP_TYPE_DEVMAP = 14
25 BPF_MAP_TYPE_SOCKMAP = 15
26 BPF_MAP_TYPE_CPUMAP = 16
27 BPF_MAP_TYPE_XSKMAP = 17
28 BPF_MAP_TYPE_SOCKHASH = 18
29 BPF_MAP_TYPE_CGROUP_STORAGE = 19
30 BPF_MAP_TYPE_REUSEPORT_SOCKARRAY = 20
31
32 // BPF syscall command constants. Must match enum bpf_cmd from linux/bpf.h
33 BPF_MAP_CREATE = 0
34 BPF_MAP_LOOKUP_ELEM = 1
35 BPF_MAP_UPDATE_ELEM = 2
36 BPF_MAP_DELETE_ELEM = 3
37 BPF_MAP_GET_NEXT_KEY = 4
38 BPF_PROG_LOAD = 5
39 BPF_OBJ_PIN = 6
40 BPF_OBJ_GET = 7
41 BPF_PROG_ATTACH = 8
42 BPF_PROG_DETACH = 9
43 BPF_PROG_TEST_RUN = 10
44 BPF_PROG_GET_NEXT_ID = 11
45 BPF_MAP_GET_NEXT_ID = 12
46 BPF_PROG_GET_FD_BY_ID = 13
47 BPF_MAP_GET_FD_BY_ID = 14
48 BPF_OBJ_GET_INFO_BY_FD = 15
49 BPF_PROG_QUERY = 16
50 BPF_RAW_TRACEPOINT_OPEN = 17
51 BPF_BTF_LOAD = 18
52 BPF_BTF_GET_FD_BY_ID = 19
53 BPF_TASK_FD_QUERY = 20
54
55 // Flags for BPF_MAP_UPDATE_ELEM. Must match values from linux/bpf.h
56 BPF_ANY = 0
57 BPF_NOEXIST = 1
58 BPF_EXIST = 2
59
60 // Flags for BPF_MAP_CREATE. Must match values from linux/bpf.h
61 BPF_F_NO_PREALLOC = 1 << 0
62 BPF_F_NO_COMMON_LRU = 1 << 1
63 BPF_F_NUMA_NODE = 1 << 2
64
65 // Flags for BPF_PROG_QUERY
66 BPF_F_QUERY_EFFECTVE = 1 << 0
67
68 // Flags for accessing BPF object
69 BPF_F_RDONLY = 1 << 3
70 BPF_F_WRONLY = 1 << 4
71
72 // Flag for stack_map, store build_id+offset instead of pointer
73 BPF_F_STACK_BUILD_ID = 1 << 5
74)
75const (
76 PERF_TYPE_HARDWARE = 0
77 PERF_TYPE_SOFTWARE = 1
78 PERF_TYPE_TRACEPOINT = 2
79 PERF_TYPE_HW_CACHE = 3
80 PERF_TYPE_RAW = 4
81 PERF_TYPE_BREAKPOINT = 5
82
83 PERF_SAMPLE_IP = 1 << 0
84 PERF_SAMPLE_TID = 1 << 1
85 PERF_SAMPLE_TIME = 1 << 2
86 PERF_SAMPLE_ADDR = 1 << 3
87 PERF_SAMPLE_READ = 1 << 4
88 PERF_SAMPLE_CALLCHAIN = 1 << 5
89 PERF_SAMPLE_ID = 1 << 6
90 PERF_SAMPLE_CPU = 1 << 7
91 PERF_SAMPLE_PERIOD = 1 << 8
92 PERF_SAMPLE_STREAM_ID = 1 << 9
93 PERF_SAMPLE_RAW = 1 << 10
94 PERF_SAMPLE_BRANCH_STACK = 1 << 11
95 PERF_SAMPLE_REGS_USER = 1 << 12
96 PERF_SAMPLE_STACK_USER = 1 << 13
97 PERF_SAMPLE_WEIGHT = 1 << 14
98 PERF_SAMPLE_DATA_SRC = 1 << 15
99 PERF_SAMPLE_IDENTIFIER = 1 << 16
100 PERF_SAMPLE_TRANSACTION = 1 << 17
101 PERF_SAMPLE_REGS_INTR = 1 << 18
102
103 PERF_COUNT_SW_BPF_OUTPUT = 10
104)
105const (
106 MAX_POLL_EVENTS = 32
107)
108
109VARIABLES
110
111var (
112 MapTypeMismatch = errors.New("map type mismatch for BPF map")
113 MapKeyMismatch = errors.New("key-size mismatch for BPF map")
114 MapValueMismatch = errors.New("value-size mismatch for BPF map")
115 MapEntriesMismatch = errors.New("max entries mismatch for BPF map")
116 MapFlagsMismatch = errors.New("flags mismatch for BPF map")
117)
118
119FUNCTIONS
120
121func ConvertKeyValue(bKey []byte, bValue []byte, key MapKey, value MapValue) (MapKey, MapValue, error)
122 ConvertKeyValue converts key and value from bytes to given Golang struct
123 pointers.
124
125func CreateMap(mapType int, keySize, valueSize, maxEntries, flags, innerID uint32, path string) (int, error)
126 CreateMap creates a Map of type mapType, with key size keySize, a value size
127 of valueSize and the maximum amount of entries of maxEntries. mapType should
128 be one of the bpf_map_type in "uapi/linux/bpf.h" When mapType is the type
129 HASH_OF_MAPS an innerID is required to point at a map fd which has the same
130 type/keySize/valueSize/maxEntries as expected map entries. For all other
131 mapTypes innerID is ignored and should be zeroed.
132
133func DeleteElement(fd int, key unsafe.Pointer) error
134 DeleteElement deletes the map element with the given key.
135
136func DisableMapPreAllocation()
137 DisableMapPreAllocation disables BPF map pre-allocation as a default
138 setting. Some map types enforces pre-alloc strategy so this does not take
139 effect in that case. Also note that this does not take effect on existing
140 map although could be recreated later when objCheck() runs.
141
142func EnableMapPreAllocation()
143 EnableMapPreAllocation enables BPF map pre-allocation on map types that
144 support it. This does not take effect on existing map although some map
145 types could be recreated later when objCheck() runs.
146
147func GetMtime() (uint64, error)
148 GetMtime returns monotonic time that can be used to compare values with
149 ktime_get_ns() BPF helper, e.g. needed to check the timeout in sec for BPF
150 entries. We return the raw nsec, although that is not quite usable for
151 comparison. Go has runtime.nanotime() but doesn't expose it as API.
152
153func GetNextKey(fd int, key, nextKey unsafe.Pointer) error
154 GetNextKey stores, in nextKey, the next key after the key of the map in fd.
155 Deprecated, use GetNextKeyFromPointers
156
157func GetNextKeyFromPointers(fd int, structPtr, sizeOfStruct uintptr) error
158 GetNextKeyFromPointers stores, in nextKey, the next key after the key of the
159 map in fd.
160
161func GetOpenMaps() []*models.BPFMap
162 GetOpenMaps returns a slice of all open BPF maps. This is identical to
163 calling GetMap() on all open maps.
164
165func GetPreAllocateMapFlags(t MapType) uint32
166 GetPreAllocateMapFlags returns the map flags for map which use conditional
167 pre-allocation.
168
169func GetProgFDByID(id uint32) (int, error)
170 GetProgFDByID returns the file descriptor for the program id.
171
172func GetProgNextID(current uint32) (uint32, error)
173 GetProgNextID takes a current program ID and returns the next program ID.
174
175func IsCorrelationError(err error) bool
176func IsMapMismatch(err error) bool
177func LookupElement(fd int, key, value unsafe.Pointer) error
178 LookupElement looks up for the map value stored in fd with the given key.
179 The value is stored in the value unsafe.Pointer. Deprecated, use
180 LookupElementFromPointers
181
182func LookupElementFromPointers(fd int, structPtr, sizeOfStruct uintptr) error
183 LookupElement looks up for the map value stored in fd with the given key.
184 The value is stored in the value unsafe.Pointer.
185
186func MapFdFromID(id int) (int, error)
187 MapFdFromID retrieves a file descriptor based on a map ID.
188
189func ObjClose(fd int) error
190 ObjClose closes the map's fd.
191
192func ObjGet(pathname string) (int, error)
193 ObjGet reads the pathname and returns the map's fd read.
194
195func ObjPin(fd int, pathname string) error
196 ObjPin stores the map's fd in pathname.
197
198func OpenOrCreateMap(path string, mapType int, keySize, valueSize, maxEntries, flags uint32, innerID uint32) (int, bool, error)
199func ReadFeatureProbes(filename string) error
200 ReadFeatureProbes reads the bpf_features.h file at the specified path (as
201 generated by bpf/run_probes.sh), and stores the results of the kernel
202 feature probing.
203
204func UpdateElement(fd int, key, value unsafe.Pointer, flags uint64) error
205 UpdateElement updates the map in fd with the given value in the given key.
206 The flags can have the following values: bpf.BPF_ANY to create new element
207 or update existing; bpf.BPF_NOEXIST to create new element if it didn't
208 exist; bpf.BPF_EXIST to update existing element. Deprecated, use
209 UpdateElementFromPointers
210
211func UpdateElementFromPointers(fd int, structPtr, sizeOfStruct uintptr) error
212 UpdateElementFromPointers updates the map in fd with the given value in the
213 given key. The flags can have the following values: bpf.BPF_ANY to create
214 new element or update existing; bpf.BPF_NOEXIST to create new element if it
215 didn't exist; bpf.BPF_EXIST to update existing element.
216
217
218TYPES
219
220type CorrelationError struct {
221 Err error
222 Key interface{}
223}
224
225func (e *CorrelationError) Error() string
226type DesiredAction int
227 DesiredAction is the action to be performed on the BPF map
228
229const (
230 // OK indicates that to further action is required and the entry is in
231 // sync
232 OK DesiredAction = iota
233
234 // Insert indicates that the entry needs to be created or updated
235 Insert
236
237 // Delete indicates that the entry needs to be deleted
238 Delete
239)
240func (d DesiredAction) String() string
241type DumpCallback func(key MapKey, value MapValue)
242
243type DumpParser func(key []byte, value []byte, mapKey MapKey, mapValue MapValue) (MapKey, MapValue, error)
244
245type DumpStats struct {
246 // Started is the timestamp when the gc run was started.
247 Started time.Time
248
249 // Finished is the timestamp when the gc run completed.
250 Finished time.Time
251
252 // Lookup is the number of key lookups performed.
253 Lookup uint32
254
255 // LookupFailed is the number of key lookups that failed.
256 LookupFailed uint32
257
258 // PrevKeyUnavailable is the number of times the previous key was not
259 // available.
260 PrevKeyUnavailable uint32
261
262 // KeyFallback is the number of times the current key became invalid
263 // while traversing and we had to fall back to the previous key.
264 KeyFallback uint32
265
266 // MaxEntries is the maximum number of entries in the gc table.
267 MaxEntries uint32
268
269 // Interrupted is the number of times the gc run was interrupted and
270 // had to start from scratch.
271 Interrupted uint32
272
273 // Completed is true when the gc run has been completed.
274 Completed bool
275}
276 DumpStats tracks statistics over the dump of a map.
277
278func NewDumpStats(m *Map) *DumpStats
279 NewDumpStats returns a new stats structure for collecting dump statistics.
280
281func (d *DumpStats) Duration() time.Duration
282 Duration returns the duration of the dump.
283
284type EPoll struct {
285 // Has unexported fields.
286}
287
288func (ep *EPoll) AddFD(fd int, events uint32) error
289func (ep *EPoll) Close()
290func (ep *EPoll) Poll(timeout int) (int, error)
291type ErrorFunc func(msg *PerfEvent)
292 ErrorFunc is run when reading PerfEvent results in an error
293
294type EventMap struct {
295 // Has unexported fields.
296}
297
298func (e *EventMap) Close()
299func (e *EventMap) Update(fd int, ubaPtr, sizeOf uintptr) error
300type LostFunc func(msg *PerfEventLost, cpu int)
301
302type Map struct {
303 MapInfo
304
305 // NonPersistent is true if the map does not contain persistent data
306 // and should be removed on startup.
307 NonPersistent bool
308
309 // Has unexported fields.
310}
311
312func GetMap(path string) *Map
313 GetMap returns the registered map with the given absolute path
314
315func NewMap(name string, mapType MapType, mapKey MapKey, keySize int, mapValue MapValue, valueSize, maxEntries int, flags uint32, innerID uint32, dumpParser DumpParser) *Map
316 NewMap creates a new Map instance - object representing a BPF map
317
318func NewPerCPUHashMap(name string, mapKey MapKey, keySize int, mapValue MapValue, valueSize, cpus, maxEntries int, flags uint32, innerID uint32, dumpParser DumpParser) *Map
319 NewPerCPUHashMap creates a new Map type of "per CPU hash" - object
320 representing a BPF map The number of cpus is used to have the size
321 representation of a value when a lookup is made on this map types.
322
323func OpenMap(mapPath string) (*Map, error)
324 OpenMap opens the given bpf map and generates the Map info based in the
325 information stored in the bpf map. *Warning*: Calling this function requires
326 the caller to properly setup the MapInfo.MapKey and MapInfo.MapValues fields
327 as those structures are not stored in the bpf map.
328
329func (m *Map) CheckAndUpgrade(desired *MapInfo) bool
330 CheckAndUpgrade checks the received map's properties (for the map currently
331 loaded into the kernel) against the desired properties, and if they do not
332 match, deletes the map.
333
334 Returns true if the map was upgraded.
335
336func (m *Map) Close() error
337func (m *Map) DeepEquals(other *Map) bool
338 DeepEquals compares the current map against another map to see that the
339 attributes of the two maps are the same.
340
341func (m *Map) Delete(key MapKey) error
342func (m *Map) DeleteAll() error
343 DeleteAll deletes all entries of a map by traversing the map and deleting
344 individual entries. Note that if entries are added while the taversal is in
345 progress, such entries may survive the deletion process.
346
347func (m *Map) DeleteWithErrno(key MapKey) (error, syscall.Errno)
348func (m *Map) Dump(hash map[string][]string) error
349 Dump returns the map (type map[string][]string) which contains all data
350 stored in BPF map.
351
352func (m *Map) DumpIfExists(hash map[string][]string) error
353 DumpIfExists dumps the contents of the map into hash via Dump() if the map
354 file exists
355
356func (m *Map) DumpReliablyWithCallback(cb DumpCallback, stats *DumpStats) error
357 DumpReliablyWithCallback is similar to DumpWithCallback, but performs
358 additional tracking of the current and recently seen keys, so that if an
359 element is removed from the underlying kernel map during the dump, the dump
360 can continue from a recently seen key rather than restarting from scratch.
361 In addition, it caps the maximum number of map entry iterations by the
362 maximum size of the map.
363
364 The caller must provide a callback for handling each entry, and a stats
365 object initialized via a call to NewDumpStats().
366
367func (m *Map) DumpWithCallback(cb DumpCallback) error
368 DumpWithCallback iterates over the Map and calls the given callback function
369 on each iteration. That callback function is receiving the actual key and
370 value. The callback function should consider creating a deepcopy of the key
371 and value on between each iterations to avoid memory corruption.
372
373func (m *Map) DumpWithCallbackIfExists(cb DumpCallback) error
374 DumpWithCallbackIfExists is similar to DumpWithCallback, but returns earlier
375 if the given map does not exist.
376
377func (m *Map) EndParallelMode()
378 EndParallelMode ends the parallel mode of a map
379
380func (m *Map) GetFd() int
381func (m *Map) GetModel() *models.BPFMap
382 GetModel returns a BPF map in the representation served via the API
383
384func (m *Map) GetNextKey(key MapKey, nextKey MapKey) error
385 GetNextKey returns the next key in the Map after key.
386
387func (m *Map) Lookup(key MapKey) (MapValue, error)
388func (m *Map) Name() string
389 Name returns the basename of this map.
390
391func (m *Map) Open() error
392func (m *Map) OpenOrCreate() (bool, error)
393 OpenOrCreate attempts to open the Map, or if it does not yet exist, create
394 the Map. If the existing map's attributes such as map type, key/value size,
395 capacity, etc. do not match the Map's attributes, then the map will be
396 deleted and reopened without any attempt to retain its previous contents. If
397 the map is marked as non-persistent, it will always be recreated.
398
399 If the map type is MapTypeLRUHash or MapTypeLPMTrie and the kernel lacks
400 support for this map type, then the map will be opened as MapTypeHash
401 instead. Note that the BPF code that interacts with this map *MUST* be
402 structured in such a way that the map is declared as the same type based on
403 the same probe logic (eg HAVE_LRU_MAP_TYPE, HAVE_LPM_MAP_TYPE).
404
405 For code that uses an LPMTrie, the BPF code must also use macros to retain
406 the "longest prefix match" behaviour on top of the hash maps, for example
407 via LPM_LOOKUP_FN() (see bpf/lib/maps.h).
408
409 To detect map type support properly, this function must be called after a
410 call to ReadFeatureProbes(); failure to do so will result in LPM or LRU map
411 types being unconditionally opened as hash maps.
412
413 Returns whether the map was deleted and recreated, or an optional error.
414
415func (m *Map) OpenParallel() (bool, error)
416 OpenParallel is similar to OpenOrCreate() but prepares the existing map to
417 be faded out while a new map is taking over. This can be used if a map is
418 shared between multiple consumers and the context of the shared map is
419 changing. Any update to the shared map would impact all consumers and
420 consumers can only be updated one by one. Parallel mode allows for consumers
421 to continue using the old version of the map until the consumer is updated
422 to use the new version.
423
424func (m *Map) Path() string
425 Path returns the path to this map on the filesystem.
426
427func (m *Map) Reopen() error
428 Reopen attempts to close and re-open the received map.
429
430func (m *Map) SynchronizeCache(ctx context.Context) (*MapSyncStats, error)
431 SynchronizeCache iterates through the in-memory cache of entries that have
432 been inserted into the map and attempts to resolve discrepancies between the
433 desired state of the map in the cache and the actual state in the underlying
434 BPF map. If all entries in the cache are populated in the BPF map, then this
435 is a no-op.
436
437 This function will only attempt to resolve a limited number of discrepancies
438 within a single execution.
439
440func (m *Map) Unpin() error
441 Unpin attempts to unpin (remove) the map from the filesystem.
442
443func (m *Map) UnpinIfExists() error
444 UnpinIfExists tries to unpin (remove) the map only if it exists.
445
446func (m *Map) Update(key MapKey, value MapValue) error
447func (m *Map) WithCache(scheduler MapSyncScheduler) *Map
448 WithCache enables use of a cache. This will store all entries inserted from
449 user space in a local cache (map) and will indicate the status of each
450 individual entry.
451
452 The scheduler parameter is optional, and if non-nil, will be invoked
453 whenever an error occurs while managing entries in the BPF map (for example,
454 via Update() or Delete()).
455
456func (m *Map) WithNonPersistent() *Map
457 WithNonPersistent turns the map non-persistent and returns the map
458
459type MapInfo struct {
460 MapType MapType
461 MapKey MapKey
462 KeySize uint32
463 MapValue MapValue
464 // ReadValueSize is the value size that is used to read from the BPF maps
465 // this value an the ValueSize values can be different for BPF_MAP_TYPE_PERCPU_HASH
466 // for example.
467 ReadValueSize uint32
468 ValueSize uint32
469 MaxEntries uint32
470 Flags uint32
471 InnerID uint32
472 OwnerProgType ProgType
473}
474
475func GetMapInfo(pid int, fd int) (*MapInfo, error)
476type MapKey interface {
477 fmt.Stringer
478
479 // Returns pointer to start of key
480 GetKeyPtr() unsafe.Pointer
481
482 // Allocates a new value matching the key type
483 NewValue() MapValue
484
485 // DeepCopyMapKey returns a deep copy of the map key
486 DeepCopyMapKey() MapKey
487}
488
489type MapMismatchError struct {
490 Err error
491 Old interface{}
492 New interface{}
493}
494
495func (e *MapMismatchError) Error() string
496type MapSyncScheduler interface {
497 HandleError()
498}
499 MapSyncScheduler is responsible for scheduling calls to m.SynchronizeMap()
500 when errors occur while attempting to update or delete keys from the
501 underlying BPF map.
502
503type MapSyncStats struct {
504 PendingEntries int
505 ResolvedErrors int
506 ScannedEntries int
507 SyncDuration time.Duration
508}
509 MapSyncStats
510
511type MapType int
512 MapType is an enumeration for valid BPF map types
513
514const (
515 MapTypeUnspec MapType = iota
516 MapTypeHash
517 MapTypeArray
518 MapTypeProgArray
519 MapTypePerfEventArray
520 MapTypePerCPUHash
521 MapTypePerCPUArray
522 MapTypeStackTrace
523 MapTypeCgroupArray
524 MapTypeLRUHash
525 MapTypeLRUPerCPUHash
526 MapTypeLPMTrie
527 MapTypeArrayOfMaps
528 MapTypeHashOfMaps
529 MapTypeDevMap
530 MapTypeSockMap
531 MapTypeCPUMap
532 MapTypeXSKMap
533 MapTypeSockHash
534 // MapTypeMaximum is the maximum supported known map type.
535 MapTypeMaximum
536)
537 This enumeration must be in sync with enum bpf_prog_type in <linux/bpf.h>
538
539func GetMapType(t MapType) MapType
540 GetMapType determines whether the specified map type is supported by the
541 kernel (as determined by ReadFeatureProbes()), and if the map type is not
542 supported, returns a more primitive map type that may be used to implement
543 the map on older implementations. Otherwise, returns the specified map type.
544
545func (t MapType) String() string
546type MapValidator func(path string) (bool, error)
547
548type MapValue interface {
549 fmt.Stringer
550
551 // Returns pointer to start of value
552 GetValuePtr() unsafe.Pointer
553
554 // DeepCopyMapValue returns a deep copy of the map value
555 DeepCopyMapValue() MapValue
556}
557
558type PerCpuEvents struct {
559 Cpus int
560 Npages int
561 Pagesize int
562
563 // Has unexported fields.
564}
565
566func NewPerCpuEvents(config *PerfEventConfig) (*PerCpuEvents, error)
567func (e *PerCpuEvents) CloseAll() error
568func (e *PerCpuEvents) Poll(timeout int) (int, error)
569func (e *PerCpuEvents) ReadAll(receive ReceiveFunc, lost LostFunc, handleError ErrorFunc) error
570 ReadAll reads perf events
571
572func (e *PerCpuEvents) Stats() (uint64, uint64, uint64)
573type PerfEvent struct {
574 Fd int
575
576 // Has unexported fields.
577}
578
579func PerfEventFromMemory(page *PerfEventMmapPage, buf []byte) *PerfEvent
580 PerfEventFromMemory creates an in-memory PerfEvent object for testing and
581 analysis purposes. No kernel interaction is made.
582
583 The caller MUST eventually call Disable() to free event resources.
584
585func PerfEventOpen(config *PerfEventConfig, pid int, cpu int, groupFD int, flags int) (*PerfEvent, error)
586func (e *PerfEvent) Close()
587func (e *PerfEvent) Debug() string
588 Debug returns string with internal information about PerfEvent
589
590func (e *PerfEvent) DebugDump() string
591func (e *PerfEvent) Disable() error
592func (e *PerfEvent) Enable() error
593func (e *PerfEvent) Mmap(pagesize int, npages int) error
594func (e *PerfEvent) Munmap() error
595func (e *PerfEvent) Read(receive ReceiveFunc, lostFn LostFunc, err ErrorFunc)
596 Read attempts to read all events from the perf event buffer, calling one of
597 the receive / lost functions for each event. receiveFn is called when the
598 event is a valid sample; lostFn is called when the kernel has attempted to
599 write an event into the ringbuffer but ran out of space for the event.
600
601 If all events are not read within a time period (default 20s), it will call
602 errFn() and stop reading events.
603
604type PerfEventConfig struct {
605 NumCpus int
606 NumPages int
607 MapPath string
608 Type int
609 Config int
610 SampleType int
611 WakeupEvents int
612}
613
614func DefaultPerfEventConfig(path string) *PerfEventConfig
615type PerfEventHeader struct {
616 Type uint32
617 Misc uint16
618 TotalSize uint16
619}
620 PerfEventHeader must match 'struct perf_event_header in
621 <linux/perf_event.h>.
622
623type PerfEventLost struct {
624 PerfEventHeader
625 Id uint64
626 Lost uint64
627}
628 PerfEventLost must match 'struct perf_event_lost in kernel sources.
629
630type PerfEventMmapPage struct {
631 Version uint32 // version number of this structure
632 CompatVersion uint32 // lowest version this is compat with
633
634 Lock uint32 // seqlock for synchronization
635 Index uint32 // hardware event identifier
636 Offset int64 // add to hardware event value
637 TimeEnabled uint64 // time event active
638 TimeRunning uint64 // time event on cpu
639 //union {
640 Capabilities uint64
641
642 // cap_user_rdpmc : 1, /* The RDPMC instruction can be used to read counts */
643 // cap_user_time : 1, /* The time_* fields are used */
644 // cap_user_time_zero : 1, /* The time_zero field is used */
645 // cap_____res : 59;
646 //};
647 //};
648 PmcWidth uint16
649
650 TimeShift uint16
651 TimeMult uint32
652 TimeOffset uint64
653 TimeZero uint64
654 Size uint32
655
656 Reserved [118*8 + 4]uint8 // align to 1k.
657
658 DataHead uint64 // head in the data section
659 DataTail uint64 // user-space written tail
660 DataOffset uint64 // where the buffer starts
661 DataSize uint64 // data buffer size
662
663 AuxHead uint64
664 AuxTail uint64
665 AuxOffset uint64
666 AuxSize uint64
667}
668 PerfEventMmapPage reflects the Linux 'struct perf_event_mmap_page'
669
670func (p *PerfEventMmapPage) Decode(reader io.ReadSeeker) error
671 Decode populates 'p' base on the bytes read from the specified reader.
672
673 This function should not be used from performance-sensitive code.
674
675type PerfEventSample struct {
676 PerfEventHeader
677 Size uint32
678 // Has unexported fields.
679}
680 PerfEventSample must match 'struct perf_event_sample in kernel sources.
681
682func (e *PerfEventSample) DataCopy() []byte
683func (e *PerfEventSample) DataDirect() []byte
684type ProgInfo struct {
685 ProgType uint32
686 ID uint32
687 Tag uint8
688 JitedProgLen uint32
689 XlatedProgLen uint32
690 JitedProgInsns uint64
691 XlatedProgInsns uint64
692 LoadTime uint64 // ns since boottime
693 CreatedByUID uint32
694 NRMapIDs uint32
695 MapIDs []uint32
696 Name string
697 IfIndex uint32
698 NetnsDev uint64
699 NetnsIno uint64
700 NrJitedKsyms uint32
701 NrJitedFuncLens uint32
702 JitedKsyms uint64
703 JitedFuncLens uint64
704}
705 ProgInfo holds values from the upstream struct bpf_prog_info. From:
706 https://github.com/torvalds/linux/blob/v4.19-rc2/include/uapi/linux/bpf.h#L2427
707
708func GetProgInfoByFD(fd int) (ProgInfo, error)
709 GetProgInfoByFD gets the bpf program info from its file descriptor.
710
711type ProgType int
712 ProgType is an enumeration for valid BPF program types
713
714const (
715 ProgTypeUnspec ProgType = iota
716 ProgTypeSocketFilter
717 ProgTypeKprobe
718 ProgTypeSchedCls
719 ProgTypeSchedAct
720 ProgTypeTracepoint
721 ProgTypeXdp
722 ProgTypePerfEvent
723 ProgTypeCgroupSkb
724 ProgTypeCgroupSock
725 ProgTypeLwtIn
726 ProgTypeLwtOut
727 ProgTypeLwtXmit
728 ProgTypeSockOps
729 ProgTypeSkSkb
730 ProgTypeCgroupDevice
731 ProgTypeSkMsg
732 ProgTypeRawTracepoint
733 ProgTypeCgroupSockAddr
734 ProgTypeLwtSeg6Local
735 ProgTypeLircMode2
736 ProgTypeSkReusePort
737)
738 This enumeration must be in sync with enum bpf_prog_type in <linux/bpf.h>
739
740func (t ProgType) String() string
741type ReadState struct {
742 Base uint64 // Actually a pointer
743 RawSize uint64
744 LastSize uint64
745}
746 ReadState is a golang reflection of C.struct_read_state{}
747
748func (r *ReadState) Decode(reader io.ReadSeeker) error
749 Decode populates 'r' based on the bytes read from the specified reader.
750
751 This function should not be used from performance-sensitive code.
752
753type ReceiveFunc func(msg *PerfEventSample, cpu int)