bpf: Fix 8-byte alignment of map values
Subsystems (6)
v2 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. All of them fault on misaligned addresses. FEAT_LSE2 relaxes that for LSE atomics that stay within a 16-byte block, and for LDAR/STLR only if SCTLR_EL1.nAA is set, which Linux does not do. 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 pads the lpm_trie key to a multiple of 8 bytes, like hashtab does.
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 "arm32 + patch 1" 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 + 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: devmap val at offset 52 -> 56 (arm64, size stays 64) and 28 -> 32 (arm32), and lpm_trie_node data[] at 24 (arm64) and 16 (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 LDAR/STLR behaviour with FEAT_LSE2 and the x86 split lock case come from the Arm ARM (SCTLR_EL1.nAA) and arch/x86/kernel/traps.c; I did not trigger them.
The lpm_trie bug was found with AI assistance while trying to verify the correctness of map value accesses with formal methods. Patches 2-4 and this cover letter were written with the help of an AI coding assistant (Claude Opus 5.5).
[1] https://lore.kernel.org/all/[email protected]/
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)". data[] is at offset 24 or 16 already and the annotation changed nothing (Alexei). Add a BUILD_BUG_ON() for that offset instead.
- 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.
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 | 5 +- kernel/bpf/hashtab.c | 2 +- kernel/bpf/lpm_trie.c | 19 ++++--- kernel/bpf/memalloc.c | 8 +-- .../bpf/prog_tests/map_value_align.c | 51 +++++++++++++++++++ .../selftests/bpf/progs/map_value_align.c | 48 +++++++++++++++++ 6 files changed, 121 insertions(+), 12 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 v2 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 v2 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. All of them raise an alignment fault on a misaligned address. FEAT_LSE2 relaxes that for LSE atomics that stay within a 16-byte block, and for LDAR/STLR only if SCTLR_EL1.nAA is set, which Linux does not do. 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").
Round data_size up to a multiple of 8 when computing the value offset and the node size, like hashtab does for keys. IPv4 nodes grow by 4 bytes, IPv6 nodes (data_size 16) are unchanged. Add a BUILD_BUG_ON() for the offset of data[], which the alignment of the value relies on.
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 patch was written with the help of an AI coding assistant (Claude Opus 5.5).
--- kernel/bpf/lpm_trie.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-)
kernel/bpf/lpm_trie.c +13 -6
@@ -286,7 +286,7 @@ static void *trie_lookup_elem(struct bpf_map *map, void *_key)if (!found)return NULL ; -return found->data + trie->data_size; +return found->data +round_up (trie->data_size,8 ); } static struct lpm_trie_node *lpm_trie_node_alloc(struct lpm_trie *trie,
@@ -302,7 +302,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 (node->data +round_up (trie->data_size,8 ), value, trie->map.value_size);return node;
@@ -597,8 +597,14 @@ 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 + +/* Allocate intermediate and leaf nodes from the same allocator. +* The key bytes are padded to a multiple of 8 bytes, because the +* verifier assumes that map values are 8-byte aligned. Objects from +* bpf_mem_alloc are 8-byte aligned, so data[] must be as well. +*/ +BUILD_BUG_ON (offsetof(struct lpm_trie_node , data) %8 ); + leaf_size =sizeof (struct lpm_trie_node ) + +round_up (trie->data_size,8 ) + trie->map.value_size; err =bpf_mem_alloc_init (&trie->ma, leaf_size, false);if (err)
@@ -766,8 +772,9 @@ 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 =sizeof (struct lpm_trie_node ) + +round_up (trie->data_size,8 ) + + 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 v2 2/4] bpf: Align lpm_trie map values to 8 bytes
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] bpf: non-standard multi-line comment style in trie_alloc() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] bpf: non-standard multi-line comment style in trie_alloc() --
commit 7745369351fba1841a655972ae45f1b4be10934b
Author: Tobias Philipp <[email protected]>
bpf: Align lpm_trie map values to 8 bytes
This commit rounds lpm_trie's data_size up to a multiple of 8 bytes when computing the value offset and node size so that map values are 8-byte aligned.
Quoted 4 lines
kernel/bpf/lpm_trie.c +0
-0
[ ... ]
kernel/bpf/lpm_trie.c static struct bpf_map *trie_alloc(union bpf_attr *attr) · line 604
Quoted 11 lines
kernel/bpf/lpm_trie.c +5
-2@@ -597,8 +597,14 @@ 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 + +/* Allocate intermediate and leaf nodes from the same allocator. +* The key bytes are padded to a multiple of 8 bytes, because the +* verifier assumes that map values are 8-byte aligned. Objects from +* bpf_mem_alloc are 8-byte aligned, so data[] must be as well. +*/
[Severity: Low]
This isn't a bug, but BPF multi-line comment style puts the opening /* on its own line before the comment text.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v2 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 a misaligned address. FEAT_LSE2 does not change that, because Linux does not set SCTLR_EL1.nAA. 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 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
kernel/bpf/devmap.c +4 -1
@@ -70,7 +70,10 @@ struct bpf_dtab_netdev {struct bpf_prog *xdp_prog;struct rcu_head rcu;unsigned int idx; -struct bpf_devmap_val val; +/* Returned to BPF programs as the map value, which the verifier +* assumes to be 8-byte aligned. +*/ +struct bpf_devmap_val val__aligned(8) ; };struct bpf_dtab {
Signature · 1 line
2.54.0 (Apple Git-157)
[email protected]
AI reviewRe: [PATCH bpf-next v2 3/4] bpf: Align devmap values to 8 bytes
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] bpf: non-standard multi-line comment style in struct bpf_dtab_netdev --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] bpf: non-standard multi-line comment style in struct bpf_dtab_netdev
--
commit b6749200cfd19f384e3c763bbc57d732deab6c99
Author: Tobias Philipp <[email protected]>
bpf: Align devmap values to 8 bytes
This commit aligns struct bpf_dtab_netdev::val to 8 bytes so that devmap values match the verifier's 8-byte map-value alignment assumption and avoid alignment faults on 64-bit load-acquire instructions.
Quoted 5 lines
kernel/bpf/devmap.c +0
-0
kernel/bpf/devmap.c struct bpf_dtab_netdev { · line 77
Quoted 9 lines
kernel/bpf/devmap.c +4
-1@@ -70,7 +70,10 @@ struct bpf_dtab_netdev {struct bpf_prog *xdp_prog;struct rcu_head rcu;unsigned int idx; -struct bpf_devmap_val val; +/* Returned to BPF programs as the map value, which the verifier +* assumes to be 8-byte aligned. +*/ +struct bpf_devmap_val val__aligned(8) ; };
[Severity: Low]
This isn't a bug, but BPF multi-line comments place the opening /* on its own line with the comment text starting on the next line.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
PATCH v2 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)