Skip to contentSkip to conversation

bpf: Use kmalloc for local storage if possible

PATCH In review Emil Tsalapatis 4 participants 12 messages Nov 24

Subsystems (7)
lore
Share & tools
lore

Emil Tsalapatis

author reviewer
#0 lore raw

cover bpf: Use kmalloc for local storage if possible

Local storage currently only goes through kmalloc_nolock() to allocate new memory. This is needlessly restrictive, because the calling context may allow for spinning on the zone lock, or even sleeping. Exclusively using kmalloc_nolock() has the downside that the call may fail where a different variant would succeed, e.g., under heavy contention on the ZONE_NORMAL zone lock combined with high hugepage usage in the system draining ZONE_DMA32 below the watermark where a ZONE_NORMAL allocation can allocate from it. This scenario has been observed in production environments.

Add more granular context checking during local storage allocation, and do either a GFP_KERNEL kmalloc sleepable allocation, a GFP_NOWAIT nonsleepable kmalloc allocation, or a kmalloc_nolock() allocation. This requires plumbing the aux metadata of the program through the local data allocation helpers, and inspecting at runtime the context's preemption/nmi state along with the sleepability of the call.

The logic is effectively:

  if (aux && bpf_prog_can_sleep(aux->prog)) {
          ptr = kzalloc(size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
  } else if (IS_ENABLED(CONFIG_PREEMPT_COUNT) && can_spin_in_alloc() &&
             size <= KMALLOC_MAX_CACHE_SIZE) {
          ptr = kmalloc(size, GFP_NOWAIT | __GFP_NOMEMALLOC | __GFP_ZERO);
          if (!ptr)
                  ptr = kmalloc_nolock(size, __GFP_ZERO, NUMA_NO_NODE);
  } else {
          ptr = kmalloc_nolock(size, __GFP_ZERO, NUMA_NO_NODE);
  }

Emil Tsalapatis (4):
bpf: Add call for selecting kmalloc or kmalloc_nolock at call time
bpf: Plumb local storage context
bpf: Add sleepable local storage
selftests/bpf: Test kmalloc variant selection for task storage

 include/linux/bpf.h                           |   8 ++
 include/linux/bpf_local_storage.h             |   3 +-
 kernel/bpf/bpf_cgrp_storage.c                 |   9 +-
 kernel/bpf/bpf_inode_storage.c                |   9 +-
 kernel/bpf/bpf_local_storage.c                |  53 ++++++--
 kernel/bpf/bpf_task_storage.c                 |   9 +-
 kernel/bpf/syscall.c                          |  27 +++-
 net/core/bpf_sk_storage.c                     |  17 ++-
 .../bpf/prog_tests/task_storage_sleepable.c   |  94 +++++++++++++
 .../bpf/progs/task_storage_sleepable.c        | 126 ++++++++++++++++++
 10 files changed, 319 insertions(+), 36 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/task_storage_sleepable.c
 create mode 100644 tools/testing/selftests/bpf/progs/task_storage_sleepable.c
Signature · 1 line
2.52.1
author reviewer
#1 lore raw

PATCH 1/4 bpf: Add call for selecting kmalloc or kmalloc_nolock at call time

Certain parts of the BPF runtime like task-locl storage call kmalloc_nolock by default, even when the context within which they are called could use regular (nonsleepable) kmalloc. Add a helper for determining whether we can try to satisfy the allocation with a regular kmalloc, and make a call to kmalloc with GFP_NOWAIT when possible before resorting to kmalloc_nolock.

Spinning on the lock instead of only doing kmalloc_nolock avoids unnecessary allocation failures. Using trylock instead of committing to spinning during allocation risks failures under contention in the critical path. Normally, kmalloc_nolock falls back to ZONE_DMA32 that is in practice never contended, but the zone may be below the low watermark and fail to allocate. This is the case, e.g., in systems with a large amount of hugepages in use (hugepages also allocate form ZONE_DMA32 when necessary, lowering it to below the watermark).

Make both calls in succession to maximize the possibility of success. kmalloc_nolock() tries buckets larger than the requested size's when necesary, which kmalloc() does not. The two calls are therefore complementary, and we cannot call just kmalloc() when it is available.

---
 include/linux/bpf.h            |  3 +++
 kernel/bpf/bpf_local_storage.c |  6 ++----
 kernel/bpf/syscall.c           | 27 +++++++++++++++++++++++++--
 3 files changed, 30 insertions(+), 6 deletions(-)
include/linux/bpf.h +3 -0
index a5ad08b7937c7..5565a735ae7ce 100644
@@ -3037,6 +3037,9 @@ struct page *bpf_alloc_page(int nid, bool sleepable);
 int bpf_alloc_pages(int nid, unsigned long nr_pages,
 		    struct llist_head *pages, bool sleepable);
 void bpf_free_pages(struct llist_head *pages);
+
+void *bpf_map_kmalloc_maylock(const struct bpf_map *map, size_t size, gfp_t flags);
+
 #ifdef CONFIG_MEMCG
 void bpf_map_memcg_enter(const struct bpf_map *map, struct mem_cgroup **old_memcg,
 			 struct mem_cgroup **new_memcg);
kernel/bpf/bpf_local_storage.c +2 -4
index b12fcec47ffa0..bd79754a1e2fd 100644
@@ -75,8 +75,7 @@ bpf_selem_alloc(struct bpf_local_storage_map *smap, void *owner,
 	if (mem_charge(smap, owner, smap->elem_size))
 		return NULL;
 
-	selem = bpf_map_kmalloc_nolock(&smap->map, smap->elem_size,
-				       __GFP_ZERO, NUMA_NO_NODE);
+	selem = bpf_map_kmalloc_maylock(&smap->map, smap->elem_size, __GFP_ZERO);
 
 	if (selem) {
 		RCU_INIT_POINTER(SDATA(selem)->smap, smap);
@@ -512,8 +511,7 @@ int bpf_local_storage_alloc(void *owner,
 	if (err)
 		return err;
 
-	storage = bpf_map_kmalloc_nolock(&smap->map, sizeof(*storage),
-					 __GFP_ZERO, NUMA_NO_NODE);
+	storage = bpf_map_kmalloc_maylock(&smap->map, sizeof(*storage), __GFP_ZERO);
 	if (!storage) {
 		err = -ENOMEM;
 		goto uncharge;
kernel/bpf/syscall.c +25 -2
index ec8e787929112..4c72b05e11eb0 100644
@@ -597,15 +597,38 @@ static void bpf_map_release_memcg(struct bpf_map *map)
 }
 #endif
 
-static bool can_alloc_pages(void)
+static bool can_spin_in_alloc(void)
 {
 	return preempt_count() == 0 && !irqs_disabled() &&
 		!IS_ENABLED(CONFIG_PREEMPT_RT);
 }
 
+void *bpf_map_kmalloc_maylock(const struct bpf_map *map, size_t size, gfp_t flags)
+{
+	const gfp_t nolock_flags = __GFP_ACCOUNT | __GFP_ZERO |
+				   __GFP_NOWARN | __GFP_NOMEMALLOC;
+	struct mem_cgroup *memcg, *old_memcg;
+	void *ptr = NULL;
+
+	bpf_map_memcg_enter(map, &old_memcg, &memcg);
+	if (IS_ENABLED(CONFIG_MEMCG))
+		flags |= __GFP_ACCOUNT;
+
+	/* Only try the spinning allocation when preemption disables are tracked. */
+	if (IS_ENABLED(CONFIG_PREEMPT_COUNT) && can_spin_in_alloc() &&
+	    size <= KMALLOC_MAX_CACHE_SIZE && !(flags & ~nolock_flags))
+		ptr = kmalloc(size, flags | GFP_NOWAIT | __GFP_NOMEMALLOC);
+	/* Allocation failed or kmalloc_nolock()-only context. */
+	if (!ptr)
+		ptr = kmalloc_nolock(size, flags, NUMA_NO_NODE);
+
+	bpf_map_memcg_exit(old_memcg, memcg);
+	return ptr;
+}
+
 struct page *bpf_alloc_page(int nid, bool sleepable)
 {
-	if (!sleepable || !can_alloc_pages())
+	if (!sleepable || !can_spin_in_alloc())
 		return alloc_pages_nolock(__GFP_ACCOUNT, nid, 0);
 
 	return alloc_pages_node(nid,
Signature · 1 line
2.52.1
#2 lore raw

Re: [PATCH bpf-next v1 1/4] bpf: Add call for selecting kmalloc or kmalloc_nolock at call time

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [Critical] bpf: missing dcache flush in…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [Critical] bpf: missing dcache flush in __bpf_alloc_page() [1] --

commit 761d9aaa5b4ddd842253567eefeb0a2ef78a0aa0
Author: Emil Tsalapatis <[email protected]>

bpf: Add call for selecting kmalloc or kmalloc_nolock at call time

This commit adds bpf_map_kmalloc_maylock() to attempt a non-sleeping kmalloc() when spinning is safe before falling back to kmalloc_nolock(), and switches BPF local storage allocations to use it.

Quoted 4 lines
kernel/bpf/syscall.c +0 -0
index ec8e787929112..4c72b05e11eb0 100644

[ ... ]

kernel/bpf/syscall.c void *bpf_map_kmalloc_maylock(const struct bpf_map *map, size_t size, gfp_t flag · line 631

Quoted 7 lines
kernel/bpf/syscall.c +1 -1
@@ -627,5 +627,5 @@ void *bpf_map_kmalloc_maylock(const struct bpf_map *map, size_t size, gfp_t flag
 struct page *bpf_alloc_page(int nid, bool sleepable)
 {
-	if (!sleepable || !can_alloc_pages())
+	if (!sleepable || !can_spin_in_alloc())
 		return alloc_pages_nolock(__GFP_ACCOUNT, nid, 0);
 

[Severity: Critical]
This problem wasn't introduced by this patch, but does bpf_alloc_page() miss a dcache flush on cache-aliasing architectures [1]?

Both alloc_pages_nolock() and alloc_pages_node(..., __GFP_ZERO, ...) zero the page through the kernel linear mapping, leaving the zeroed lines in the CPU data cache without flushing them to main memory. When user space subsequently mmaps the BPF map or arena page at an aliasing virtual address, the CPU can bypass those dirty cache lines and read stale data from physical memory, disclosing uninitialized kernel memory to user space.

[1] https://sashiko.dev/#/bug/linux-f9f23bef-4238-4cdc-90e6-85c0f416ca5b

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

Re: [PATCH bpf-next v1 1/4] bpf: Add call for selecting kmalloc or kmalloc_nolock at call time

In reply to Emil Tsalapatis

Review

Quoted 4 lines · Emil Tsalapatis
(quoted diff) +4 -0
+	/* Only try the spinning allocation when preemption disables are tracked. */
+	if (IS_ENABLED(CONFIG_PREEMPT_COUNT) && can_spin_in_alloc() &&
+	    size <= KMALLOC_MAX_CACHE_SIZE && !(flags & ~nolock_flags))
+		ptr = kmalloc(size, flags | GFP_NOWAIT | __GFP_NOMEMALLOC);

It works, but I after a bit of brainstorming the following might be a better fix, since it will address the root cause:
Pls run it by Vlastimil, Harry, Sebastian.

mm/page_alloc.c +20 -2
index 2fef409..4368ab5 100644
@@ -2536,6 +2536,24 @@ __rmqueue(struct zone *zone, unsigned int order, int migratetype,
 	return NULL;
 }
 
+static DEFINE_WAIT_OVERRIDE_MAP(zone_nolock_map, LD_WAIT_CONFIG);
+
+/*
+ * zone->lock is always held with IRQs disabled. A caller that runs with IRQs
+ * enabled is not nested inside of it, so it can wait for the owner.
+ */
+static bool zone_lock_nolock(struct zone *zone, unsigned long *flags)
+{
+	if (IS_ENABLED(CONFIG_PREEMPT_RT) || irqs_disabled() || in_nmi())
+		return spin_trylock_irqsave(&zone->lock, *flags);
+
+	/* The caller may hold a raw_spinlock_t. */
+	lock_map_acquire_try(&zone_nolock_map);
+	spin_lock_irqsave(&zone->lock, *flags);
+	lock_map_release(&zone_nolock_map);
+	return true;
+}
+
 /*
  * Obtain a specified number of elements from the buddy allocator, all under
  * a single hold of the lock, for efficiency.  Add them to the supplied list.
@@ -2550,7 +2568,7 @@ static int rmqueue_bulk(struct zone *zone, unsigned int order,
 	int i;
 
 	if (unlikely(alloc_flags & ALLOC_NOLOCK)) {
-		if (!spin_trylock_irqsave(&zone->lock, flags))
+		if (!zone_lock_nolock(zone, &flags))
 			return 0;
 	} else {
 		spin_lock_irqsave(&zone->lock, flags);
@@ -3237,7 +3255,7 @@ struct page *rmqueue_buddy(struct zone *preferred_zone, struct zone *zone,
 	do {
 		page = NULL;
 		if (unlikely(alloc_flags & ALLOC_NOLOCK)) {
-			if (!spin_trylock_irqsave(&zone->lock, flags))
+			if (!zone_lock_nolock(zone, &flags))
 				return NULL;
 		} else {
 			spin_lock_irqsave(&zone->lock, flags);

pw-bot: cr

#4 lore raw

Re: [PATCH bpf-next v1 1/4] bpf: Add call for selecting kmalloc or kmalloc_nolock at call time

In reply to Emil Tsalapatis
TL;DR: - Mixing kmalloc() and kmalloc_nolock() local storage objects may cause false kmemleak reports of live objects - Unconfirmed: asks for justification that the run-time context test excludes…
Quoted 1 line

bpf: Add call for selecting kmalloc or kmalloc_nolock at call time

TL;DR:
- Mixing kmalloc() and kmalloc_nolock() local storage objects may cause false kmemleak reports of live objects
- Unconfirmed: asks for justification that the run-time context test excludes NMI and allocator-internal contexts

Quoted 3 lines
kernel/bpf/syscall.c +0 -0

[ ... ]

Quoted 8 lines
kernel/bpf/syscall.c +8 -0
+void *bpf_map_kmalloc_maylock(const struct bpf_map *map, size_t size, gfp_t flags)
+{
+	const gfp_t nolock_flags = __GFP_ACCOUNT | __GFP_ZERO |
+				   __GFP_NOWARN | __GFP_NOMEMALLOC;
+	struct mem_cgroup *memcg, *old_memcg;
+	void *ptr = NULL;
+
+	bpf_map_memcg_enter(map, &old_memcg, &memcg);

kernel/bpf/syscall.c static void bpf_map_release_memcg(struct bpf_map *map) · line 623

Quoted 10 lines
kernel/bpf/syscall.c +10 -0
+	if (IS_ENABLED(CONFIG_MEMCG))
+		flags |= __GFP_ACCOUNT;
+
+	/* Only try the spinning allocation when preemption disables are tracked. */
+	if (IS_ENABLED(CONFIG_PREEMPT_COUNT) && can_spin_in_alloc() &&
+	    size <= KMALLOC_MAX_CACHE_SIZE && !(flags & ~nolock_flags))
+		ptr = kmalloc(size, flags | GFP_NOWAIT | __GFP_NOMEMALLOC);
+	/* Allocation failed or kmalloc_nolock()-only context. */
+	if (!ptr)
+		ptr = kmalloc_nolock(size, flags, NUMA_NO_NODE);

Can this leave live objects reported by kmemleak? kmalloc() objects are registered with kmemleak, but kmalloc_nolock() objects are not, because slab_post_alloc_hook() only calls kmemleak_alloc_recursive() when alloc_flags_allow_spinning() is true. Before this patch every selem and storage came from kmalloc_nolock(), so none were registered. Now both kinds end up in the same RCU hlists, and kmemleak never scans the contents of an unregistered object.

For example:

1. A kprobe program in atomic context creates task T's storage S and selem A for map M1 through kmalloc_nolock(). Neither is registered.

2. A preemptible caller, such as an fentry program or bpf_pid_task_storage_update_elem(), creates selem B for map M2 on T. bpf_selem_alloc() gets B from kmalloc(), so B is registered. bpf_selem_link_storage_nolock() makes S->list.first point to B, and A.snode.pprev points into B.

3. A later selem C of M2, created through kmalloc_nolock() for another owner, hashes to the same bucket. hlist_add_head_rcu() makes b->list.first point to C and C.map_node.next point to B.

B is now referenced only from S, A and C, none of which kmemleak scans, so B can be reported as an unreferenced object even though it is live. The same applies to sk storage, where softirq programs use kmalloc_nolock() and cgroup sockopt programs or syscall updates use kmalloc().

A similar false positive was fixed before in ccff81e1d028 ("bpf: Fix false positive kmemleak report in bpf_ringbuf_area_alloc()").

Should the kmalloc()ed local storage objects be marked with kmemleak_not_leak() or kmemleak_ignore(), or should kmemleak registration otherwise be kept the same for both paths?

This isn't a confirmed bug, but the BPF subsystem guide lists kmalloc() in an op that programs can reach as potentially unsafe when the verifier admits the op for kprobe, tracepoint or perf event programs. bpf_task_storage_get() and bpf_cgrp_storage_get() are offered to all of those program types by bpf_base_func_proto(), and reach this code through:

bpf_task_storage_get()
bpf_local_storage_update()
bpf_selem_alloc() / bpf_local_storage_alloc()
bpf_map_kmalloc_maylock()
kmalloc()

The guide lists bpf_mem_cache_alloc(), bpf_map_kmalloc_nolock() with kfree_nolock(), and a verifier restriction to the program types in may_update_sockmap() as safe. This code uses a run-time context test instead (CONFIG_PREEMPT_COUNT && preempt_count() == 0 && !irqs_disabled() && !CONFIG_PREEMPT_RT).

That test appears to exclude NMI, hardirq, softirq and contexts holding spinning locks inside the allocator, since those raise preempt_count(). One context does look able to reach kmalloc(): raw_tp/tp_btf programs run via __bpf_trace_run() under rcu_read_lock_dont_migrate() and the tracepoint SRCU guard, so preempt_count() can be zero there. Those call sites hold no spinning lock, so kmalloc(GFP_NOWAIT) seems fine on that analysis.

Could the changelog or a comment state why this run-time test excludes every NMI and inside-allocator context that the guide is concerned about?

---
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/45338923700

author reviewer
#5 lore raw

PATCH 2/4 bpf: Plumb local storage context

In reply to Emil Tsalapatis

Local-storage allocation lacks context about the calling program. Pass the program through the hidden helper argument and share the allocation path for new elements and storage containers.

Non-functional change, will be used to decide whether context allocation should be sleepable.

---
 include/linux/bpf_local_storage.h |  3 +-
 kernel/bpf/bpf_cgrp_storage.c     |  9 +++---
 kernel/bpf/bpf_inode_storage.c    |  9 +++---
 kernel/bpf/bpf_local_storage.c    | 47 +++++++++++++++++++++++--------
 kernel/bpf/bpf_task_storage.c     |  9 +++---
 net/core/bpf_sk_storage.c         | 17 ++++++-----
 6 files changed, 62 insertions(+), 32 deletions(-)
include/linux/bpf_local_storage.h +2 -1
index 6c643ac510799..28f6ffbd75741 100644
@@ -213,7 +213,8 @@ bpf_local_storage_alloc(void *owner,
 
 struct bpf_local_storage_data *
 bpf_local_storage_update(void *owner, struct bpf_local_storage_map *smap,
-			 void *value, u64 map_flags, bool swap_uptrs);
+			 void *value, u64 map_flags, bool swap_uptrs,
+			 const struct bpf_prog_aux *aux);
 
 u64 bpf_local_storage_map_mem_usage(const struct bpf_map *map);
 
kernel/bpf/bpf_cgrp_storage.c +5 -4
index c76e9b0fabba8..8a6b38b51ea2f 100644
@@ -76,7 +76,7 @@ static long bpf_cgrp_storage_update_elem(struct bpf_map *map, void *key,
 		return PTR_ERR(cgroup);
 
 	sdata = bpf_local_storage_update(cgroup, (struct bpf_local_storage_map *)map,
-					 value, map_flags, false);
+					 value, map_flags, false, NULL);
 	cgroup_put(cgroup);
 	return PTR_ERR_OR_ZERO(sdata);
 }
@@ -122,8 +122,8 @@ static void cgroup_storage_map_free(struct bpf_map *map)
 	bpf_local_storage_map_free(map, &cgroup_cache);
 }
 
-BPF_CALL_4(bpf_cgrp_storage_get, struct bpf_map *, map, struct cgroup *, cgroup,
-	   void *, value, u64, flags)
+BPF_CALL_5(bpf_cgrp_storage_get, struct bpf_map *, map, struct cgroup *, cgroup,
+	   void *, value, u64, flags, struct bpf_prog_aux *, aux)
 {
 	struct bpf_local_storage_data *sdata;
 
@@ -142,7 +142,7 @@ BPF_CALL_4(bpf_cgrp_storage_get, struct bpf_map *, map, struct cgroup *, cgroup,
 	if (!percpu_ref_is_dying(&cgroup->self.refcnt) &&
 	    (flags & BPF_LOCAL_STORAGE_GET_F_CREATE))
 		sdata = bpf_local_storage_update(cgroup, (struct bpf_local_storage_map *)map,
-						 value, BPF_NOEXIST, false);
+						 value, BPF_NOEXIST, false, aux);
 
 out:
 	return IS_ERR_OR_NULL(sdata) ? (unsigned long)NULL : (unsigned long)sdata->data;
@@ -181,6 +181,7 @@ const struct bpf_func_proto bpf_cgrp_storage_get_proto = {
 	.arg2_btf_id	= &bpf_cgroup_btf_id[0],
 	.arg3_type	= ARG_PTR_TO_MAP_VALUE_OR_NULL,
 	.arg4_type	= ARG_ANYTHING,
+	.arg5_type	= ARG_PTR_TO_PROG_AUX,
 };
 
 const struct bpf_func_proto bpf_cgrp_storage_delete_proto = {
kernel/bpf/bpf_inode_storage.c +5 -4
index f9e81060c1f45..c979e841ec130 100644
@@ -98,7 +98,7 @@ static long bpf_fd_inode_storage_update_elem(struct bpf_map *map, void *key,
 
 	sdata = bpf_local_storage_update(file_inode(fd_file(f)),
 					 (struct bpf_local_storage_map *)map,
-					 value, map_flags, false);
+					 value, map_flags, false, NULL);
 	return PTR_ERR_OR_ZERO(sdata);
 }
 
@@ -122,8 +122,8 @@ static long bpf_fd_inode_storage_delete_elem(struct bpf_map *map, void *key)
 	return inode_storage_delete(file_inode(fd_file(f)), map);
 }
 
-BPF_CALL_4(bpf_inode_storage_get, struct bpf_map *, map, struct inode *, inode,
-	   void *, value, u64, flags)
+BPF_CALL_5(bpf_inode_storage_get, struct bpf_map *, map, struct inode *, inode,
+	   void *, value, u64, flags, struct bpf_prog_aux *, aux)
 {
 	struct bpf_local_storage_data *sdata;
 
@@ -149,7 +149,7 @@ BPF_CALL_4(bpf_inode_storage_get, struct bpf_map *, map, struct inode *, inode,
 	if (flags & BPF_LOCAL_STORAGE_GET_F_CREATE) {
 		sdata = bpf_local_storage_update(
 			inode, (struct bpf_local_storage_map *)map, value,
-			BPF_NOEXIST, false);
+			BPF_NOEXIST, false, aux);
 		return IS_ERR(sdata) ? (unsigned long)NULL :
 					     (unsigned long)sdata->data;
 	}
@@ -221,6 +221,7 @@ const struct bpf_func_proto bpf_inode_storage_get_proto = {
 	.arg2_btf_id	= &bpf_inode_storage_btf_ids[0],
 	.arg3_type	= ARG_PTR_TO_MAP_VALUE_OR_NULL,
 	.arg4_type	= ARG_ANYTHING,
+	.arg5_type	= ARG_PTR_TO_PROG_AUX,
 };
 
 const struct bpf_func_proto bpf_inode_storage_delete_proto = {
kernel/bpf/bpf_local_storage.c +35 -12

107 lines not on this page · raw message

kernel/bpf/bpf_task_storage.c +5 -4
index 4b342be29eac7..b081e8799eef1 100644
@@ -118,7 +118,7 @@ static long bpf_pid_task_storage_update_elem(struct bpf_map *map, void *key,
 
 	sdata = bpf_local_storage_update(
 		task, (struct bpf_local_storage_map *)map, value, map_flags,
-		true);
+		true, NULL);
 
 	err = PTR_ERR_OR_ZERO(sdata);
 out:
@@ -165,8 +165,8 @@ static long bpf_pid_task_storage_delete_elem(struct bpf_map *map, void *key)
 	return err;
 }
 
-BPF_CALL_4(bpf_task_storage_get, struct bpf_map *, map, struct task_struct *,
-	   task, void *, value, u64, flags)
+BPF_CALL_5(bpf_task_storage_get, struct bpf_map *, map, struct task_struct *, task,
+	   void *, value, u64, flags, struct bpf_prog_aux *, aux)
 {
 	struct bpf_local_storage_data *sdata;
 
@@ -183,7 +183,7 @@ BPF_CALL_4(bpf_task_storage_get, struct bpf_map *, map, struct task_struct *,
 	    (flags & BPF_LOCAL_STORAGE_GET_F_CREATE)) {
 		sdata = bpf_local_storage_update(
 			task, (struct bpf_local_storage_map *)map, value,
-			BPF_NOEXIST, false);
+			BPF_NOEXIST, false, aux);
 		return IS_ERR(sdata) ? (unsigned long)NULL : (unsigned long)sdata->data;
 	}
 
@@ -244,6 +244,7 @@ const struct bpf_func_proto bpf_task_storage_get_proto = {
 	.arg2_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
 	.arg3_type = ARG_PTR_TO_MAP_VALUE_OR_NULL,
 	.arg4_type = ARG_ANYTHING,
+	.arg5_type = ARG_PTR_TO_PROG_AUX,
 };
 
 const struct bpf_func_proto bpf_task_storage_delete_proto = {
net/core/bpf_sk_storage.c +10 -7
index 1c59300af05c7..5a013b81d161a 100644
@@ -106,7 +106,7 @@ static long bpf_fd_sk_storage_update_elem(struct bpf_map *map, void *key,
 	if (sock) {
 		sdata = bpf_local_storage_update(
 			sock->sk, (struct bpf_local_storage_map *)map, value,
-			map_flags, false);
+			map_flags, false, NULL);
 		sockfd_put(sock);
 		return PTR_ERR_OR_ZERO(sdata);
 	}
@@ -232,8 +232,8 @@ int bpf_sk_storage_clone(const struct sock *sk, struct sock *newsk)
 	return ret;
 }
 
-BPF_CALL_4(bpf_sk_storage_get, struct bpf_map *, map, struct sock *, sk,
-	   void *, value, u64, flags)
+BPF_CALL_5(bpf_sk_storage_get, struct bpf_map *, map, struct sock *, sk,
+	   void *, value, u64, flags, struct bpf_prog_aux *, aux)
 {
 	struct bpf_local_storage_data *sdata;
 
@@ -254,7 +254,7 @@ BPF_CALL_4(bpf_sk_storage_get, struct bpf_map *, map, struct sock *, sk,
 	    refcount_inc_not_zero(&sk->sk_refcnt)) {
 		sdata = bpf_local_storage_update(
 			sk, (struct bpf_local_storage_map *)map, value,
-			BPF_NOEXIST, false);
+			BPF_NOEXIST, false, aux);
 		/* sk must be a fullsock (guaranteed by verifier),
 		 * so sock_gen_put() is unnecessary.
 		 */
@@ -341,6 +341,7 @@ const struct bpf_func_proto bpf_sk_storage_get_proto = {
 	.arg2_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
 	.arg3_type	= ARG_PTR_TO_MAP_VALUE_OR_NULL,
 	.arg4_type	= ARG_ANYTHING,
+	.arg5_type	= ARG_PTR_TO_PROG_AUX,
 };
 
 const struct bpf_func_proto bpf_sk_storage_get_cg_sock_proto = {
@@ -351,6 +352,7 @@ const struct bpf_func_proto bpf_sk_storage_get_cg_sock_proto = {
 	.arg2_type	= ARG_PTR_TO_CTX, /* context is 'struct sock' */
 	.arg3_type	= ARG_PTR_TO_MAP_VALUE_OR_NULL,
 	.arg4_type	= ARG_ANYTHING,
+	.arg5_type	= ARG_PTR_TO_PROG_AUX,
 };
 
 const struct bpf_func_proto bpf_sk_storage_delete_proto = {
@@ -387,14 +389,14 @@ static bool bpf_sk_storage_tracing_allowed(const struct bpf_prog *prog)
 	return false;
 }
 
-BPF_CALL_4(bpf_sk_storage_get_tracing, struct bpf_map *, map, struct sock *, sk,
-	   void *, value, u64, flags)
+BPF_CALL_5(bpf_sk_storage_get_tracing, struct bpf_map *, map, struct sock *, sk,
+	   void *, value, u64, flags, struct bpf_prog_aux *, aux)
 {
 	WARN_ON_ONCE(!bpf_rcu_lock_held());
 	if (in_hardirq() || in_nmi())
 		return (unsigned long)NULL;
 
-	return (unsigned long)____bpf_sk_storage_get(map, sk, value, flags);
+	return ____bpf_sk_storage_get(map, sk, value, flags, aux);
 }
 
 BPF_CALL_2(bpf_sk_storage_delete_tracing, struct bpf_map *, map,
@@ -416,6 +418,7 @@ const struct bpf_func_proto bpf_sk_storage_get_tracing_proto = {
 	.arg2_btf_id	= &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
 	.arg3_type	= ARG_PTR_TO_MAP_VALUE_OR_NULL,
 	.arg4_type	= ARG_ANYTHING,
+	.arg5_type	= ARG_PTR_TO_PROG_AUX,
 	.allowed	= bpf_sk_storage_tracing_allowed,
 };
 
Signature · 1 line
2.52.1
#6 lore raw

Re: [PATCH bpf-next v1 2/4] bpf: Plumb local storage context

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf: bpf_local_storage_update() 6th arg breaks selftest fexit_update() probes --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: bpf_local_storage_update() 6th arg breaks selftest fexit_update() probes
--

commit ab094afd08fb6622ca0c449a168c674fa21d6976
Author: Emil Tsalapatis <[email protected]>

bpf: Plumb local storage context

This commit passes struct bpf_prog_aux as a hidden fifth argument to the bpf_*_storage_get() helpers and threads it into bpf_local_storage_update() while consolidating local storage memory allocation into bpf_local_storage_alloc_mem().

include/linux/bpf_local_storage.h bpf_local_storage_alloc(void *owner, · line 217

Quoted 11 lines
include/linux/bpf_local_storage.h +2 -1
index 6c643ac510799..28f6ffbd75741 100644
@@ -213,7 +213,8 @@ bpf_local_storage_alloc(void *owner,
 
 struct bpf_local_storage_data *
 bpf_local_storage_update(void *owner, struct bpf_local_storage_map *smap,
-			 void *value, u64 map_flags, bool swap_uptrs);
+			 void *value, u64 map_flags, bool swap_uptrs,
+			 const struct bpf_prog_aux *aux);

[Severity: Medium]
Does adding the sixth parameter to bpf_local_storage_update() break the SEC("fexit/bpf_local_storage_update") probes in tools/testing/selftests/bpf/progs/cgrp_ls_sleepable.c and tools/testing/selftests/bpf/progs/task_local_storage.c?

Both fexit_update() programs still declare five arguments before ret:

tools/testing/selftests/bpf/progs/cgrp_ls_sleepable.c:
SEC("fexit/bpf_local_storage_update")
int BPF_PROG(fexit_update, void *owner, struct bpf_local_storage_map *smap,
void *value, u64 map_flags, bool swap_uptrs, struct bpf_local_storage_data *ret)

{
	if (IS_ERR_VALUE(ret))
		update_err = PTR_ERR(ret);
	return 0;
}

With aux at ctx[5] and the return value shifted to ctx[6], ret binds to aux instead of the return value, so update_err is never set when bpf_local_storage_update() returns an error pointer.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author reviewer
#7 lore raw

PATCH 3/4 bpf: Add sleepable local storage

In reply to Emil Tsalapatis

Sleepable BPF programs still create local storage with kmalloc_maylock. Use the program aux metadata from the expanded helper to allocate storage with a sleepable call when available.

---
 include/linux/bpf.h            | 5 +++++
 kernel/bpf/bpf_local_storage.c | 6 +++++-
 2 files changed, 10 insertions(+), 1 deletion(-)
include/linux/bpf.h +5 -0
index 5565a735ae7ce..52eee026d0685 100644
@@ -2094,6 +2094,11 @@ static inline bool bpf_prog_runs_sleepable(const struct bpf_prog *prog)
 	return prog->sleepable || prog->aux->sleepable_async_cb;
 }
 
+static inline bool bpf_prog_can_sleep(const struct bpf_prog *prog)
+{
+	return prog->sleepable && preemptible() && !rcu_preempt_depth();
+}
+
 struct bpf_array_aux {
 	/* Programs with direct jumps into programs part of this array. */
 	struct list_head poke_progs;
kernel/bpf/bpf_local_storage.c +5 -1
index 28eaee5c66ce8..74dfebf180970 100644
@@ -69,6 +69,10 @@ static bool selem_linked_to_map(const struct bpf_local_storage_elem *selem)
 static void *bpf_local_storage_alloc_mem(struct bpf_local_storage_map *smap,
 					size_t size, bool sleepable)
 {
+	if (sleepable)
+		return bpf_map_kzalloc(&smap->map, size,
+				       GFP_KERNEL | __GFP_RETRY_MAYFAIL);
+
 	return bpf_map_kmalloc_maylock(&smap->map, size, __GFP_ZERO);
 }
 
@@ -598,7 +602,7 @@ bpf_local_storage_update(void *owner, struct bpf_local_storage_map *smap,
 {
 	struct bpf_local_storage_data *old_sdata = NULL;
 	struct bpf_local_storage_elem *alloc_selem, *selem = NULL;
-	bool sleepable = false;
+	bool sleepable = aux && bpf_prog_can_sleep(aux->prog);
 	struct bpf_local_storage *local_storage;
 	struct bpf_local_storage_map_bucket *b;
 	HLIST_HEAD(old_selem_free_list);
Signature · 1 line
2.52.1
#8 lore raw

Re: [PATCH bpf-next v1 3/4] bpf: Add sleepable local storage

TL;DR: The new sleepable GFP_KERNEL | __GFP_RETRY_MAYFAIL local storage allocation lacks __GFP_NOWARN, so under memory pressure it may print allocator warnings and stack dumps on handled failures.…
Quoted 1 line

bpf: Add sleepable local storage

TL;DR: The new sleepable GFP_KERNEL | __GFP_RETRY_MAYFAIL local storage allocation lacks __GFP_NOWARN, so under memory pressure it may print allocator warnings and stack dumps on handled failures. Intentional?

Quoted 3 lines
kernel/bpf/bpf_local_storage.c +0 -0

[ ... ]

kernel/bpf/bpf_local_storage.c static bool selem_linked_to_map(const struct bpf_local_storage_elem *selem) · line 75

Quoted 8 lines
kernel/bpf/bpf_local_storage.c +4 -0
@@ -69,6 +69,10 @@ static bool selem_linked_to_map(const struct bpf_local_storage_elem *selem)
 static void *bpf_local_storage_alloc_mem(struct bpf_local_storage_map *smap,
 					size_t size, bool sleepable)
 {
+	if (sleepable)
+		return bpf_map_kzalloc(&smap->map, size,
+				       GFP_KERNEL | __GFP_RETRY_MAYFAIL);
+

Should this mask also include __GFP_NOWARN?

A failure here is already handled: __bpf_selem_alloc() uncharges and returns NULL, and bpf_*_storage_get() returns NULL to the program. Without __GFP_NOWARN, a program creating local storage under memory pressure can make the allocator print warnings (slab_out_of_memory() and warn_alloc() with a stack dump).

The previous path did not warn, since bpf_map_kmalloc_maylock() ends up using GFP_NOWAIT or kmalloc_nolock(), both of which imply __GFP_NOWARN. The GFP_KERNEL path local storage had before 5063e7758899 ("bpf: Use kmalloc_nolock() universally in local storage") passed "gfp_flags | __GFP_NOWARN", and other GFP_KERNEL | __GFP_RETRY_MAYFAIL allocations in kernel/bpf (arena.c, bpf_ringbuf_area_alloc(), __bpf_map_area_alloc()) also add __GFP_NOWARN.

A sleepable program calling bpf_task_storage_get() with BPF_LOCAL_STORAGE_GET_F_CREATE reaches this via bpf_local_storage_update()->__bpf_selem_alloc()-> bpf_local_storage_alloc_mem(). Is the omission intentional?

kernel/bpf/bpf_local_storage.c static bool selem_linked_to_map(const struct bpf_local_storage_elem *selem) · line 77

Quoted 2 lines
kernel/bpf/bpf_local_storage.c +0 -0
 	return bpf_map_kmalloc_maylock(&smap->map, size, __GFP_ZERO);
 }

[ ... ]

---
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/45338923700

#9 lore raw

Re: [PATCH bpf-next v1 3/4] bpf: Add sleepable local storage

In reply to Emil Tsalapatis
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] bpf: missing __GFP_NOWARN in sleepable bpf_local_storage_alloc_mem() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] bpf: missing __GFP_NOWARN in sleepable bpf_local_storage_alloc_mem()
--

commit 6a9b8094f2dfaf87e47ddf985c894923ff71ad36
Author: Emil Tsalapatis <[email protected]>

bpf: Add sleepable local storage

This commit uses bpf_map_kzalloc() with GFP_KERNEL | __GFP_RETRY_MAYFAIL to allocate local storage when called from a sleepable BPF program in a sleepable context.

Quoted 5 lines
kernel/bpf/bpf_local_storage.c +0 -0
index 28eaee5c66ce8..74dfebf180970 100644

kernel/bpf/bpf_local_storage.c static bool selem_linked_to_map(const struct bpf_local_storage_elem *selem) · line 77

Quoted 9 lines
kernel/bpf/bpf_local_storage.c +4 -0
@@ -69,6 +69,10 @@ static bool selem_linked_to_map(const struct bpf_local_storage_elem *selem)
 static void *bpf_local_storage_alloc_mem(struct bpf_local_storage_map *smap,
 					size_t size, bool sleepable)
 {
+	if (sleepable)
+		return bpf_map_kzalloc(&smap->map, size,
+				       GFP_KERNEL | __GFP_RETRY_MAYFAIL);
+
 	return bpf_map_kmalloc_maylock(&smap->map, size, __GFP_ZERO);
 }

[Severity: Low]
Should this bpf_map_kzalloc() call also pass __GFP_NOWARN? Without it, an allocation failure under memory pressure or higher-order fragmentation triggers a warn_alloc() stack dump in dmesg, even though bpf_local_storage_update() handles a NULL return gracefully.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author reviewer
#10 lore raw

PATCH 4/4 selftests/bpf: Test kmalloc variant selection for task storage

In reply to Emil Tsalapatis

Add testing to confirm that task-storage allocations use the right sleepable vs maylock kmalloc variant for an allocation given the context the call is made in.

---
 .../bpf/prog_tests/task_storage_sleepable.c   |  94 +++++++++++++
 .../bpf/progs/task_storage_sleepable.c        | 126 ++++++++++++++++++
 2 files changed, 220 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/task_storage_sleepable.c
 create mode 100644 tools/testing/selftests/bpf/progs/task_storage_sleepable.c
tools/testing/selftests/bpf/prog_tests/task_storage_sleepable.c new file +94 -0
new file mode 100644
index 0000000000000..fa0818f63c6bc
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <pthread.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+#include <test_progs.h>
+#include "task_storage_sleepable.skel.h"
+
+static void *run_storage(void *arg)
+{
+	struct task_storage_sleepable *skel = arg;
+
+	/* A new thread has no task storage from earlier tests. */
+	skel->bss->target_pid = syscall(SYS_gettid);
+	syscall(SYS_getpgid, 0);
+	skel->bss->target_pid = 0;
+	return NULL;
+}
+
+static void test_alloc(const char *prog_name, int regular_allocs, int nonsleepable_allocs)
+{
+	struct task_storage_sleepable *skel;
+	struct bpf_link *link = NULL;
+	struct bpf_program *regular_probe, *prog;
+	pthread_t thread;
+	int err;
+
+	skel = task_storage_sleepable__open();
+	if (!ASSERT_OK_PTR(skel, "open"))
+		return;
+
+	regular_probe = skel->progs.on_regular_alloc;
+	err = bpf_program__set_attach_target(regular_probe, 0, "bpf_map_kzalloc");
+	if (err == -ESRCH) {
+		printf("%s: bpf_map_kzalloc missing from kernel BTF\n", __func__);
+		err = bpf_program__set_autoload(regular_probe, false);
+	}
+	if (!ASSERT_OK(err, "configure_regular_alloc_probe"))
+		goto out;
+
+	/* Task storage uses the nolock allocator until the fallback is added. */
+	prog = skel->progs.on_nonsleepable_alloc;
+	err = bpf_program__set_attach_target(prog, 0, "bpf_map_kmalloc_maylock");
+	if (err == -ESRCH)
+		err = bpf_program__set_attach_target(prog, 0, "bpf_map_kmalloc_nolock");
+	if (!ASSERT_OK(err, "set_nonsleepable_alloc_target"))
+		goto out;
+
+	err = task_storage_sleepable__load(skel);
+	if (!ASSERT_OK(err, "load"))
+		goto out;
+
+	if (bpf_program__autoload(regular_probe)) {
+		skel->links.on_regular_alloc = bpf_program__attach(regular_probe);
+		if (!ASSERT_OK_PTR(skel->links.on_regular_alloc, "attach_regular_alloc"))
+			goto out;
+	}
+	skel->links.on_nonsleepable_alloc = bpf_program__attach(skel->progs.on_nonsleepable_alloc);
+	if (!ASSERT_OK_PTR(skel->links.on_nonsleepable_alloc, "attach_nonsleepable_alloc"))
+		goto out;
+
+	prog = bpf_object__find_program_by_name(skel->obj, prog_name);
+	if (!ASSERT_OK_PTR(prog, "find_program"))
+		goto out;
+	link = bpf_program__attach(prog);
+	if (!ASSERT_OK_PTR(link, "attach_program"))
+		goto out;
+
+	err = pthread_create(&thread, NULL, run_storage, skel);
+	if (!ASSERT_OK(err, "pthread_create"))
+		goto out;
+	err = pthread_join(thread, NULL);
+	ASSERT_OK(err, "pthread_join");
+	ASSERT_EQ(skel->bss->errors, 0, "storage_errors");
+	if (skel->links.on_regular_alloc)
+		ASSERT_EQ(skel->bss->regular_allocs, regular_allocs, "regular_allocs");
+	ASSERT_EQ(skel->bss->nonsleepable_allocs, nonsleepable_allocs, "nonsleepable_allocs");
+out:
+	bpf_link__destroy(link);
+	task_storage_sleepable__destroy(skel);
+}
+
+void test_task_storage_sleepable(void)
+{
+	if (test__start_subtest("sleepable"))
+		test_alloc("sleepable", 3, 0);
+	if (test__start_subtest("non_sleepable"))
+		test_alloc("non_sleepable", 0, 3);
+	if (test__start_subtest("sleepable_rcu"))
+		test_alloc("sleepable_rcu", 0, 3);
+	if (test__start_subtest("mixed_contexts"))
+		test_alloc("mixed_contexts", 2, 2);
+}
tools/testing/selftests/bpf/progs/task_storage_sleepable.c new file +126 -0

126 lines not on this page · raw message

Signature · 1 line
2.52.1
#11 lore raw

Re: [PATCH bpf-next v1 4/4] selftests/bpf: Test kmalloc variant selection for task storage

TL;DR: Nit only, in the selftest: the bpf_map_kmalloc_nolock fallback and its comment look unreachable, since local storage doesn't call it in this tree. Could both be dropped?
Quoted 1 line

selftests/bpf: Test kmalloc variant selection for task storage

TL;DR: Nit only, in the selftest: the bpf_map_kmalloc_nolock fallback and its comment look unreachable, since local storage doesn't call it in this tree. Could both be dropped?

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/task_storage_sleepable.c +0 -0

[ ... ]

tools/testing/selftests/bpf/prog_tests/task_storage_sleepable.c line 46

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/task_storage_sleepable.c +5 -0
+	/* Task storage uses the nolock allocator until the fallback is added. */
+	prog = skel->progs.on_nonsleepable_alloc;
+	err = bpf_program__set_attach_target(prog, 0, "bpf_map_kmalloc_maylock");
+	if (err == -ESRCH)
+		err = bpf_program__set_attach_target(prog, 0, "bpf_map_kmalloc_nolock");

This isn't a bug, but is the bpf_map_kmalloc_nolock fallback still needed here?

bpf_map_kmalloc_maylock() is added earlier in this series, and local storage does not call bpf_map_kmalloc_nolock() in this tree, so the -ESRCH branch and the comment above it look unreachable.

Could both be dropped?

---
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/45338923700