| 1 | |
| 2 |
|
| 3 | |
| 4 | BPF helper utilities for kernel selftests.
|
| 5 |
|
| 6 | Provides common operations for interacting with BPF maps and programs
|
| 7 | via bpftool, used by XDP and other BPF-based test files.
|
| 8 |
|
| 9 |
|
| 10 | from .utils import bpftool
|
| 11 |
|
| 12 | def _format_hex_bytes(value):
|
| 13 | |
| 14 | Helper function that converts an integer into a formatted hexadecimal byte string.
|
| 15 |
|
| 16 | Args:
|
| 17 | value: An integer representing the number to be converted.
|
| 18 |
|
| 19 | Returns:
|
| 20 | A string representing hexadecimal equivalent of value, with bytes separated by spaces.
|
| 21 |
|
| 22 | hex_str = value.to_bytes(4, byteorder='little', signed=True)
|
| 23 | return ' '.join(f'{byte:02x}' for byte in hex_str)
|
| 24 |
|
| 25 |
|
| 26 | def bpf_map_set(map_name, key, value):
|
| 27 | |
| 28 | Updates an XDP map with a given key-value pair using bpftool.
|
| 29 |
|
| 30 | Args:
|
| 31 | map_name: The name of the XDP map to update.
|
| 32 | key: The key to update in the map, formatted as a hexadecimal string.
|
| 33 | value: The value to associate with the key, formatted as a hexadecimal string.
|
| 34 |
|
| 35 | key_formatted = _format_hex_bytes(key)
|
| 36 | value_formatted = _format_hex_bytes(value)
|
| 37 | bpftool(
|
| 38 | f"map update name {map_name} key hex {key_formatted} value hex {value_formatted}"
|
| 39 | )
|
| 40 |
|
| 41 | def bpf_map_dump(map_id):
|
| 42 | |
| 43 |
|
| 44 | Args:
|
| 45 | map_id: Numeric map ID (as returned by bpftool prog show).
|
| 46 |
|
| 47 | Returns:
|
| 48 | A dict mapping formatted key (int) to formatted value (int).
|
| 49 |
|
| 50 | raw = bpftool(f"map dump id {map_id}", json=True)
|
| 51 | return {e["formatted"]["key"]: e["formatted"]["value"] for e in raw}
|
| 52 |
|
| 53 |
|
| 54 | def bpf_prog_map_ids(prog_id):
|
| 55 | |
| 56 |
|
| 57 | Args:
|
| 58 | prog_id: Numeric program ID.
|
| 59 |
|
| 60 | Returns:
|
| 61 | A dict mapping map name (str) to map ID (int).
|
| 62 |
|
| 63 | map_ids = bpftool(f"prog show id {prog_id}", json=True)["map_ids"]
|
| 64 | maps = {}
|
| 65 | for mid in map_ids:
|
| 66 | name = bpftool(f"map show id {mid}", json=True)["name"]
|
| 67 | maps[name] = mid
|
| 68 | return maps
|