BPF_MAP_TYPE_HASH, with PERCPU and LRU Variants
BPF_MAP_TYPE_HASH and BPF_MAP_TYPE_PERCPU_HASH provide general purpose hash map storage. Both the key and the value can be structs, allowing for composite keys and values.
The kernel is responsible for allocating and freeing key/value pairs, up to the max_entries limit that you specify. Hash maps use pre-allocation of hash table elements by default. The BPF_F_NO_PREALLOC flag can be used to disable pre-allocation when it is too memory expensive.
BPF_MAP_TYPE_PERCPU_HASH provides a separate value slot per CPU. The per-cpu values are stored internally in an array.
The BPF_MAP_TYPE_LRU_HASH and BPF_MAP_TYPE_LRU_PERCPU_HASH variants add LRU semantics to their respective hash tables. An LRU hash will automatically evict the least recently used entries when the hash table reaches capacity. An LRU hash maintains an internal LRU list that is used to select elements for eviction. This internal LRU list is shared across CPUs but it is possible to request a per CPU LRU list with the BPF_F_NO_COMMON_LRU flag when calling bpf_map_create. The following table outlines the properties of LRU maps depending on the a map type and the flags used to create the map.
|
Flag |
|
|
|---|---|---|
|
BPF_F_NO_COMMON_LRU |
Per-CPU LRU, global map |
Per-CPU LRU, per-cpu map |
|
!BPF_F_NO_COMMON_LRU |
Global LRU, global map |
Global LRU, per-cpu map |
Usage #
Kernel BPF #
bpf_map_update_elem() #
long Hash entries can be added or updated using the bpf_map_update_elem() helper. This helper replaces existing elements atomically. The flags parameter can be used to control the update behaviour:
-
BPF_ANYwill create a new element or update an existing element -
BPF_NOEXISTwill create a new element only if one did not already exist -
BPF_EXISTwill update an existing element
bpf_map_update_elem() returns 0 on success, or negative error in case of failure.
bpf_map_lookup_elem() #
void *Hash entries can be retrieved using the bpf_map_lookup_elem() helper. This helper returns a pointer to the value associated with key, or NULL if no entry was found.
bpf_map_delete_elem() #
long Hash entries can be deleted using the bpf_map_delete_elem() helper. This helper will return 0 on success, or negative error in case of failure.
Per CPU Hashes #
For BPF_MAP_TYPE_PERCPU_HASH and BPF_MAP_TYPE_LRU_PERCPU_HASH the bpf_map_update_elem() and bpf_map_lookup_elem() helpers automatically access the hash slot for the current CPU.
bpf_map_lookup_percpu_elem() #
void *The bpf_map_lookup_percpu_elem() helper can be used to lookup the value in the hash slot for a specific CPU. Returns value associated with key on cpu , or NULL if no entry was found or cpu is invalid.
Concurrency #
Values stored in BPF_MAP_TYPE_HASH can be accessed concurrently by programs running on different CPUs. Since Kernel version 5.1, the BPF infrastructure provides struct bpf_spin_lock to synchronise access. See tools/testing/selftests/bpf/progs/test_spin_lock.c.
Userspace #
bpf_map_get_next_key() #
int In userspace, it is possible to iterate through the keys of a hash using libbpf's bpf_map_get_next_key() function. The first key can be fetched by calling bpf_map_get_next_key() with cur_key set to NULL. Subsequent calls will fetch the next key that follows the current key. bpf_map_get_next_key() returns 0 on success, -ENOENT if cur_key is the last key in the hash, or negative error in case of failure.
Note that if cur_key gets deleted then bpf_map_get_next_key() will instead return the first key in the hash table which is undesirable. It is recommended to use batched lookup if there is going to be key deletion intermixed with bpf_map_get_next_key().
Examples #
Please see the tools/testing/selftests/bpf directory for functional examples. The code snippets below demonstrates API usage.
This example shows how to declare an LRU Hash with a struct key and a struct value.
;
;
packet_stats ;
This example shows how to create or update hash values using atomic instructions:
static void
Userspace walking the map elements from the map declared above:
static void
Internals #
This section of the document is targeted at Linux developers and describes aspects of the map implementations that are not considered stable ABI. The following details are subject to change in future versions of the kernel.
BPF_MAP_TYPE_LRU_HASH and variants #
Updating elements in LRU maps may trigger eviction behaviour when the capacity of the map is reached. There are various steps that the update algorithm attempts in order to enforce the LRU property which have increasing impacts on other CPUs involved in the following operation attempts:
-
Attempt to use CPU-local state to batch operations
-
Attempt to fetch
target_freefree nodes from global lists -
Attempt to pull any node from a global list and remove it from the hashmap
-
Attempt to pull any node from any CPU's list and remove it from the hashmap
The number of nodes to borrow from the global list in a batch, target_free, depends on the size of the map. Larger batch size reduces lock contention, but may also exhaust the global structure. The value is computed at map init to avoid exhaustion, by limiting aggregate reservation by all CPUs to half the map size. With a minimum of a single element and maximum budget of 128 at a time.
This algorithm is described visually in the following diagram. See the description in commit 3a08c2fd7634 ("bpf: LRU List") for a full explanation of the corresponding operations:
flowchart TB
n5(["begin<br/>bpf_map_update()"])
n6{"Local freelist<br/>node available?"}
n7["Use node owned<br/>by this CPU"]
n8{"Map created with<br/>common LRU?<br/>(!BPF_F_NO_COMMON_LRU)"}
n9["Flush local pending,<br/>Rotate Global list, move<br/>target_free<br/>from global -#62; local"]
n10{"Able to free<br/>target_free<br/>nodes?"}
n11["Shrink inactive list<br/>up to remaining<br/>target_free<br/>(global LRU -#62; local)"]
n12{"#62; 0 entries in<br/>local free list?"}
n13["Steal one node from<br/>inactive, or if empty,<br/>from active global list"]
n14["Try to remove<br/>node from hashtab"]
n15{"Htab removal<br/>successful?"}
n16{"Map created with<br/>common LRU?<br/>(!BPF_F_NO_COMMON_LRU)"}
n22["Use node that was<br/>not recently referenced"]
n23["Use node that was<br/>actively referenced<br/>in global list"]
n24(["return -ENOMEM"])
n25["Use node that was<br/>actively referenced<br/>in (another?) CPU's cache"]
n26["Update hashmap<br/>with new element"]
n27(["return 0"])
n28(["return -EBUSY"])
n29(["return -EEXIST"])
n30(["return -ENOENT"])
subgraph g0["Key<br/>(locks held during operation)"]
direction TB
n0["remote CPU LRU lock"]
n1["hashtab lock"]
n2["LRU lock"]
n3["local CPU LRU lock"]
n4["no locks held"]
end
subgraph g1["Iterate through CPUs<br/>(start from current)"]
direction LR
n17{"Steal a node from<br/>per-cpu freelist?"}
n18["Steal a node from<br/>(1) Unreferenced pending, or<br/>(2) Any pending node"]
n19["Try to remove<br/>node from hashtab"]
n20{"Stole node<br/>from remote<br/>CPU?"}
n21{"Iterated<br/>all CPUs?"}
end
n5 --> n6
n6 -->|"Y"| n7
n6 -->|"N"| n8
n8 -->|"Y"| n9
n8 -->|"N"| n11
n9 --> n10
n10 -->|"Y"| n22
n10 -->|"N"| n11
n11 --> n12
n12 -->|"Y"| n22
n12 -->|"N"| n13
n13 --> n14
n14 --> n15
n15 -->|"Y"| n23
n15 -->|"N"| n16
n16 -->|"Y"| n17
n16 -->|"N"| n24
n17 -->|"Y"| n20
n17 -->|"N"| n18
n18 --> n19
n19 --> n20
n20 -->|"Y"| n25
n20 -->|"N"| n21
n21 -->|"Y"| n24
n21 -->|"N"| n17
n25 --> n26
n7 --> n26
n22 --> n26
n23 --> n26
n26 -->|"Success"| n27
n26 -->|"Hashtab lock failed"| n28
n26 -->|"BPF_EXIST set and<br/>key already exists"| n29
n26 -->|"BPF_NOEXIST set<br/>and no such entry"| n30
style n0 fill:#ffff99,color:#111
style n1 fill:#fdc086,color:#111
style n2 fill:#beaed4,color:#111
style n3 fill:#7fc97f,color:#111
style n6 fill:#7fc97f,color:#111
style n9 fill:#beaed4,color:#111
style n10 fill:#beaed4,color:#111
style n11 fill:#fdc086,color:#111
style n12 fill:#beaed4,color:#111
style n13 fill:#beaed4,color:#111
style n14 fill:#fdc086,color:#111
style n17 fill:#ffff99,color:#111
style n18 fill:#ffff99,color:#111
style n19 fill:#fdc086,color:#111
style n26 fill:#fdc086,color:#111
style g1 stroke-dasharray:6 4
Diagram outlining the LRU eviction steps taken during map update.
LRU hash eviction during map update for BPF_MAP_TYPE_LRU_HASH and
variants. See the dot file source for kernel function name code references.
Map updates start from the oval in the top right "begin bpf_map_update()" and progress through the graph towards the bottom where the result may be either a successful update or a failure with various error codes. The key in the top right provides indicators for which locks may be involved in specific operations. This is intended as a visual hint for reasoning about how map contention may impact update operations, though the map type and flags may impact the actual contention on those locks, based on the logic described in the table above. For instance, if the map is created with type BPF_MAP_TYPE_LRU_PERCPU_HASH and flags BPF_F_NO_COMMON_LRU then all map properties would be per-cpu.