bpf: Fix 8-byte alignment of map values
Subsystems (6)
v3 cover bpf: Fix 8-byte alignment of map values
The verifier checks the alignment of BPF_DW atomics and 64-bit load-acquire/store-release on PTR_TO_MAP_VALUE only against the offset within the value. It assumes that the value itself is 8-byte aligned. That does not hold for all map types. Address of the value mod 8, as measured on bpf-next (see Testing below):
64-bit 32-bit lpm_trie, key_size 8 (IPv4) 4 0 (by accident) lpm_trie, key_size 20 (IPv6) 0 4 hash, rhash (BPF_F_NO_PREALLOC) 0 4 devmap, devmap_hash 4 4 (harmless, see patch 3)
On arm64 the JIT emits LSE atomics or LDXR/STXR loops, LDAR and STLR for these instructions. They fault on misaligned addresses; with FEAT_LSE2, LSE atomics, LDAR and STLR only when the access crosses a 16-byte boundary. On arm32 the interpreter uses atomic64_*(), i.e. LDREXD/STREXD, which require 8-byte alignment. On x86-64 a locked 8-byte access at 4 mod 8 that crosses a cache line is a split lock, which is fatal in kernel mode on CPUs with split lock detection. None of these faults is fixed up.
Patch 1 is Felix Fietkau's fix for bpf_mem_alloc on 32-bit [1]. It was posted in July and is not applied yet. It is included unchanged apart from a rebase, because patch 2 depends on it. It fixes the hash and rhash rows and the node alignment of lpm_trie on 32-bit. The Sashiko review of that posting points out a pre-existing 8-byte load of the 4-byte percpu pointer in the bpf_per_cpu_ptr()/bpf_this_cpu_ptr() fixup on 32-bit. Patch 1 neither causes nor fixes it, and this series does not address it. Among the 32-bit JITs only x86 supports kfuncs, so only x86-32 can reach it. Using BPF_SIZEOF(void *) for that load would fix it.
Patch 2 places the lpm_trie value at the next 8-byte boundary after the key and shrinks prefixlen and flags to u16, so that nodes don't grow.
Patch 3 aligns the devmap value.
Patch 4 adds a selftest that checks the address of the value returned by bpf_map_lookup_elem() for lpm_trie, hash and devmap. It executes no instruction that needs alignment, so on an affected kernel it fails instead of crashing.
Patches 1 and 2 have to be applied together: on 32-bit, either one alone misaligns the IPv4 lpm_trie value (see "+ patch 1" and "+ patch 2" in the table below), and both commit messages say so. I kept them separate to keep Felix's authorship; they can be squashed if that is preferred.
The other map types that hand a value pointer to programs return 8-byte aligned values. cpumap has its value at offset 20 on 32-bit, but the verifier does not let programs look it up.
Testing, in disposable QEMU VMs:
- arm64, defconfig + selftests/bpf config, QEMU with HVF on an Apple M-series host (FEAT_LSE2): map_value_align fails on bpf-next (lpm_value_align: 4, devmap_value_align: 4) and passes with the series. With the series, test_maps passes the lpm_trie basic_ops, batch_ops and get_next_key tests and the hash and array tests, and test_progs passes pinning_devmap_reuse and xdp_devmap_attach subtests 2 and 3.
- arm32, multi_v7_defconfig + BPF_SYSCALL, QEMU virt with Cortex-A15 (TCG): test_progs is hard to cross-build for armhf, so a small static program does the same check as the selftest: an XDP program looks up each map and stores the value pointer in an array map. Address mod 8:
lpm IPv4 lpm IPv6 hash rhash devmap
arm32 bpf-next 0 4 4 4 4
arm32 + patch 1 4 0 0 0 4
arm32 + patch 2 4 4 4 4 4
arm32 + patches 1-4 0 0 0 0 0
arm64 bpf-next 4 0 0 0 4
arm64 + patches 1-4 0 0 0 0 0
- pahole matches the layouts in the commit messages: lpm_trie_node data[] moves from 24 to 20 (arm64) and from 16 to 12 (arm32), and devmap val from 52 to 56 (arm64, size stays 64) and from 28 to 32 (arm32).
- W=1 builds of the four touched kernel files on x86_64, arm64 and arm32 produce no warnings.
Not tested: runtime on x86_64; test_progs on arm32; selftests that need CONFIG_FTRACE or bpf_testmod, which my configuration lacked. That includes xdp_devmap_attach subtests 1 and 4 and the bpf_obj_new and percpu allocation tests; they failed to load in the same way with and without the series. Patch 1 does not change anything on 64-bit. The x86 split lock case comes from arch/x86/kernel/traps.c; I did not trigger it.
The lpm_trie bug was found with AI assistance while trying to verify the correctness of map value accesses with formal methods. Patches 3-4, the commit messages and this cover letter were written with the help of an AI coding assistant (Claude Opus 5.5). The code of patch 2 follows Alexei's suggestion.
[1] https://lore.kernel.org/all/[email protected]/
Changes in v3:
- Patch 2: place the value at round_up(offsetof(data) + data_size, 8) and make prefixlen and flags u16, so that nodes don't grow and move to a larger kmalloc bucket. This drops the BUILD_BUG_ON(), the four round_up() calls and the comment that was not in kernel style (Alexei).
- Patch 3: use a single-line comment (Sashiko).
- Correct the FEAT_LSE2 statement for LDAR/STLR in this cover letter and in patches 2 and 3 (Alexei).
Changes in v2:
- Target bpf-next (Alexei).
- Fix the 32-bit node misalignment at its root in bpf_mem_alloc by including Felix's patch. v1 rounded data_size up on top of a node at 4 mod 8 on 32-bit and so misaligned the IPv4 value there, which is aligned today (Alexei).
- Drop "data[] __aligned(8)", which changed nothing (Alexei).
- Add the devmap fix (Alexei).
- Add a selftest (Alexei).
- Correct the commit message, which claimed that the IPv4 value is at 4 mod 8 on all architectures.
v2: https://lore.kernel.org/bpf/[email protected]/
v1: https://lore.kernel.org/bpf/[email protected]/
Felix Fietkau (1):
bpf: Fix alignment of memory allocator objects on 32-bit archs
Tobias Philipp (3):
bpf: Align lpm_trie map values to 8 bytes
bpf: Align devmap values to 8 bytes selftests/bpf: Check that map values are 8-byte aligned
kernel/bpf/devmap.c | 3 +- kernel/bpf/hashtab.c | 2 +- kernel/bpf/lpm_trie.c | 22 +++++--- kernel/bpf/memalloc.c | 8 +-- .../bpf/prog_tests/map_value_align.c | 51 +++++++++++++++++++ .../selftests/bpf/progs/map_value_align.c | 48 +++++++++++++++++ 6 files changed, 120 insertions(+), 14 deletions(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/map_value_align.c create mode 100644 tools/testing/selftests/bpf/progs/map_value_align.c
base-commit: a58375b858fac35afb78a3dd68ad6a19c01799eb
Signature · 1 line
2.54.0 (Apple Git-157)
PATCH v3 1/4 bpf: Fix alignment of memory allocator objects on 32-bit archs
From: Felix Fietkau <[email protected]>
The BPF memory allocator prefixes each object with a header that holds struct llist_node while the object sits on a free list, and a pointer to the owning bpf_mem_cache while it is allocated. The header size was sizeof(struct llist_node), so on 32-bit architectures the memory handed out was offset by 4 bytes from the 8-byte aligned kmalloc allocation.
The verifier assumes that allocated objects are 8-byte aligned and allows BPF_DW atomic instructions on their u64 fields, e.g. on values of non-preallocated hash maps, objects from bpf_obj_new() and local storage. On arm32 the JIT does not implement atomics, and the interpreter executes them via atomic64_*(), which are implemented with LDREXD/STREXD on ARMv6K and later. Those instructions require 8-byte aligned addresses; a misaligned address raises an alignment fault and crashes the kernel.
Pad the header to 8 bytes to preserve the alignment provided by kmalloc. Store the percpu pointer of percpu objects at the new header offset instead of assuming the header is pointer-sized, and update the copy of the header size used by the hash map memory usage accounting.
[tphilipp: rebased onto bpf-next, adjusted context in hashtab.c.
Local storage no longer uses bpf_mem_alloc in bpf-next. On 32-bit this patch moves an IPv4 lpm_trie value from 0 to 4 mod 8; the next patch fixes that, so both have to be applied together.]
--- kernel/bpf/hashtab.c | 2 +- kernel/bpf/memalloc.c | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-)
kernel/bpf/hashtab.c +1 -1
@@ -2594,7 +2594,7 @@ static u64 htab_map_mem_usage(const struct bpf_map *map)else if (!lru) usage +=sizeof (struct htab_elem *) *num_possible_cpus (); }else { -#define LLIST_NODE_SZ sizeof(struct llist_node) +#define LLIST_NODE_SZ ALIGN(sizeof(struct llist_node), 8) num_entries =bpf_map_sum_elem_count (map); usage += (htab->elem_size +LLIST_NODE_SZ ) * num_entries;
kernel/bpf/memalloc.c +4 -4
@@ -33,7 +33,7 @@* Every allocated objected is padded with extra 8 bytes that contains * struct llist_node. */ -#define LLIST_NODE_SZ sizeof(struct llist_node) +#define LLIST_NODE_SZ ALIGN(sizeof(struct llist_node), 8)#define BPF_MEM_ALLOC_SIZE_MAX 4096
@@ -148,7 +148,7 @@ static struct llist_node notrace *__llist_del_first(struct llist_head *head)static void *__alloc (struct bpf_mem_cache *c,int node,gfp_t flags) {if (c->percpu_size) { -void __percpu **obj =kmalloc_node (c->percpu_size, flags, node); +void *obj =kmalloc_node (c->percpu_size, flags, node);void __percpu *pptr =__alloc_percpu_gfp (c->unit_size,8 , flags);if (!obj || !pptr) {
@@ -156,7 +156,7 @@ static void *__alloc(struct bpf_mem_cache *c, int node, gfp_t flags)kfree (obj);return NULL ; } - obj[1 ] = pptr; + *(void __percpu **)(obj +LLIST_NODE_SZ ) = pptr;return obj; }
@@ -262,7 +262,7 @@ static void alloc_bulk(struct bpf_mem_cache *c, int cnt, int node, bool atomic)static void free_one (void *obj,bool percpu) {if (percpu) -free_percpu (((void __percpu **)obj)[1 ]); +free_percpu (*(void __percpu **)(obj +LLIST_NODE_SZ ));kfree (obj); }
Signature · 1 line
2.54.0 (Apple Git-157)
PATCH v3 2/4 bpf: Align lpm_trie map values to 8 bytes
In reply to Tobias PhilippThe verifier checks the alignment of PTR_TO_MAP_VALUE accesses only against the offset within the value and assumes that the value itself starts on an 8-byte boundary. It accepts BPF_DW atomics and 64-bit load-acquire/store-release at 8-byte aligned offsets of a value.
lpm_trie stores the value directly behind the key bytes, at node->data + trie->data_size, where data_size is key_size - 4 and can be anything from 1 to 256. Nodes come from bpf_mem_alloc, which returns 8-byte aligned objects (on 32-bit architectures since the previous patch), and data[] is at offset 24 (64-bit) or 16 (32-bit) in the node. So the value is 8-byte aligned only if data_size is a multiple of 8. For an IPv4 trie (key_size 8, data_size 4) it is 4 mod 8.
On arm64 the JIT emits LSE atomics or LDXR/STXR loops, LDAR and STLR for these instructions. They raise an alignment fault on a misaligned address; on CPUs with FEAT_LSE2, LSE atomics, LDAR and STLR only do so when the access crosses a 16-byte boundary. The fault is not fixed up. This oops is from a 64-bit atomic add at offset 8 of an IPv4 lpm_trie value, which crosses a 16-byte boundary (Linux 7.3.5 under QEMU, HVF on an FEAT_LSE2 host):
Mem abort info:
ESR = 0x0000000096000021
FSC = 0x21: alignment fault
Internal error: Oops: 0x96000021 [#1] SMP
pc : bpf_prog_cc9155b98965fc5e+0x64/0x90
Call trace:
bpf_prog_cc9155b98965fc5e+0x64/0x90 (P)
bpf_dispatcher_xdp_func+0x14/0x28
bpf_test_run+0x11c/0x360
bpf_prog_test_run_xdp+0x358/0x548On x86-64 a locked 8-byte access at 4 mod 8 is a split lock when it crosses a cache line, which is fatal in kernel mode on CPUs with split lock detection ("Split lock detected").
Place the value at the next 8-byte boundary after the key bytes. So that nodes don't grow, shrink prefixlen and flags to u16: prefixlen is at most 2048 and flags has one bit. data[] moves to offset 20 (64-bit) or 12 (32-bit). Bytes that bpf_mem_alloc asks from kmalloc on 64-bit:
data_size value_size before after --------- ---------- ------ ----- 4 28 64 60 4 60 96 92 16 16 64 64 20 12 64 60
This patch and the previous one have to be applied together. Without the previous patch, nodes are at 4 mod 8 on 32-bit architectures and this patch misaligns the IPv4 value there, which is aligned today by accident. Without this patch, the previous one misaligns it.
This was found with AI assistance while trying to verify the correctness of map value accesses with formal methods. The code follows Alexei's suggestion; the commit message was written with the help of an AI coding assistant (Claude Opus 5.5).
--- kernel/bpf/lpm_trie.c | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-)
kernel/bpf/lpm_trie.c +14 -8
@@ -25,8 +25,8 @@ struct lpm_trie_node;struct lpm_trie_node {struct lpm_trie_node __rcu *child[2 ]; -u32 prefixlen; -u32 flags; +u16 prefixlen; +u16 flags;u8 data[]; };
@@ -40,6 +40,12 @@ struct lpm_trie {rqspinlock_t lock; }; +/* The verifier assumes that map values are 8-byte aligned */ +static size_t trie_value_off (const struct lpm_trie *trie) +{ +return round_up (offsetof(struct lpm_trie_node , data) + trie->data_size,8 ); +} +/* This trie implements a longest prefix match algorithm that can be used to * match IP addresses to a stored set of ranges. *
@@ -286,7 +292,7 @@ static void *trie_lookup_elem(struct bpf_map *map, void *_key)if (!found)return NULL ; -return found->data + trie->data_size; +return (void *)found +trie_value_off (trie); } static struct lpm_trie_node *lpm_trie_node_alloc(struct lpm_trie *trie,
@@ -302,7 +308,7 @@ static struct lpm_trie_node *lpm_trie_node_alloc(struct lpm_trie *trie, node->flags =0 ;if (value) -memcpy (node->data + trie->data_size, value, +memcpy ((void *)node +trie_value_off (trie), value, trie->map.value_size);return node;
@@ -557,6 +563,8 @@ static long trie_delete_elem(struct bpf_map *map, void *_key)#define LPM_DATA_SIZE_MAX 256#define LPM_DATA_SIZE_MIN 1 +static_assert (LPM_DATA_SIZE_MAX *8 <=U16_MAX ); +#define LPM_VAL_SIZE_MAX (KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \ sizeof(struct lpm_trie_node))#define LPM_VAL_SIZE_MIN 1
@@ -598,8 +606,7 @@ static struct bpf_map *trie_alloc(union bpf_attr *attr)raw_res_spin_lock_init (&trie->lock);/* Allocate intermediate and leaf nodes from the same allocator */ - leaf_size =sizeof (struct lpm_trie_node ) + trie->data_size + - trie->map.value_size; + leaf_size =trie_value_off (trie) + trie->map.value_size; err =bpf_mem_alloc_init (&trie->ma, leaf_size, false);if (err) goto free_out;
@@ -766,8 +773,7 @@ static u64 trie_mem_usage(const struct bpf_map *map) struct lpm_trie *trie = container_of(map, struct lpm_trie, map);u64 elem_size; - elem_size =sizeof (struct lpm_trie_node ) + trie->data_size + - trie->map.value_size; + elem_size =trie_value_off (trie) + trie->map.value_size;return elem_size *READ_ONCE (trie->n_entries); }
Signature · 1 line
2.54.0 (Apple Git-157)
[email protected]
AI reviewRe: [PATCH bpf-next v3 2/4] bpf: Align lpm_trie map values to 8 bytes
TL;DR: Commit message only: the claim that lpm_trie nodes don't grow looks wrong for data sizes with remainder 5-7 mod 8, where nodes get 1-3 bytes bigger, possibly moving to a larger kmalloc…
Quoted 1 line
bpf: Align
lpm_triemap values to 8 bytes
TL;DR: Commit message only: the claim that lpm_trie nodes don't grow looks wrong for data sizes with remainder 5-7 mod 8, where nodes get 1-3 bytes bigger, possibly moving to a larger kmalloc bucket. Code looks correct.
Quoted 10 lines
Place the value at the next 8-byte boundary after the key bytes. So that nodes don't grow, shrink prefixlen and flags to u16: prefixlen is at most 2048 and flags has one bit. data[] moves to offset 20 (64-bit) or 12 (32-bit). Bytes that
bpf_mem_allocasks from kmalloc on 64-bit:data_size value_size before after --------- ---------- ------ ----- 4 28 64 60 4 60 96 92 16 16 64 64 20 12 64 60
Is the statement "So that nodes don't grow" accurate for all key sizes?
The bytes in front of the value change from sizeof(struct lpm_trie_node) + data_size (24 + ds on 64-bit, 16 + ds on 32-bit) to round_up(offsetof(struct lpm_trie_node, data) + data_size, 8), which is round_up(20 + ds, 8) or round_up(12 + ds, 8).
The difference is (padding - 4), with padding between 0 and 7. When data_size % 8 is 5, 6 or 7, the node becomes 3, 2 or 1 bytes bigger on both 64-bit and 32-bit. For example, with data_size 6 (an IPv4 address plus a port), 24 + 6 = 30 becomes round_up(26, 8) = 32.
The growth can also move a node into a larger kmalloc bucket. On 64-bit with data_size 5 and value_size 27, the request is 24 + 5 + 27 + 8 = 64 before and 32 + 27 + 8 = 67 after, so the node moves from kmalloc-64 to kmalloc-96. The table only lists data_size 4, 16 and 20, where nodes shrink or stay the same.
The code looks correct, so this is about the rationale. Could the wording say that the u16 shrink keeps the alignment padding to at most 3 bytes and makes IPv4 nodes 4 bytes smaller?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45888065586
PATCH v3 3/4 bpf: Align devmap values to 8 bytes
In reply to Tobias Philippdev_map_lookup_elem() and dev_map_hash_lookup_elem() return &obj->val as the map value. In struct bpf_dtab_netdev, val follows "unsigned int idx" and is at offset 52 on 64-bit and 28 on 32-bit architectures, so it is only 4-byte aligned.
devmap is read-only for BPF programs, but the verifier assumes that map values are 8-byte aligned and accepts a 64-bit load-acquire at offset 0 of a struct bpf_devmap_val value on 64-bit architectures. The arm64 JIT emits LDAR for it, which raises an alignment fault on CPUs without FEAT_LSE2. The fault is not fixed up.
Mark val as __aligned(8). On 64-bit it moves to offset 56 and the size of struct bpf_dtab_netdev stays 64 bytes. On 32-bit the verifier rejects 64-bit load-acquire, so the misaligned value is harmless there. Aligning it anyway keeps all map values 8-byte aligned and grows the struct from 36 to 40 bytes. Entries are allocated with kmalloc, which provides at least 8-byte alignment.
This patch was written with the help of an AI coding assistant (Claude Opus 5.5).
--- kernel/bpf/devmap.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/bpf/devmap.c +2 -1
@@ -70,7 +70,8 @@ struct bpf_dtab_netdev {struct bpf_prog *xdp_prog;struct rcu_head rcu;unsigned int idx; -struct bpf_devmap_val val; +/* The verifier assumes that map values are 8-byte aligned */ +struct bpf_devmap_val val__aligned(8) ; };struct bpf_dtab {
Signature · 1 line
2.54.0 (Apple Git-157)
PATCH v3 4/4 selftests/bpf: Check that map values are 8-byte aligned
In reply to Tobias PhilippThe verifier assumes that map values are 8-byte aligned. Add a test that looks up an IPv4 lpm_trie value, a BPF_F_NO_PREALLOC hash value and a devmap value from an XDP program, stores the returned addresses in global variables and checks them in user space.
The program does not execute any instruction that requires alignment, so on an affected kernel the test fails instead of crashing it. Without the previous patches the lpm_trie and devmap checks fail on 64-bit architectures, and the hash and devmap checks fail on 32-bit architectures.
This patch was written with the help of an AI coding assistant (Claude Opus 5.5).
--- .../bpf/prog_tests/map_value_align.c | 51 +++++++++++++++++++ .../selftests/bpf/progs/map_value_align.c | 48 +++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/map_value_align.c create mode 100644 tools/testing/selftests/bpf/progs/map_value_align.c
tools/testing/selftests/bpf/prog_tests/map_value_align.c new file +51 -0
@@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0 +#include <test_progs.h> +#include <network_helpers.h> +#include "map_value_align.skel.h" + +#define IFINDEX_LO 1 + +/* The verifier assumes that map values are 8-byte aligned */ +void test_map_value_align (void ) +{ +LIBBPF_OPTS (bpf_test_run_opts, topts, + .data_in = &pkt_v4, + .data_size_in = sizeof(pkt_v4), + ); +struct bpf_devmap_val dval = { .ifindex =IFINDEX_LO }; +struct {__u32 prefixlen, data; } lkey = { .prefixlen =32 }; +struct map_value_align *skel; +__u64 val =0 ; +__u32 key =0 ; +int err; + + skel =map_value_align__open_and_load (); +if (!ASSERT_OK_PTR (skel,"open_and_load" )) +return ; + + err =bpf_map__update_elem (skel->maps.lpm, &lkey,sizeof (lkey), + &val,sizeof (val),BPF_ANY ); +if (!ASSERT_OK (err,"lpm_update" )) + goto out; + err =bpf_map__update_elem (skel->maps.hash, &key,sizeof (key), + &val,sizeof (val),BPF_ANY ); +if (!ASSERT_OK (err,"hash_update" )) + goto out; + err =bpf_map__update_elem (skel->maps.devmap, &key,sizeof (key), + &dval,sizeof (dval),BPF_ANY ); +if (!ASSERT_OK (err,"devmap_update" )) + goto out; + + err =bpf_prog_test_run_opts (bpf_program__fd (skel->progs.lookup), &topts); +if (!ASSERT_OK (err,"test_run" )) + goto out; + +ASSERT_NEQ (skel->bss->lpm_addr,0 ,"lpm_lookup" ); +ASSERT_EQ (skel->bss->lpm_addr &7 ,0 ,"lpm_value_align" ); +ASSERT_NEQ (skel->bss->hash_addr,0 ,"hash_lookup" ); +ASSERT_EQ (skel->bss->hash_addr &7 ,0 ,"hash_value_align" ); +ASSERT_NEQ (skel->bss->devmap_addr,0 ,"devmap_lookup" ); +ASSERT_EQ (skel->bss->devmap_addr &7 ,0 ,"devmap_value_align" ); +out: +map_value_align__destroy (skel); +}
tools/testing/selftests/bpf/progs/map_value_align.c new file +48 -0
48 lines not on this page · raw message
Signature · 1 line
2.54.0 (Apple Git-157)