BPF List
 help / color / mirror / Atom feed
* [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit
@ 2026-12-04 20:03 Mykyta Yatsenko
  2026-12-04 20:03 ` [PATCH bpf-next 1/5] bpf: Make a NULL cache slot mean that local storage has no value Mykyta Yatsenko
                   ` (5 more replies)
  0 siblings, 6 replies; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 20:03 UTC (permalink / raw)
  To: bpf, ast, andrii, daniel, kernel-team, eddyz87, memxor; +Cc: Mykyta Yatsenko

An egress program that looks up the sk storage of a cold socket waits
for two cache misses in a row. The first miss is on cache[] of the
storage, and the second miss is on the element. A lookup of a value
that the socket does not have is worse: it walks the whole list of the
storage, with one miss for each element. With many connections, these
misses are a large part of the program cost.

This series replaces the BPF_F_INLINE_VALUE series [1] with the design
that Alexei proposed [2], [3]:
- Patch 1 makes a NULL cache[] slot mean that the storage has no value
  for the slot, so that a lookup of an absent value stops at the first
  load [3]. This patch is generic: task, inode and cgroup storage get
  it too. Patch 2 tests maps that share slots.
- Patch 3 prefetches cache[] when sendmsg starts and when a transmit
  starts, because TCP knows the socket before the egress programs run.
- Patch 4 learns on each CPU which cache[] slots the programs look up,
  and prefetches the elements of these slots just before
  ->queue_xmit(). Patch 5 tests the hooks under traffic.
Patches 1-2 do not need patches 3-5. There is no UAPI change and no new
limit.

Changes from the prototype in [2]:
- A work item changes the static key from a count of the maps. Map
  create can run, and map free always runs, with migration disabled,
  and a change of a static key takes cpus_read_lock(). This can
  deadlock with a CPU offline: the key code of the prototype hung in a
  CPU hotplug and light skeleton stress test.
- Only bpf_sk_storage_get() marks a slot, for any socket. The prototype
  marked the lookups of the last socket that sent on the CPU.
- One mask of marked slots, cleared every 256 transmits. The prototype
  kept a second mask with the slots of the last round.
- The cache[] prefetch runs only on a CPU that has a marked slot.
- The sendmsg prefetch is in tcp_sendmsg_locked(), so that kTLS,
  sockmap and espintcp get it too.
- this_cpu operations, because the hooks can run in preemptible process
  context.

Limits:
- Patches 3-4 cover only TCP transmit and sk storage. The lookups of
  all programs mark slots, so a map that only ingress or sock_ops
  programs use also gets a prefetch on each transmit.
- The static key is on while any sk storage map exists. While a CPU has
  a hot slot, each transmit on that CPU loads sk->sk_bpf_storage. A
  gate for each socket can come later, if a workload needs it.
- With more than 16 maps, maps share cache[] slots, and a lookup of an
  absent value in a shared slot can still walk the list.

On x86-64, clang emits no instruction for prefetch(), because the
kernel builds with -mno-sse [4], [5]. Thus the hooks use prefetchw().

Results: AMD Zen 5 KVM guest, 4 server vCPUs, IPv6 over veth, 131072
connections, 9 sk storage maps for each socket, bpf-next 2bf3351c5f89.
2 tc egress programs do 2 sk storage lookups on each packet. The change
of the time in each lookup against base, from perf profiles, mean of 3
runs:

                                  lookup 1    lookup 2
  both values present              -95.7%      -93.7%
  lookup 2 finds no value          -96.4%      -99.5%

With patch 1 alone, the lookup that finds no value takes 98.7% less
time, and the other lookups change by less than 4%. The local storage
benchmarks in selftests show no change larger than the noise between
runs.

Signed-off-by: Mykyta Yatsenko <yatsenko@meta.com>

[1] https://lore.kernel.org/bpf/20261123-sls_f1-v2-0-76474de9b052@meta.com/
[2] https://lore.kernel.org/bpf/DN8A36W906WG.1BTUYRC2FIIR@gmail.com/
[3] https://lore.kernel.org/bpf/DN92BUAQMX7H.3NKLFY0FRORT7@gmail.com/
[4] https://lore.kernel.org/all/20261103060658.696994-1-martin.ankerl@gmail.com/
[5] https://github.com/llvm/llvm-project/pull/248194
[6] https://lore.kernel.org/bpf/DNAPOYTT6B0G.2RZJJ80T3HFKU@gmail.com/

---
Mykyta Yatsenko (5):
      bpf: Make a NULL cache slot mean that local storage has no value
      selftests/bpf: Test sk storage maps that share cache slots
      bpf: tcp: Prefetch sk storage cache[] before TCP transmit
      bpf: tcp: Prefetch values of hot sk storage maps before transmit
      selftests/bpf: Test sk storage lookups during TCP transmit

 include/linux/bpf_local_storage.h                  |  14 +-
 include/net/bpf_sk_storage.h                       |  53 +++++++
 kernel/bpf/bpf_local_storage.c                     |  23 +++-
 net/core/bpf_sk_storage.c                          |  69 +++++++++-
 net/ipv4/tcp.c                                     |   2 +
 net/ipv4/tcp_output.c                              |   3 +
 .../bpf/prog_tests/sk_storage_shared_slots.c       |  57 ++++++++
 .../selftests/bpf/prog_tests/sk_storage_xmit.c     | 153 +++++++++++++++++++++
 .../testing/selftests/bpf/progs/sk_storage_xmit.c  |  46 +++++++
 9 files changed, 415 insertions(+), 5 deletions(-)
---
base-commit: 94299e4ad749bd5b361498b97b59f326bedac6fe
change-id: 20261130-sk_storage_prefetch-575e7df22179

Best regards,
--  
Mykyta Yatsenko <yatsenko@meta.com>


^ permalink raw reply	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 1/5] bpf: Make a NULL cache slot mean that local storage has no value
  2026-12-04 20:03 [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit Mykyta Yatsenko
@ 2026-12-04 20:03 ` Mykyta Yatsenko
  2026-12-04 20:03 ` [PATCH bpf-next 2/5] selftests/bpf: Test sk storage maps that share cache slots Mykyta Yatsenko
                   ` (4 subsequent siblings)
  5 siblings, 0 replies; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 20:03 UTC (permalink / raw)
  To: bpf, ast, andrii, daniel, kernel-team, eddyz87, memxor; +Cc: Mykyta Yatsenko

From: Mykyta Yatsenko <yatsenko@meta.com>

A lookup of a value that the owner does not have walks the whole list
of its storage, with one cache miss for each element when the owner is
cold. A prefetch cannot hide these misses, because each address comes
from the element before it.

Fill the cache[] slot when an element is linked, and refill it from the
list when the element in the slot is unlinked. Then a NULL slot means
that no element has this slot, and the lookup stops at the first load.
This applies to all local storage types.

With more than 16 maps, maps share slots, and a lookup can still walk
the list. A delete and map_free() now walk the list once under the
lock, to refill the slot. An update could already walk the whole list
under this lock. A create of an absent value no longer walks the list.
destroy() does not refill the slots, because the owner goes away.

On 64-bit, the copy of cache_idx goes into a hole of the element. On a
32-bit CPU with 32-byte cache lines, the element grows by 32 bytes.

The local storage benchmarks in selftests (1 to 1000 task storage maps,
and creates) show no change larger than the noise between runs.

Suggested-by: Alexei Starovoitov <ast@kernel.org>
Link: https://lore.kernel.org/bpf/DN92BUAQMX7H.3NKLFY0FRORT7@gmail.com/
Signed-off-by: Mykyta Yatsenko <yatsenko@meta.com>
---
 include/linux/bpf_local_storage.h | 14 +++++++++++---
 kernel/bpf/bpf_local_storage.c    | 23 ++++++++++++++++++++++-
 2 files changed, 33 insertions(+), 4 deletions(-)

diff --git a/include/linux/bpf_local_storage.h b/include/linux/bpf_local_storage.h
index 6c643ac510799..83d849595805f 100644
--- a/include/linux/bpf_local_storage.h
+++ b/include/linux/bpf_local_storage.h
@@ -85,7 +85,8 @@ struct bpf_local_storage_elem {
 						 */
 	};
 	atomic_t state;
-	/* 4 bytes hole */
+	u16 cache_idx;		/* Copy of smap->cache_idx. smap can be NULL */
+	/* 2 bytes hole */
 	/* The data is stored in another cacheline to minimize
 	 * the number of cachelines access during a cache hit.
 	 */
@@ -93,6 +94,10 @@ struct bpf_local_storage_elem {
 };
 
 struct bpf_local_storage {
+	/*
+	 * A NULL slot means that no selem on the list has this cache_idx. Link
+	 * fills the slot, and unlink refills it from the list, under the lock.
+	 */
 	struct bpf_local_storage_data __rcu *cache[BPF_LOCAL_STORAGE_CACHE_SIZE];
 	struct hlist_head list; /* List of bpf_local_storage_elem */
 	void *owner;		/* The object that owns the above "list" of
@@ -164,10 +169,13 @@ bpf_local_storage_lookup(struct bpf_local_storage *local_storage,
 	/* Fast path (cache hit) */
 	sdata = rcu_dereference_check(local_storage->cache[smap->cache_idx],
 				      bpf_rcu_lock_held());
-	if (sdata && rcu_access_pointer(sdata->smap) == smap)
+	/* The slot is NULL only if no selem on the list has this cache_idx */
+	if (!sdata)
+		return NULL;
+	if (rcu_access_pointer(sdata->smap) == smap)
 		return sdata;
 
-	/* Slow path (cache miss) */
+	/* Slow path (another map has the slot) */
 	hlist_for_each_entry_rcu(selem, &local_storage->list, snode,
 				  rcu_read_lock_trace_held())
 		if (rcu_access_pointer(SDATA(selem)->smap) == smap)
diff --git a/kernel/bpf/bpf_local_storage.c b/kernel/bpf/bpf_local_storage.c
index ed849546afd1f..b61183c0c17b4 100644
--- a/kernel/bpf/bpf_local_storage.c
+++ b/kernel/bpf/bpf_local_storage.c
@@ -172,6 +172,20 @@ static void bpf_selem_free_list(struct hlist_head *list, bool reuse_now)
 		bpf_selem_free(selem, reuse_now);
 }
 
+/* Another sdata for the cache[] slot of @selem. local_storage->lock is held. */
+static struct bpf_local_storage_data *
+selem_cache_sibling(struct bpf_local_storage *local_storage,
+		    struct bpf_local_storage_elem *selem)
+{
+	struct bpf_local_storage_elem *pos;
+
+	hlist_for_each_entry(pos, &local_storage->list, snode)
+		if (pos != selem && pos->cache_idx == selem->cache_idx)
+			return SDATA(pos);
+
+	return NULL;
+}
+
 static void bpf_selem_unlink_storage_nolock_misc(struct bpf_local_storage_elem *selem,
 						 struct bpf_local_storage_map *smap,
 						 struct bpf_local_storage *local_storage,
@@ -182,7 +196,8 @@ static void bpf_selem_unlink_storage_nolock_misc(struct bpf_local_storage_elem *
 
 	if (rcu_access_pointer(local_storage->cache[smap->cache_idx]) ==
 	    SDATA(selem))
-		RCU_INIT_POINTER(local_storage->cache[smap->cache_idx], NULL);
+		rcu_assign_pointer(local_storage->cache[smap->cache_idx],
+				   selem_cache_sibling(local_storage, selem));
 
 	if (pin_owner && !refcount_inc_not_zero(&local_storage->owner_refcnt))
 		return;
@@ -228,6 +243,10 @@ static bool bpf_selem_unlink_storage_nolock(struct bpf_local_storage *local_stor
 	return free_local_storage;
 }
 
+/*
+ * The caller holds local_storage->lock, or no other CPU can unlink from the
+ * storage yet: a new storage before it is published, or the storage of a clone.
+ */
 void bpf_selem_link_storage_nolock(struct bpf_local_storage *local_storage,
 				   struct bpf_local_storage_elem *selem)
 {
@@ -236,8 +255,10 @@ void bpf_selem_link_storage_nolock(struct bpf_local_storage *local_storage,
 	smap = rcu_dereference_check(SDATA(selem)->smap, bpf_rcu_lock_held());
 	local_storage->mem_charge += smap->elem_size;
 
+	selem->cache_idx = smap->cache_idx;
 	RCU_INIT_POINTER(selem->local_storage, local_storage);
 	hlist_add_head_rcu(&selem->snode, &local_storage->list);
+	rcu_assign_pointer(local_storage->cache[smap->cache_idx], SDATA(selem));
 }
 
 static void bpf_selem_unlink_map_nolock(struct bpf_local_storage_map *smap,

-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 2/5] selftests/bpf: Test sk storage maps that share cache slots
  2026-12-04 20:03 [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit Mykyta Yatsenko
  2026-12-04 20:03 ` [PATCH bpf-next 1/5] bpf: Make a NULL cache slot mean that local storage has no value Mykyta Yatsenko
@ 2026-12-04 20:03 ` Mykyta Yatsenko
  2026-12-04 20:03 ` [PATCH bpf-next 3/5] bpf: tcp: Prefetch sk storage cache[] before TCP transmit Mykyta Yatsenko
                   ` (3 subsequent siblings)
  5 siblings, 0 replies; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 20:03 UTC (permalink / raw)
  To: bpf, ast, andrii, daniel, kernel-team, eddyz87, memxor; +Cc: Mykyta Yatsenko

From: Mykyta Yatsenko <yatsenko@meta.com>

A NULL cache[] slot now means that the storage has no element for the
slot, so a delete must refill the slot from the other elements. Use more
maps than slots, and check the other lookups after each delete.

Signed-off-by: Mykyta Yatsenko <yatsenko@meta.com>
---
 .../bpf/prog_tests/sk_storage_shared_slots.c       | 57 ++++++++++++++++++++++
 1 file changed, 57 insertions(+)

diff --git a/tools/testing/selftests/bpf/prog_tests/sk_storage_shared_slots.c b/tools/testing/selftests/bpf/prog_tests/sk_storage_shared_slots.c
new file mode 100644
index 0000000000000..d75b0f6115f5d
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/sk_storage_shared_slots.c
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <bpf/btf.h>
+
+/* More maps than the 16 cache[] slots, so that maps share slots */
+#define NR_MAPS 20
+
+void test_sk_storage_shared_slots(void)
+{
+	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_NO_PREALLOC,
+		    .btf_key_type_id = 1, .btf_value_type_id = 1);
+	int fds[NR_MAPS], sk = -1, n = 0, i, j, val;
+	struct btf *btf;
+
+	/* sk storage maps need BTF for the key and the value: type 1 is int */
+	btf = btf__new_empty();
+	if (!ASSERT_OK_PTR(btf, "btf__new_empty"))
+		return;
+	btf__add_int(btf, "int", 4, BTF_INT_SIGNED);
+	if (!ASSERT_OK(btf__load_into_kernel(btf), "btf__load_into_kernel"))
+		goto out;
+	opts.btf_fd = btf__fd(btf);
+	for (n = 0; n < NR_MAPS; n++) {
+		fds[n] = bpf_map_create(BPF_MAP_TYPE_SK_STORAGE, NULL, 4, 4, 0,
+					&opts);
+		if (!ASSERT_OK_FD(fds[n], "bpf_map_create"))
+			goto out;
+	}
+	sk = socket(AF_INET6, SOCK_STREAM, 0);
+	if (!ASSERT_OK_FD(sk, "socket"))
+		goto out;
+	for (i = 0; i < NR_MAPS; i++)
+		ASSERT_OK(bpf_map_update_elem(fds[i], &sk, &i, BPF_NOEXIST),
+			  "update");
+
+	/*
+	 * A link puts its element in the slot, so the last maps hold the shared
+	 * slots. Delete these maps first: each delete must refill the slot.
+	 */
+	for (i = NR_MAPS - 1; i >= 0; i--) {
+		ASSERT_OK(bpf_map_delete_elem(fds[i], &sk), "delete");
+		ASSERT_EQ(bpf_map_lookup_elem(fds[i], &sk, &val), -ENOENT,
+			  "lookup deleted");
+		for (j = 0; j < i; j++) {
+			val = -1;
+			ASSERT_OK(bpf_map_lookup_elem(fds[j], &sk, &val),
+				  "lookup");
+			ASSERT_EQ(val, j, "value");
+		}
+	}
+out:
+	if (sk >= 0)
+		close(sk);
+	while (n--)
+		close(fds[n]);
+	btf__free(btf);
+}

-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 3/5] bpf: tcp: Prefetch sk storage cache[] before TCP transmit
  2026-12-04 20:03 [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit Mykyta Yatsenko
  2026-12-04 20:03 ` [PATCH bpf-next 1/5] bpf: Make a NULL cache slot mean that local storage has no value Mykyta Yatsenko
  2026-12-04 20:03 ` [PATCH bpf-next 2/5] selftests/bpf: Test sk storage maps that share cache slots Mykyta Yatsenko
@ 2026-12-04 20:03 ` Mykyta Yatsenko
  2026-12-04 20:23   ` sashiko-bot
  2026-12-04 20:03 ` [PATCH bpf-next 4/5] bpf: tcp: Prefetch values of hot sk storage maps before transmit Mykyta Yatsenko
                   ` (2 subsequent siblings)
  5 siblings, 1 reply; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 20:03 UTC (permalink / raw)
  To: bpf, ast, andrii, daniel, kernel-team, eddyz87, memxor; +Cc: Mykyta Yatsenko

From: Mykyta Yatsenko <yatsenko@meta.com>

An egress program that looks up the sk storage of a cold socket waits for
two cache misses in a row. The first miss is on cache[] of the storage,
and the second miss is on the element. TCP knows the socket early, so
prefetch cache[] when sendmsg starts and when a transmit starts.

The hooks are on while an sk storage map exists. Until the next patch,
they prefetch on each transmit of each socket that has sk storage.

Map create can run with migration disabled, for example from a light
skeleton loader, and map free always runs with migration disabled. A
change of a static key takes cpus_read_lock(), which can then deadlock
with a CPU offline. Thus a work item sets the key from a count of the
maps.

On x86-64, clang emits no instruction for prefetch(), because the kernel
builds with -mno-sse. Thus the hooks use prefetchw(), which is inline asm
there.

Suggested-by: Alexei Starovoitov <ast@kernel.org>
Link: https://lore.kernel.org/bpf/DN8A36W906WG.1BTUYRC2FIIR@gmail.com/
Link: https://github.com/llvm/llvm-project/pull/248194
Signed-off-by: Mykyta Yatsenko <yatsenko@meta.com>
---
 include/net/bpf_sk_storage.h | 26 ++++++++++++++++++++++++++
 net/core/bpf_sk_storage.c    | 31 ++++++++++++++++++++++++++++++-
 net/ipv4/tcp.c               |  2 ++
 net/ipv4/tcp_output.c        |  2 ++
 4 files changed, 60 insertions(+), 1 deletion(-)

diff --git a/include/net/bpf_sk_storage.h b/include/net/bpf_sk_storage.h
index 2926f1f00d656..c97cbc299bbb2 100644
--- a/include/net/bpf_sk_storage.h
+++ b/include/net/bpf_sk_storage.h
@@ -13,6 +13,8 @@
 #include <uapi/linux/sock_diag.h>
 #include <uapi/linux/btf.h>
 #include <linux/bpf_local_storage.h>
+#include <linux/jump_label.h>
+#include <linux/prefetch.h>
 
 struct sock;
 
@@ -29,6 +31,29 @@ struct sk_buff;
 struct nlattr;
 
 #ifdef CONFIG_BPF_SYSCALL
+DECLARE_STATIC_KEY_FALSE(bpf_sk_storage_xmit_key);
+
+/*
+ * Prefetch cache[] of the storage of sk before a TCP transmit, so that an
+ * egress program does not wait for it. There is no RCU read lock: the storage
+ * can be freed at any time, so only prefetch it and never load from it.
+ * On x86-64, clang emits no instruction for prefetch(), so use prefetchw().
+ */
+static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk)
+{
+	const void *storage;
+
+	if (!static_branch_unlikely(&bpf_sk_storage_xmit_key))
+		return;
+	storage = rcu_access_pointer(sk->sk_bpf_storage);
+	if (!storage)
+		return;
+	/* cache[] is at the start of the storage: one or two cache lines */
+	prefetchw(storage);
+	if (sizeof_field(struct bpf_local_storage, cache) > SMP_CACHE_BYTES)
+		prefetchw(storage + SMP_CACHE_BYTES);
+}
+
 int bpf_sk_storage_clone(const struct sock *sk, struct sock *newsk);
 struct bpf_sk_storage_diag *
 bpf_sk_storage_diag_alloc(const struct nlattr *nla_stgs);
@@ -38,6 +63,7 @@ int bpf_sk_storage_diag_put(struct bpf_sk_storage_diag *diag,
 			    int stg_array_type,
 			    unsigned int *res_diag_size);
 #else
+static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk) {}
 static inline int bpf_sk_storage_clone(const struct sock *sk,
 				       struct sock *newsk)
 {
diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c
index 67288177492ac..875fff681869e 100644
--- a/net/core/bpf_sk_storage.c
+++ b/net/core/bpf_sk_storage.c
@@ -17,6 +17,28 @@
 
 DEFINE_BPF_STORAGE_CACHE(sk_cache);
 
+DEFINE_STATIC_KEY_FALSE(bpf_sk_storage_xmit_key);
+
+/*
+ * The TCP transmit hooks are on while an sk storage map exists. Map create can
+ * run with migration disabled (a light skeleton loader is a BPF syscall
+ * program), and map free always runs with migration disabled. A change of a
+ * static key takes cpus_read_lock(), which can then deadlock with a CPU
+ * offline. So only a work item changes the key. The key gates a prefetch only,
+ * so it can lag behind the maps.
+ */
+static atomic_t sk_storage_maps;
+
+static void bpf_sk_storage_key_fn(struct work_struct *work)
+{
+	if (atomic_read(&sk_storage_maps))
+		static_branch_enable(&bpf_sk_storage_xmit_key);
+	else
+		static_branch_disable(&bpf_sk_storage_xmit_key);
+}
+
+static DECLARE_DELAYED_WORK(sk_storage_key_work, bpf_sk_storage_key_fn);
+
 static struct bpf_local_storage_data *
 bpf_sk_storage_lookup(struct sock *sk, struct bpf_map *map, bool cacheit_lockit)
 {
@@ -64,11 +86,18 @@ void bpf_sk_storage_free(struct sock *sk)
 static void bpf_sk_storage_map_free(struct bpf_map *map)
 {
 	bpf_local_storage_map_free(map, &sk_cache);
+	/* Later, so that maps that come and go patch less text */
+	if (atomic_dec_and_test(&sk_storage_maps))
+		mod_delayed_work(system_dfl_wq, &sk_storage_key_work, HZ);
 }
 
 static struct bpf_map *bpf_sk_storage_map_alloc(union bpf_attr *attr)
 {
-	return bpf_local_storage_map_alloc(attr, &sk_cache);
+	struct bpf_map *map = bpf_local_storage_map_alloc(attr, &sk_cache);
+
+	if (!IS_ERR(map) && atomic_inc_return(&sk_storage_maps) == 1)
+		mod_delayed_work(system_dfl_wq, &sk_storage_key_work, 0);
+	return map;
 }
 
 static int notsupp_get_next_key(struct bpf_map *map, void *key,
diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c
index 80de376a9d2ef..b4b0826496791 100644
--- a/net/ipv4/tcp.c
+++ b/net/ipv4/tcp.c
@@ -273,6 +273,7 @@
 #include <net/inet_common.h>
 #include <net/inet_ecn.h>
 #include <net/tcp.h>
+#include <net/bpf_sk_storage.h>
 #include <net/tcp_ecn.h>
 #include <net/mptcp.h>
 #include <net/proto_memory.h>
@@ -1133,6 +1134,7 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 	int zc = 0;
 	long timeo;
 
+	bpf_sk_storage_prefetch_cache(sk);
 	flags = msg->msg_flags;
 
 	sockc = (struct sockcm_cookie){ .tsflags = READ_ONCE(sk->sk_tsflags) };
diff --git a/net/ipv4/tcp_output.c b/net/ipv4/tcp_output.c
index cf3ddc055d48d..2881d924cf376 100644
--- a/net/ipv4/tcp_output.c
+++ b/net/ipv4/tcp_output.c
@@ -38,6 +38,7 @@
 #define pr_fmt(fmt) "TCP: " fmt
 
 #include <net/tcp.h>
+#include <net/bpf_sk_storage.h>
 #include <net/tcp_ecn.h>
 #include <net/mptcp.h>
 #include <net/smc.h>
@@ -1605,6 +1606,7 @@ static int __tcp_transmit_skb(struct sock *sk, struct sk_buff *skb,
 	int err;
 
 	BUG_ON(!skb || !tcp_skb_pcount(skb));
+	bpf_sk_storage_prefetch_cache(sk);
 	tp = tcp_sk(sk);
 	prior_wstamp = tp->tcp_wstamp_ns;
 	tp->tcp_wstamp_ns = max(tp->tcp_wstamp_ns, tp->tcp_clock_cache);

-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 4/5] bpf: tcp: Prefetch values of hot sk storage maps before transmit
  2026-12-04 20:03 [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit Mykyta Yatsenko
                   ` (2 preceding siblings ...)
  2026-12-04 20:03 ` [PATCH bpf-next 3/5] bpf: tcp: Prefetch sk storage cache[] before TCP transmit Mykyta Yatsenko
@ 2026-12-04 20:03 ` Mykyta Yatsenko
  2026-12-04 20:18   ` sashiko-bot
  2026-12-04 20:03 ` [PATCH bpf-next 5/5] selftests/bpf: Test sk storage lookups during TCP transmit Mykyta Yatsenko
  2026-12-04 21:38 ` [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before " Andrii Nakryiko
  5 siblings, 1 reply; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 20:03 UTC (permalink / raw)
  To: bpf, ast, andrii, daniel, kernel-team, eddyz87, memxor; +Cc: Mykyta Yatsenko

From: Mykyta Yatsenko <yatsenko@meta.com>

After cache[], the lookup still waits for the element. Programs look up
the same few maps on most packets, so learn these maps on each CPU and
prefetch their elements just before ->queue_xmit().

Each bpf_sk_storage_get() marks the cache[] slot of its map on the CPU,
and the hook prefetches the elements of the marked slots. The marks are
cleared every 256 transmits of the CPU, so that a slot stops being
prefetched when programs stop using it. As in the prototype, a u8
counter that wraps counts the transmits. While no slot is marked on a
CPU, the cache[] prefetch is off too.

The lookups of all programs mark slots, for all sockets. The hint is
only a prefetch: a map that egress programs do not use costs one
prefetch on each transmit. Maps that share a cache[] slot share one
mark.

The hook is inline and the per-CPU state is in the header, so that a
transmit with no marked slot makes no call.

Suggested-by: Alexei Starovoitov <ast@kernel.org>
Link: https://lore.kernel.org/bpf/DN8A36W906WG.1BTUYRC2FIIR@gmail.com/
Signed-off-by: Mykyta Yatsenko <yatsenko@meta.com>
---
 include/net/bpf_sk_storage.h | 29 ++++++++++++++++++++++++++++-
 net/core/bpf_sk_storage.c    | 38 ++++++++++++++++++++++++++++++++++++++
 net/ipv4/tcp_output.c        |  1 +
 3 files changed, 67 insertions(+), 1 deletion(-)

diff --git a/include/net/bpf_sk_storage.h b/include/net/bpf_sk_storage.h
index c97cbc299bbb2..ec12c3aaa9775 100644
--- a/include/net/bpf_sk_storage.h
+++ b/include/net/bpf_sk_storage.h
@@ -14,6 +14,7 @@
 #include <uapi/linux/btf.h>
 #include <linux/bpf_local_storage.h>
 #include <linux/jump_label.h>
+#include <linux/percpu.h>
 #include <linux/prefetch.h>
 
 struct sock;
@@ -33,6 +34,16 @@ struct nlattr;
 #ifdef CONFIG_BPF_SYSCALL
 DECLARE_STATIC_KEY_FALSE(bpf_sk_storage_xmit_key);
 
+/* Per CPU hint of the TCP transmit hooks, see net/core/bpf_sk_storage.c */
+struct bpf_sk_storage_xmit {
+	u16 seen;		/* Slots of cache[] looked up in this round */
+	u8 round;		/* Transmits in this round, wraps at 256 */
+};
+
+DECLARE_PER_CPU_ALIGNED(struct bpf_sk_storage_xmit, bpf_sk_storage_xmit);
+
+void bpf_sk_storage_prefetch_hot(const struct sock *sk, unsigned long hot);
+
 /*
  * Prefetch cache[] of the storage of sk before a TCP transmit, so that an
  * egress program does not wait for it. There is no RCU read lock: the storage
@@ -43,7 +54,8 @@ static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk)
 {
 	const void *storage;
 
-	if (!static_branch_unlikely(&bpf_sk_storage_xmit_key))
+	if (!static_branch_unlikely(&bpf_sk_storage_xmit_key) ||
+	    !this_cpu_read(bpf_sk_storage_xmit.seen))
 		return;
 	storage = rcu_access_pointer(sk->sk_bpf_storage);
 	if (!storage)
@@ -54,6 +66,20 @@ static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk)
 		prefetchw(storage + SMP_CACHE_BYTES);
 }
 
+/* Prefetch the values of sk in the slots seen in this round of 256 transmits */
+static inline void bpf_sk_storage_prefetch_values(const struct sock *sk)
+{
+	u16 seen;
+
+	if (!static_branch_unlikely(&bpf_sk_storage_xmit_key))
+		return;
+	if (unlikely(!this_cpu_inc_return(bpf_sk_storage_xmit.round)))
+		this_cpu_write(bpf_sk_storage_xmit.seen, 0);
+	seen = this_cpu_read(bpf_sk_storage_xmit.seen);
+	if (seen && rcu_access_pointer(sk->sk_bpf_storage))
+		bpf_sk_storage_prefetch_hot(sk, seen);
+}
+
 int bpf_sk_storage_clone(const struct sock *sk, struct sock *newsk);
 struct bpf_sk_storage_diag *
 bpf_sk_storage_diag_alloc(const struct nlattr *nla_stgs);
@@ -64,6 +90,7 @@ int bpf_sk_storage_diag_put(struct bpf_sk_storage_diag *diag,
 			    unsigned int *res_diag_size);
 #else
 static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk) {}
+static inline void bpf_sk_storage_prefetch_values(const struct sock *sk) {}
 static inline int bpf_sk_storage_clone(const struct sock *sk,
 				       struct sock *newsk)
 {
diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c
index 875fff681869e..5feea65d25ea3 100644
--- a/net/core/bpf_sk_storage.c
+++ b/net/core/bpf_sk_storage.c
@@ -39,6 +39,43 @@ static void bpf_sk_storage_key_fn(struct work_struct *work)
 
 static DECLARE_DELAYED_WORK(sk_storage_key_work, bpf_sk_storage_key_fn);
 
+/*
+ * Each bpf_sk_storage_get() marks the slot of its map in cache[] on this CPU,
+ * and the transmit hooks prefetch the storage and the values of the marked
+ * slots. The marks are cleared every 256 transmits on this CPU, so that a slot
+ * stops being prefetched when programs stop using it.
+ *
+ * Programs, softirqs and the transmit path on a CPU can race, and a task can
+ * move to another CPU in a hook. Thus a prefetch can be lost or wasted for one
+ * round.
+ */
+DEFINE_PER_CPU_ALIGNED(struct bpf_sk_storage_xmit, bpf_sk_storage_xmit);
+
+/* As in a lookup, the RCU read lock keeps the storage and the elements */
+void bpf_sk_storage_prefetch_hot(const struct sock *sk, unsigned long hot)
+{
+	struct bpf_local_storage_data *sdata;
+	struct bpf_local_storage *storage;
+	int i;
+
+	guard(rcu)();
+	storage = rcu_dereference(sk->sk_bpf_storage);
+	if (!storage)
+		return;
+	for_each_set_bit(i, &hot, BPF_LOCAL_STORAGE_CACHE_SIZE) {
+		sdata = rcu_dereference(storage->cache[i]);
+		if (sdata)
+			prefetchw(sdata);
+	}
+}
+
+static void bpf_sk_storage_xmit_mark(struct bpf_map *map)
+{
+	u16 idx = ((struct bpf_local_storage_map *)map)->cache_idx;
+
+	this_cpu_or(bpf_sk_storage_xmit.seen, BIT(idx));
+}
+
 static struct bpf_local_storage_data *
 bpf_sk_storage_lookup(struct sock *sk, struct bpf_map *map, bool cacheit_lockit)
 {
@@ -270,6 +307,7 @@ BPF_CALL_4(bpf_sk_storage_get, struct bpf_map *, map, struct sock *, sk,
 	if (!sk || !sk_fullsock(sk) || flags > BPF_SK_STORAGE_GET_F_CREATE)
 		return (unsigned long)NULL;
 
+	bpf_sk_storage_xmit_mark(map);
 	sdata = bpf_sk_storage_lookup(sk, map, true);
 	if (sdata)
 		return (unsigned long)sdata->data;
diff --git a/net/ipv4/tcp_output.c b/net/ipv4/tcp_output.c
index 2881d924cf376..53dcbe5635684 100644
--- a/net/ipv4/tcp_output.c
+++ b/net/ipv4/tcp_output.c
@@ -1771,6 +1771,7 @@ static int __tcp_transmit_skb(struct sock *sk, struct sk_buff *skb,
 
 	tcp_add_tx_delay(skb, tp);
 
+	bpf_sk_storage_prefetch_values(sk);
 	err = INDIRECT_CALL_INET(icsk->icsk_af_ops->queue_xmit,
 				 inet6_csk_xmit, ip_queue_xmit,
 				 sk, skb, &inet->cork.fl);

-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* [PATCH bpf-next 5/5] selftests/bpf: Test sk storage lookups during TCP transmit
  2026-12-04 20:03 [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit Mykyta Yatsenko
                   ` (3 preceding siblings ...)
  2026-12-04 20:03 ` [PATCH bpf-next 4/5] bpf: tcp: Prefetch values of hot sk storage maps before transmit Mykyta Yatsenko
@ 2026-12-04 20:03 ` Mykyta Yatsenko
  2026-12-04 20:17   ` sashiko-bot
  2026-12-04 21:38 ` [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before " Andrii Nakryiko
  5 siblings, 1 reply; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 20:03 UTC (permalink / raw)
  To: bpf, ast, andrii, daniel, kernel-team, eddyz87, memxor; +Cc: Mykyta Yatsenko

From: Mykyta Yatsenko <yatsenko@meta.com>

The transmit hooks read the storage and the elements of a socket while
another thread can delete them. Test this under traffic, so that KASAN
and lockdep can find a use-after-free or a lock problem.

A cgroup egress program looks up two sk storage maps on each packet,
while user space deletes the elements of the client socket. Then the
test frees the maps under traffic and loads them again.

Signed-off-by: Mykyta Yatsenko <yatsenko@meta.com>
---
 .../selftests/bpf/prog_tests/sk_storage_xmit.c     | 153 +++++++++++++++++++++
 .../testing/selftests/bpf/progs/sk_storage_xmit.c  |  46 +++++++
 2 files changed, 199 insertions(+)

diff --git a/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c b/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c
new file mode 100644
index 0000000000000..9e80011e6630c
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#define _GNU_SOURCE
+#include <sched.h>
+#include <pthread.h>
+#include <test_progs.h>
+#include "network_helpers.h"
+#include "sk_storage_xmit.skel.h"
+
+/* Round trips in each phase: the hint needs a few rounds of 256 transmits */
+#define NR_TRIPS	1000
+#define TIMEOUT_NS	(10ULL * 1000 * 1000 * 1000)
+
+struct pair {
+	int cli;
+	int srv;
+};
+
+static bool stop;
+static int trips;
+static int pp_err;
+
+/* A round trip sends a data segment from cli and one from srv */
+static bool round_trip(struct pair *p)
+{
+	char c = 0;
+
+	return send(p->cli, &c, 1, 0) == 1 && recv(p->srv, &c, 1, 0) == 1 &&
+	       send(p->srv, &c, 1, 0) == 1 && recv(p->cli, &c, 1, 0) == 1;
+}
+
+static void *ping_pong(void *arg)
+{
+	struct pair *p = arg;
+	cpu_set_t set;
+
+	/* Keep all transmits on one CPU, so that its slots become hot */
+	CPU_ZERO(&set);
+	CPU_SET(sched_getcpu(), &set);
+	sched_setaffinity(0, sizeof(set), &set);
+	while (!READ_ONCE(stop)) {
+		if (!round_trip(p)) {
+			WRITE_ONCE(pp_err, errno ?: EIO);
+			break;
+		}
+		WRITE_ONCE(trips, trips + 1);
+	}
+	WRITE_ONCE(stop, true);
+	return NULL;
+}
+
+static struct sk_storage_xmit *load(int cg)
+{
+	struct sk_storage_xmit *skel;
+
+	skel = sk_storage_xmit__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "open_and_load"))
+		return NULL;
+	skel->links.egress = bpf_program__attach_cgroup(skel->progs.egress, cg);
+	if (!ASSERT_OK_PTR(skel->links.egress, "attach_cgroup")) {
+		sk_storage_xmit__destroy(skel);
+		return NULL;
+	}
+	return skel;
+}
+
+/* Delete the elements of cli for NR_TRIPS round trips */
+static void churn(struct sk_storage_xmit *skel, struct pair *p)
+{
+	struct bpf_map *a = skel->maps.sk_a, *b = skel->maps.sk_b;
+	__u64 end = get_time_ns() + TIMEOUT_NS;
+	int done = READ_ONCE(trips) + NR_TRIPS;
+	int deleted = 0;
+
+	while (!READ_ONCE(stop) && READ_ONCE(trips) < done &&
+	       get_time_ns() < end) {
+		deleted += !bpf_map__delete_elem(a, &p->cli, sizeof(p->cli), 0);
+		deleted += !bpf_map__delete_elem(b, &p->cli, sizeof(p->cli), 0);
+	}
+	ASSERT_GT(deleted, 0, "deleted");
+}
+
+static __u64 value_of(const struct bpf_map *map, int fd)
+{
+	__u64 v = 0;
+
+	ASSERT_OK(bpf_map__lookup_elem(map, &fd, sizeof(fd), &v, sizeof(v), 0),
+		  bpf_map__name(map));
+	return v;
+}
+
+static void check_values(struct sk_storage_xmit *skel, struct pair *p)
+{
+	char c = 0;
+
+	/* One more send makes the elements of cli again */
+	ASSERT_EQ(send(p->cli, &c, 1, 0), 1, "send");
+	ASSERT_EQ(recv(p->srv, &c, 1, 0), 1, "recv");
+	ASSERT_GE(value_of(skel->maps.sk_a, p->cli), 1, "sk_a value");
+	ASSERT_GE(value_of(skel->maps.sk_b, p->cli), 1, "sk_b value");
+}
+
+void serial_test_sk_storage_xmit(void)
+{
+	struct pair p = { .cli = -1, .srv = -1 };
+	struct sk_storage_xmit *skel = NULL;
+	pthread_t thread;
+	int cg, lfd;
+
+	WRITE_ONCE(stop, false);
+	WRITE_ONCE(trips, 0);
+	WRITE_ONCE(pp_err, 0);
+	cg = test__join_cgroup("/sk_storage_xmit");
+	if (!ASSERT_OK_FD(cg, "join_cgroup"))
+		return;
+	lfd = start_server(AF_INET6, SOCK_STREAM, "::1", 0, 0);
+	if (!ASSERT_OK_FD(lfd, "start_server"))
+		goto out;
+	p.cli = connect_to_fd(lfd, 0);
+	if (!ASSERT_OK_FD(p.cli, "connect_to_fd"))
+		goto out;
+	p.srv = accept(lfd, NULL, NULL);
+	if (!ASSERT_OK_FD(p.srv, "accept"))
+		goto out;
+	skel = load(cg);
+	if (!skel)
+		goto out;
+	if (!ASSERT_OK(pthread_create(&thread, NULL, ping_pong, &p),
+		       "pthread_create"))
+		goto out;
+	churn(skel, &p);
+	/* Free the maps under traffic, and load them again */
+	sk_storage_xmit__destroy(skel);
+	skel = load(cg);
+	if (skel)
+		churn(skel, &p);
+	WRITE_ONCE(stop, true);
+	pthread_join(thread, NULL);
+	ASSERT_OK(pp_err, "ping_pong");
+	ASSERT_GE(trips, 2 * NR_TRIPS, "round trips");
+	if (skel)
+		check_values(skel, &p);
+out:
+	sk_storage_xmit__destroy(skel);
+	if (p.srv >= 0)
+		close(p.srv);
+	if (p.cli >= 0)
+		close(p.cli);
+	if (lfd >= 0)
+		close(lfd);
+	close(cg);
+}
diff --git a/tools/testing/selftests/bpf/progs/sk_storage_xmit.c b/tools/testing/selftests/bpf/progs/sk_storage_xmit.c
new file mode 100644
index 0000000000000..7a46c9abadf40
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/sk_storage_xmit.c
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+
+char _license[] SEC("license") = "GPL";
+
+struct {
+	__uint(type, BPF_MAP_TYPE_SK_STORAGE);
+	__uint(map_flags, BPF_F_NO_PREALLOC);
+	__type(key, int);
+	__type(value, __u64);
+} sk_a SEC(".maps");
+
+struct {
+	__uint(type, BPF_MAP_TYPE_SK_STORAGE);
+	__uint(map_flags, BPF_F_NO_PREALLOC);
+	__type(key, int);
+	__type(value, __u64);
+} sk_b SEC(".maps");
+
+static __always_inline void count(void *map, struct bpf_sock *sk)
+{
+	__u64 *v;
+
+	v = bpf_sk_storage_get(map, sk, 0, BPF_SK_STORAGE_GET_F_CREATE);
+	if (v)
+		__sync_fetch_and_add(v, 1);
+}
+
+/* Its lookups mark the slots of sk_a and sk_b for the transmit hooks */
+SEC("cgroup_skb/egress")
+int egress(struct __sk_buff *skb)
+{
+	struct bpf_sock *sk = skb->sk;
+
+	if (!sk)
+		return 1;
+	sk = bpf_sk_fullsock(sk);
+	if (!sk)
+		return 1;
+	count(&sk_a, sk);
+	count(&sk_b, sk);
+	return 1;
+}

-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 5/5] selftests/bpf: Test sk storage lookups during TCP transmit
  2026-12-04 20:03 ` [PATCH bpf-next 5/5] selftests/bpf: Test sk storage lookups during TCP transmit Mykyta Yatsenko
@ 2026-12-04 20:17   ` sashiko-bot
  2026-12-04 21:40     ` Mykyta Yatsenko
  0 siblings, 1 reply; 13+ messages in thread
From: sashiko-bot @ 2026-12-04 20:17 UTC (permalink / raw)
  To: Mykyta Yatsenko, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] selftests/bpf: scheduling race in churn() can fail deleted
  assertion
--

commit c50686a666890adca4b04b7b43ac8b9ddda340a7
Author: Mykyta Yatsenko <yatsenko@meta.com>

selftests/bpf: Test sk storage lookups during TCP transmit

This commit adds the sk_storage_xmit BPF selftest to exercise concurrent
sk_storage map lookups on TCP egress while user space deletes elements and
destroys and reloads the maps.

> diff --git a/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c b/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c
> new file mode 100644
> index 0000000000000..9e80011e6630c
> --- /dev/null
> +++ b/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c

[ ... ]

> +/* Delete the elements of cli for NR_TRIPS round trips */
> +static void churn(struct sk_storage_xmit *skel, struct pair *p)
> +{
> +	struct bpf_map *a = skel->maps.sk_a, *b = skel->maps.sk_b;
> +	__u64 end = get_time_ns() + TIMEOUT_NS;
> +	int done = READ_ONCE(trips) + NR_TRIPS;
> +	int deleted = 0;
> +
> +	while (!READ_ONCE(stop) && READ_ONCE(trips) < done &&
> +	       get_time_ns() < end) {
> +		deleted += !bpf_map__delete_elem(a, &p->cli, sizeof(p->cli), 0);
> +		deleted += !bpf_map__delete_elem(b, &p->cli, sizeof(p->cli), 0);
> +	}
> +	ASSERT_GT(deleted, 0, "deleted");
> +}

[Severity: Low]
Can a scheduling delay between the main thread and ping_pong() make
ASSERT_GT(deleted, 0, "deleted") fail spuriously?

ping_pong() runs continuously in a tight loopback round-trip loop without
coordination with churn().  During the second churn() call, ping_pong() is
already running at full speed:

main thread                       ping_pong thread
churn()
  done = READ_ONCE(trips) + 1000
  (preempted)
                                  round_trip() x 1000
                                    WRITE_ONCE(trips, trips + 1)
  while (READ_ONCE(trips) < done)
    /* exits with deleted == 0 */
  ASSERT_GT(deleted, 0, ...)  <-- spurious failure

On an oversubscribed or single-CPU VM, preemption of the main thread lets
trips reach done before bpf_map__delete_elem() succeeds once, failing the
test even though the kernel behaved correctly.

Looping while (READ_ONCE(trips) < done || !deleted), still bounded by
!READ_ONCE(stop) and get_time_ns() < end, would avoid this race.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204-sk_storage_prefetch-v1-0-ea52fb48b52b@meta.com?part=5

^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 4/5] bpf: tcp: Prefetch values of hot sk storage maps before transmit
  2026-12-04 20:03 ` [PATCH bpf-next 4/5] bpf: tcp: Prefetch values of hot sk storage maps before transmit Mykyta Yatsenko
@ 2026-12-04 20:18   ` sashiko-bot
  2026-12-04 21:35     ` Mykyta Yatsenko
  0 siblings, 1 reply; 13+ messages in thread
From: sashiko-bot @ 2026-12-04 20:18 UTC (permalink / raw)
  To: Mykyta Yatsenko, bpf

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] bpf: unconditional per-CPU RMW in
  bpf_sk_storage_prefetch_values()
- [Medium] bpf: unconditional this_cpu_or() in
  bpf_sk_storage_xmit_mark()
- [Medium] bpf: RFO prefetchw() in bpf_sk_storage_prefetch_hot() bounces
  shared lines
--

commit f0130b9d642d8428468cd298e6da4b722527388b
Author: Mykyta Yatsenko <yatsenko@meta.com>

bpf: tcp: Prefetch values of hot sk storage maps before transmit

This commit records which bpf_local_storage cache[] slots are looked up
per CPU in bpf_sk_storage_get() and prefetches the elements in those
slots from __tcp_transmit_skb() before calling ->queue_xmit(), clearing
the per-CPU mask every 256 transmits.

Link: https://lore.kernel.org/bpf/DN8A36W906WG.1BTUYRC2FIIR@gmail.com/

> diff --git a/include/net/bpf_sk_storage.h b/include/net/bpf_sk_storage.h
> index c97cbc299bbb2..ec12c3aaa9775 100644
> --- a/include/net/bpf_sk_storage.h
> +++ b/include/net/bpf_sk_storage.h

[ ... ]

> @@ -54,6 +66,20 @@ static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk)
>  		prefetchw(storage + SMP_CACHE_BYTES);
>  }
>  
> +/* Prefetch the values of sk in the slots seen in this round of 256 transmits */
> +static inline void bpf_sk_storage_prefetch_values(const struct sock *sk)
> +{
> +	u16 seen;
> +
> +	if (!static_branch_unlikely(&bpf_sk_storage_xmit_key))
> +		return;
> +	if (unlikely(!this_cpu_inc_return(bpf_sk_storage_xmit.round)))
> +		this_cpu_write(bpf_sk_storage_xmit.seen, 0);
> +	seen = this_cpu_read(bpf_sk_storage_xmit.seen);
> +	if (seen && rcu_access_pointer(sk->sk_bpf_storage))
> +		bpf_sk_storage_prefetch_hot(sk, seen);
> +}

[Severity: Medium]
Should bpf_sk_storage_prefetch_values() check bpf_sk_storage_xmit.seen
before incrementing bpf_sk_storage_xmit.round?

Whenever any BPF_MAP_TYPE_SK_STORAGE map exists, __tcp_transmit_skb()
runs this_cpu_inc_return(bpf_sk_storage_xmit.round) on every TCP segment,
even on CPUs where seen is zero.

Outside x86, arm64, and s390, this_cpu_add_return_1 falls back to
raw_local_irq_save()/raw_local_irq_restore() per packet.  On arm64 and
x86-64 it still executes an atomic RMW (ldaddb or xaddb) with a memory
clobber, dirtying the per-CPU cacheline on every transmit.

Reading seen first and returning when it is zero would skip the RMW when
no slots are marked, matching bpf_sk_storage_prefetch_cache().

[ ... ]

> diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c
> index 875fff681869e..5feea65d25ea3 100644
> --- a/net/core/bpf_sk_storage.c
> +++ b/net/core/bpf_sk_storage.c
> @@ -39,6 +39,43 @@ static void bpf_sk_storage_key_fn(struct work_struct *work)

[ ... ]

> +/* As in a lookup, the RCU read lock keeps the storage and the elements */
> +void bpf_sk_storage_prefetch_hot(const struct sock *sk, unsigned long hot)
> +{
> +	struct bpf_local_storage_data *sdata;
> +	struct bpf_local_storage *storage;
> +	int i;
> +
> +	guard(rcu)();
> +	storage = rcu_dereference(sk->sk_bpf_storage);
> +	if (!storage)
> +		return;
> +	for_each_set_bit(i, &hot, BPF_LOCAL_STORAGE_CACHE_SIZE) {
> +		sdata = rcu_dereference(storage->cache[i]);
> +		if (sdata)
> +			prefetchw(sdata);
> +	}
> +}

[Severity: Medium]
Can prefetchw(sdata) here cause cross-CPU cacheline bouncing in
full-duplex TCP workloads?

On x86-64 (with X86_FEATURE_3DNOWPREFETCH) and arm64 (prfm pstl1keep),
prefetchw() issues a store-intent read-for-ownership prefetch that
invalidates shared copies on other CPUs.  The same applies to the
prefetchw() calls on storage->cache[] in bpf_sk_storage_prefetch_cache().

Because bpf_sk_storage_xmit_mark() runs for all bpf_sk_storage_get()
callers, a map read only on the RX CPU is still pulled into exclusive
state by the TX CPU on every transmit.  On arm64, prefetch() already
emits prfm pldl1keep and does not need the x86-64 clang workaround.

> +
> +static void bpf_sk_storage_xmit_mark(struct bpf_map *map)
> +{
> +	u16 idx = ((struct bpf_local_storage_map *)map)->cache_idx;
> +
> +	this_cpu_or(bpf_sk_storage_xmit.seen, BIT(idx));
> +}

[Severity: Medium]
Can bpf_sk_storage_xmit_mark() skip this_cpu_or() when BIT(idx) is
already set in bpf_sk_storage_xmit.seen?

Because seen is only cleared every 256 TCP transmits (and never on CPUs
not transmitting TCP), BIT(idx) is already set on almost every
bpf_sk_storage_get() and bpf_sk_storage_get_tracing() lookup.

Outside x86, arm64, and s390, this_cpu_or_2 falls back to
this_cpu_generic_to_op(), adding raw_local_irq_save() and
raw_local_irq_restore() to every lookup; on arm64 it executes an LSE
ldseth (or LL/SC loop) instead of a plain load.

Guarding the update with an unlikely check on
this_cpu_read(bpf_sk_storage_xmit.seen) & BIT(idx) avoids the atomic RMW
and IRQ disable on the steady-state lookup path.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204-sk_storage_prefetch-v1-0-ea52fb48b52b@meta.com?part=4

^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 3/5] bpf: tcp: Prefetch sk storage cache[] before TCP transmit
  2026-12-04 20:03 ` [PATCH bpf-next 3/5] bpf: tcp: Prefetch sk storage cache[] before TCP transmit Mykyta Yatsenko
@ 2026-12-04 20:23   ` sashiko-bot
  2026-12-04 21:25     ` Mykyta Yatsenko
  0 siblings, 1 reply; 13+ messages in thread
From: sashiko-bot @ 2026-12-04 20:23 UTC (permalink / raw)
  To: Mykyta Yatsenko, bpf

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] bpf: prefetchw() on read-only cache[] in
  bpf_sk_storage_prefetch_cache()
- [Medium] bpf: tcp: bpf_sk_storage_prefetch_cache() loads cold
  sk_bpf_storage on TX
--

commit 2c340de4783284547e3b378ba37fabbc3b62bef3
Author: Mykyta Yatsenko <yatsenko@meta.com>

bpf: tcp: Prefetch sk storage cache[] before TCP transmit

This commit adds a static-key-gated helper to prefetch a socket's BPF
local storage cache[] array at the start of tcp_sendmsg_locked() and
__tcp_transmit_skb(), enabled via a delayed work item whenever any
BPF_MAP_TYPE_SK_STORAGE map exists.

Link: https://lore.kernel.org/bpf/DN8A36W906WG.1BTUYRC2FIIR@gmail.com/
Link: https://github.com/llvm/llvm-project/pull/248194

> diff --git a/include/net/bpf_sk_storage.h b/include/net/bpf_sk_storage.h
> index 2926f1f00d656..c97cbc299bbb2 100644
> --- a/include/net/bpf_sk_storage.h
> +++ b/include/net/bpf_sk_storage.h

[ ... ]

> @@ -29,6 +31,29 @@ struct sk_buff;
>  struct nlattr;
>  
>  #ifdef CONFIG_BPF_SYSCALL
> +DECLARE_STATIC_KEY_FALSE(bpf_sk_storage_xmit_key);
> +
> +/*
> + * Prefetch cache[] of the storage of sk before a TCP transmit, so that an
> + * egress program does not wait for it. There is no RCU read lock: the storage
> + * can be freed at any time, so only prefetch it and never load from it.
> + * On x86-64, clang emits no instruction for prefetch(), so use prefetchw().
> + */
> +static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk)
> +{
> +	const void *storage;
> +
> +	if (!static_branch_unlikely(&bpf_sk_storage_xmit_key))
> +		return;
> +	storage = rcu_access_pointer(sk->sk_bpf_storage);
> +	if (!storage)
> +		return;

[Severity: Medium]
Does synchronously loading sk->sk_bpf_storage on every TCP transmit add a
cold cache miss for sockets that do not use egress sk_storage?

sk_bpf_storage sits in the cold tail cache line of struct sock alongside
sk_destruct, sk_reuseport_cb, and sk_rcu, outside sock_read_tx, so TCP TX
otherwise never touches it.

Because bpf_sk_storage_xmit_key is enabled whenever any sk_storage map
exists, workloads using sk_storage only outside egress (such as ingress
filters or tracing) take an extra cache miss in tcp_sendmsg_locked() and
__tcp_transmit_skb(), even when sk_bpf_storage is NULL.

Moving sk_bpf_storage into sock_read_tx or gating the prefetch on egress
BPF programs would avoid this TX cache footprint regression.

> +	/* cache[] is at the start of the storage: one or two cache lines */
> +	prefetchw(storage);
> +	if (sizeof_field(struct bpf_local_storage, cache) > SMP_CACHE_BYTES)
> +		prefetchw(storage + SMP_CACHE_BYTES);

[Severity: Medium]
Can prefetchw() on read-only storage->cache[] cause cross-CPU cache-line
bouncing on full-duplex TCP connections?

bpf_local_storage_lookup() only reads local_storage->cache[] on the fast
path.  On x86-64 with X86_FEATURE_3DNOWPREFETCH, prefetchw() issues RFO
and invalidates shared copies on other CPUs, causing MESI ping-pong when
TX and RX (tcp_v4_rcv() -> tcp_filter()) run on different CPUs.

Non-x86 architectures such as arm64 already emit inline assembly read
prefetches for prefetch() (prfm pldl1keep), so using prefetchw() forces
unnecessary store-intent prefetches (prfm pstl1keep) there as well.

In addition, bpf_local_storage_cache_idx_get() assigns slots starting
from index 0, so with 8 or fewer sk_storage maps cache[8..15] is never
used and unconditionally prefetching storage + SMP_CACHE_BYTES doubles
the unnecessary RFO and L1 traffic.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204-sk_storage_prefetch-v1-0-ea52fb48b52b@meta.com?part=3

^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 3/5] bpf: tcp: Prefetch sk storage cache[] before TCP transmit
  2026-12-04 20:23   ` sashiko-bot
@ 2026-12-04 21:25     ` Mykyta Yatsenko
  0 siblings, 0 replies; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 21:25 UTC (permalink / raw)
  To: sashiko-reviews, bpf



On 12/4/26 8:23 PM, sashiko-bot@kernel.org wrote:
> Thank you for your contribution! Sashiko AI review found 2 potential
> issues to consider:
> - [Medium] bpf: prefetchw() on read-only cache[] in
>   bpf_sk_storage_prefetch_cache()
> - [Medium] bpf: tcp: bpf_sk_storage_prefetch_cache() loads cold
>   sk_bpf_storage on TX
> --
> 
> commit 2c340de4783284547e3b378ba37fabbc3b62bef3
> Author: Mykyta Yatsenko <yatsenko@meta.com>
> 
> bpf: tcp: Prefetch sk storage cache[] before TCP transmit
> 
> This commit adds a static-key-gated helper to prefetch a socket's BPF
> local storage cache[] array at the start of tcp_sendmsg_locked() and
> __tcp_transmit_skb(), enabled via a delayed work item whenever any
> BPF_MAP_TYPE_SK_STORAGE map exists.
> 
> Link: https://lore.kernel.org/bpf/DN8A36W906WG.1BTUYRC2FIIR@gmail.com/
> Link: https://github.com/llvm/llvm-project/pull/248194
> 
>> diff --git a/include/net/bpf_sk_storage.h b/include/net/bpf_sk_storage.h
>> index 2926f1f00d656..c97cbc299bbb2 100644
>> --- a/include/net/bpf_sk_storage.h
>> +++ b/include/net/bpf_sk_storage.h
> 
> [ ... ]
> 
>> @@ -29,6 +31,29 @@ struct sk_buff;
>>  struct nlattr;
>>  
>>  #ifdef CONFIG_BPF_SYSCALL
>> +DECLARE_STATIC_KEY_FALSE(bpf_sk_storage_xmit_key);
>> +
>> +/*
>> + * Prefetch cache[] of the storage of sk before a TCP transmit, so that an
>> + * egress program does not wait for it. There is no RCU read lock: the storage
>> + * can be freed at any time, so only prefetch it and never load from it.
>> + * On x86-64, clang emits no instruction for prefetch(), so use prefetchw().
>> + */
>> +static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk)
>> +{
>> +	const void *storage;
>> +
>> +	if (!static_branch_unlikely(&bpf_sk_storage_xmit_key))
>> +		return;
>> +	storage = rcu_access_pointer(sk->sk_bpf_storage);
>> +	if (!storage)
>> +		return;
> 
> [Severity: Medium]
> Does synchronously loading sk->sk_bpf_storage on every TCP transmit add a
> cold cache miss for sockets that do not use egress sk_storage?

In this patch, yes, while any sk storage map exists. Patch 4 adds a
gate: the hooks do the load only when a bpf_sk_storage_get()
has marked a slot.

> 
> sk_bpf_storage sits in the cold tail cache line of struct sock alongside
> sk_destruct, sk_reuseport_cb, and sk_rcu, outside sock_read_tx, so TCP TX
> otherwise never touches it.
> 
> Because bpf_sk_storage_xmit_key is enabled whenever any sk_storage map
> exists, workloads using sk_storage only outside egress (such as ingress
> filters or tracing) take an extra cache miss in tcp_sendmsg_locked() and
> __tcp_transmit_skb(), even when sk_bpf_storage is NULL.
> 
> Moving sk_bpf_storage into sock_read_tx or gating the prefetch on egress
> BPF programs would avoid this TX cache footprint regression.
> 
>> +	/* cache[] is at the start of the storage: one or two cache lines */
>> +	prefetchw(storage);
>> +	if (sizeof_field(struct bpf_local_storage, cache) > SMP_CACHE_BYTES)
>> +		prefetchw(storage + SMP_CACHE_BYTES);
> 
> [Severity: Medium]
> Can prefetchw() on read-only storage->cache[] cause cross-CPU cache-line
> bouncing on full-duplex TCP connections?

Yes, theoretically, when programs on another CPU read the same storage.
The hooks use prefetchw() because, with clang, prefetch() emits no
instruction on x86-64, fixes for both kernel and llvm are submitted.
> 
> bpf_local_storage_lookup() only reads local_storage->cache[] on the fast
> path.  On x86-64 with X86_FEATURE_3DNOWPREFETCH, prefetchw() issues RFO
> and invalidates shared copies on other CPUs, causing MESI ping-pong when
> TX and RX (tcp_v4_rcv() -> tcp_filter()) run on different CPUs.
> 
> Non-x86 architectures such as arm64 already emit inline assembly read
> prefetches for prefetch() (prfm pldl1keep), so using prefetchw() forces
> unnecessary store-intent prefetches (prfm pstl1keep) there as well.
> 
> In addition, bpf_local_storage_cache_idx_get() assigns slots starting
> from index 0, so with 8 or fewer sk_storage maps cache[8..15] is never
> used and unconditionally prefetching storage + SMP_CACHE_BYTES doubles
> the unnecessary RFO and L1 traffic.
> 


^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 4/5] bpf: tcp: Prefetch values of hot sk storage maps before transmit
  2026-12-04 20:18   ` sashiko-bot
@ 2026-12-04 21:35     ` Mykyta Yatsenko
  0 siblings, 0 replies; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 21:35 UTC (permalink / raw)
  To: sashiko-reviews, bpf



On 12/4/26 8:18 PM, sashiko-bot@kernel.org wrote:
> Thank you for your contribution! Sashiko AI review found 3 potential
> issues to consider:
> - [Medium] bpf: unconditional per-CPU RMW in
>   bpf_sk_storage_prefetch_values()
> - [Medium] bpf: unconditional this_cpu_or() in
>   bpf_sk_storage_xmit_mark()
> - [Medium] bpf: RFO prefetchw() in bpf_sk_storage_prefetch_hot() bounces
>   shared lines
> --
> 
> commit f0130b9d642d8428468cd298e6da4b722527388b
> Author: Mykyta Yatsenko <yatsenko@meta.com>
> 
> bpf: tcp: Prefetch values of hot sk storage maps before transmit
> 
> This commit records which bpf_local_storage cache[] slots are looked up
> per CPU in bpf_sk_storage_get() and prefetches the elements in those
> slots from __tcp_transmit_skb() before calling ->queue_xmit(), clearing
> the per-CPU mask every 256 transmits.
> 
> Link: https://lore.kernel.org/bpf/DN8A36W906WG.1BTUYRC2FIIR@gmail.com/
> 
>> diff --git a/include/net/bpf_sk_storage.h b/include/net/bpf_sk_storage.h
>> index c97cbc299bbb2..ec12c3aaa9775 100644
>> --- a/include/net/bpf_sk_storage.h
>> +++ b/include/net/bpf_sk_storage.h
> 
> [ ... ]
> 
>> @@ -54,6 +66,20 @@ static inline void bpf_sk_storage_prefetch_cache(const struct sock *sk)
>>  		prefetchw(storage + SMP_CACHE_BYTES);
>>  }
>>  
>> +/* Prefetch the values of sk in the slots seen in this round of 256 transmits */
>> +static inline void bpf_sk_storage_prefetch_values(const struct sock *sk)
>> +{
>> +	u16 seen;
>> +
>> +	if (!static_branch_unlikely(&bpf_sk_storage_xmit_key))
>> +		return;
>> +	if (unlikely(!this_cpu_inc_return(bpf_sk_storage_xmit.round)))
>> +		this_cpu_write(bpf_sk_storage_xmit.seen, 0);
>> +	seen = this_cpu_read(bpf_sk_storage_xmit.seen);
>> +	if (seen && rcu_access_pointer(sk->sk_bpf_storage))
>> +		bpf_sk_storage_prefetch_hot(sk, seen);
>> +}
> 
> [Severity: Medium]
> Should bpf_sk_storage_prefetch_values() check bpf_sk_storage_xmit.seen
> before incrementing bpf_sk_storage_xmit.round?
> 
> Whenever any BPF_MAP_TYPE_SK_STORAGE map exists, __tcp_transmit_skb()
> runs this_cpu_inc_return(bpf_sk_storage_xmit.round) on every TCP segment,
> even on CPUs where seen is zero.
> 
> Outside x86, arm64, and s390, this_cpu_add_return_1 falls back to
> raw_local_irq_save()/raw_local_irq_restore() per packet.  On arm64 and
> x86-64 it still executes an atomic RMW (ldaddb or xaddb) with a memory
> clobber, dirtying the per-CPU cacheline on every transmit.
> 
> Reading seen first and returning when it is zero would skip the RMW when
> no slots are marked, matching bpf_sk_storage_prefetch_cache().

Agree.

> 
> [ ... ]
> 
>> diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c
>> index 875fff681869e..5feea65d25ea3 100644
>> --- a/net/core/bpf_sk_storage.c
>> +++ b/net/core/bpf_sk_storage.c
>> @@ -39,6 +39,43 @@ static void bpf_sk_storage_key_fn(struct work_struct *work)
> 
> [ ... ]
> 
>> +/* As in a lookup, the RCU read lock keeps the storage and the elements */
>> +void bpf_sk_storage_prefetch_hot(const struct sock *sk, unsigned long hot)
>> +{
>> +	struct bpf_local_storage_data *sdata;
>> +	struct bpf_local_storage *storage;
>> +	int i;
>> +
>> +	guard(rcu)();
>> +	storage = rcu_dereference(sk->sk_bpf_storage);
>> +	if (!storage)
>> +		return;
>> +	for_each_set_bit(i, &hot, BPF_LOCAL_STORAGE_CACHE_SIZE) {
>> +		sdata = rcu_dereference(storage->cache[i]);
>> +		if (sdata)
>> +			prefetchw(sdata);
>> +	}
>> +}
> 
> [Severity: Medium]
> Can prefetchw(sdata) here cause cross-CPU cacheline bouncing in
> full-duplex TCP workloads?
> 
> On x86-64 (with X86_FEATURE_3DNOWPREFETCH) and arm64 (prfm pstl1keep),
> prefetchw() issues a store-intent read-for-ownership prefetch that
> invalidates shared copies on other CPUs.  The same applies to the
> prefetchw() calls on storage->cache[] in bpf_sk_storage_prefetch_cache().
> 
> Because bpf_sk_storage_xmit_mark() runs for all bpf_sk_storage_get()
> callers, a map read only on the RX CPU is still pulled into exclusive
> state by the TX CPU on every transmit.  On arm64, prefetch() already
> emits prfm pldl1keep and does not need the x86-64 clang workaround.
> 

Same as previous patch.
>> +
>> +static void bpf_sk_storage_xmit_mark(struct bpf_map *map)
>> +{
>> +	u16 idx = ((struct bpf_local_storage_map *)map)->cache_idx;
>> +
>> +	this_cpu_or(bpf_sk_storage_xmit.seen, BIT(idx));
>> +}
> 
> [Severity: Medium]
> Can bpf_sk_storage_xmit_mark() skip this_cpu_or() when BIT(idx) is
> already set in bpf_sk_storage_xmit.seen?
> 
> Because seen is only cleared every 256 TCP transmits (and never on CPUs
> not transmitting TCP), BIT(idx) is already set on almost every
> bpf_sk_storage_get() and bpf_sk_storage_get_tracing() lookup.
> 
> Outside x86, arm64, and s390, this_cpu_or_2 falls back to
> this_cpu_generic_to_op(), adding raw_local_irq_save() and
> raw_local_irq_restore() to every lookup; on arm64 it executes an LSE
> ldseth (or LL/SC loop) instead of a plain load.
> 
> Guarding the update with an unlikely check on
> this_cpu_read(bpf_sk_storage_xmit.seen) & BIT(idx) avoids the atomic RMW
> and IRQ disable on the steady-state lookup path.
> 


^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit
  2026-12-04 20:03 [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit Mykyta Yatsenko
                   ` (4 preceding siblings ...)
  2026-12-04 20:03 ` [PATCH bpf-next 5/5] selftests/bpf: Test sk storage lookups during TCP transmit Mykyta Yatsenko
@ 2026-12-04 21:38 ` Andrii Nakryiko
  5 siblings, 0 replies; 13+ messages in thread
From: Andrii Nakryiko @ 2026-12-04 21:38 UTC (permalink / raw)
  To: Mykyta Yatsenko
  Cc: bpf, ast, andrii, daniel, kernel-team, eddyz87, memxor,
	Mykyta Yatsenko

On Fri, Dec 4, 2026 at 12:04 PM Mykyta Yatsenko
<mykyta.yatsenko5@gmail.com> wrote:
>
> An egress program that looks up the sk storage of a cold socket waits
> for two cache misses in a row. The first miss is on cache[] of the
> storage, and the second miss is on the element. A lookup of a value
> that the socket does not have is worse: it walks the whole list of the
> storage, with one miss for each element. With many connections, these
> misses are a large part of the program cost.
>
> This series replaces the BPF_F_INLINE_VALUE series [1] with the design
> that Alexei proposed [2], [3]:
> - Patch 1 makes a NULL cache[] slot mean that the storage has no value
>   for the slot, so that a lookup of an absent value stops at the first
>   load [3]. This patch is generic: task, inode and cgroup storage get
>   it too. Patch 2 tests maps that share slots.
> - Patch 3 prefetches cache[] when sendmsg starts and when a transmit
>   starts, because TCP knows the socket before the egress programs run.
> - Patch 4 learns on each CPU which cache[] slots the programs look up,
>   and prefetches the elements of these slots just before
>   ->queue_xmit(). Patch 5 tests the hooks under traffic.
> Patches 1-2 do not need patches 3-5. There is no UAPI change and no new
> limit.
>
> Changes from the prototype in [2]:
> - A work item changes the static key from a count of the maps. Map
>   create can run, and map free always runs, with migration disabled,
>   and a change of a static key takes cpus_read_lock(). This can
>   deadlock with a CPU offline: the key code of the prototype hung in a
>   CPU hotplug and light skeleton stress test.
> - Only bpf_sk_storage_get() marks a slot, for any socket. The prototype
>   marked the lookups of the last socket that sent on the CPU.
> - One mask of marked slots, cleared every 256 transmits. The prototype
>   kept a second mask with the slots of the last round.
> - The cache[] prefetch runs only on a CPU that has a marked slot.
> - The sendmsg prefetch is in tcp_sendmsg_locked(), so that kTLS,
>   sockmap and espintcp get it too.
> - this_cpu operations, because the hooks can run in preemptible process
>   context.
>
> Limits:
> - Patches 3-4 cover only TCP transmit and sk storage. The lookups of
>   all programs mark slots, so a map that only ingress or sock_ops
>   programs use also gets a prefetch on each transmit.
> - The static key is on while any sk storage map exists. While a CPU has
>   a hot slot, each transmit on that CPU loads sk->sk_bpf_storage. A
>   gate for each socket can come later, if a workload needs it.
> - With more than 16 maps, maps share cache[] slots, and a lookup of an
>   absent value in a shared slot can still walk the list.
>
> On x86-64, clang emits no instruction for prefetch(), because the
> kernel builds with -mno-sse [4], [5]. Thus the hooks use prefetchw().
>
> Results: AMD Zen 5 KVM guest, 4 server vCPUs, IPv6 over veth, 131072
> connections, 9 sk storage maps for each socket, bpf-next 2bf3351c5f89.
> 2 tc egress programs do 2 sk storage lookups on each packet. The change
> of the time in each lookup against base, from perf profiles, mean of 3
> runs:
>
>                                   lookup 1    lookup 2
>   both values present              -95.7%      -93.7%
>   lookup 2 finds no value          -96.4%      -99.5%

So just for awareness, we internally are testing a BPF-only
alternative that implements open-addressing hashmap for
"anything"-local storage (with fallback to socket/task/whatever local
storage if we run out of free slots or the number of collisions is too
high). We are still testing on real production workloads, but
preliminary results show 30% improvement in CPU cycles per BPF program
invocation.

I think it would be useful to try to test this approach and compare
performance *on real application*, not an artificial benchmark, so we
can make an informed decision on how helpful this is.

Kumar is working on this with internal customers, I think we can try
to build a custom kernel with these changes and evaluate them as well
some time next week.


>
> With patch 1 alone, the lookup that finds no value takes 98.7% less
> time, and the other lookups change by less than 4%. The local storage
> benchmarks in selftests show no change larger than the noise between
> runs.
>
> Signed-off-by: Mykyta Yatsenko <yatsenko@meta.com>
>
> [1] https://lore.kernel.org/bpf/20261123-sls_f1-v2-0-76474de9b052@meta.com/
> [2] https://lore.kernel.org/bpf/DN8A36W906WG.1BTUYRC2FIIR@gmail.com/
> [3] https://lore.kernel.org/bpf/DN92BUAQMX7H.3NKLFY0FRORT7@gmail.com/
> [4] https://lore.kernel.org/all/20261103060658.696994-1-martin.ankerl@gmail.com/
> [5] https://github.com/llvm/llvm-project/pull/248194
> [6] https://lore.kernel.org/bpf/DNAPOYTT6B0G.2RZJJ80T3HFKU@gmail.com/
>
> ---
> Mykyta Yatsenko (5):
>       bpf: Make a NULL cache slot mean that local storage has no value
>       selftests/bpf: Test sk storage maps that share cache slots
>       bpf: tcp: Prefetch sk storage cache[] before TCP transmit
>       bpf: tcp: Prefetch values of hot sk storage maps before transmit
>       selftests/bpf: Test sk storage lookups during TCP transmit
>
>  include/linux/bpf_local_storage.h                  |  14 +-
>  include/net/bpf_sk_storage.h                       |  53 +++++++
>  kernel/bpf/bpf_local_storage.c                     |  23 +++-
>  net/core/bpf_sk_storage.c                          |  69 +++++++++-
>  net/ipv4/tcp.c                                     |   2 +
>  net/ipv4/tcp_output.c                              |   3 +
>  .../bpf/prog_tests/sk_storage_shared_slots.c       |  57 ++++++++
>  .../selftests/bpf/prog_tests/sk_storage_xmit.c     | 153 +++++++++++++++++++++
>  .../testing/selftests/bpf/progs/sk_storage_xmit.c  |  46 +++++++
>  9 files changed, 415 insertions(+), 5 deletions(-)
> ---
> base-commit: 94299e4ad749bd5b361498b97b59f326bedac6fe
> change-id: 20261130-sk_storage_prefetch-575e7df22179
>
> Best regards,
> --
> Mykyta Yatsenko <yatsenko@meta.com>
>

^ permalink raw reply	[flat|nested] 13+ messages in thread

* Re: [PATCH bpf-next 5/5] selftests/bpf: Test sk storage lookups during TCP transmit
  2026-12-04 20:17   ` sashiko-bot
@ 2026-12-04 21:40     ` Mykyta Yatsenko
  0 siblings, 0 replies; 13+ messages in thread
From: Mykyta Yatsenko @ 2026-12-04 21:40 UTC (permalink / raw)
  To: sashiko-reviews, bpf



On 12/4/26 8:17 PM, sashiko-bot@kernel.org wrote:
> Thank you for your contribution! Sashiko AI review found 1 potential
> issue to consider:
> - [Low] selftests/bpf: scheduling race in churn() can fail deleted
>   assertion
> --
> 
> commit c50686a666890adca4b04b7b43ac8b9ddda340a7
> Author: Mykyta Yatsenko <yatsenko@meta.com>
> 
> selftests/bpf: Test sk storage lookups during TCP transmit
> 
> This commit adds the sk_storage_xmit BPF selftest to exercise concurrent
> sk_storage map lookups on TCP egress while user space deletes elements and
> destroys and reloads the maps.
> 
>> diff --git a/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c b/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c
>> new file mode 100644
>> index 0000000000000..9e80011e6630c
>> --- /dev/null
>> +++ b/tools/testing/selftests/bpf/prog_tests/sk_storage_xmit.c
> 
> [ ... ]
> 
>> +/* Delete the elements of cli for NR_TRIPS round trips */
>> +static void churn(struct sk_storage_xmit *skel, struct pair *p)
>> +{
>> +	struct bpf_map *a = skel->maps.sk_a, *b = skel->maps.sk_b;
>> +	__u64 end = get_time_ns() + TIMEOUT_NS;
>> +	int done = READ_ONCE(trips) + NR_TRIPS;
>> +	int deleted = 0;
>> +
>> +	while (!READ_ONCE(stop) && READ_ONCE(trips) < done &&
>> +	       get_time_ns() < end) {
>> +		deleted += !bpf_map__delete_elem(a, &p->cli, sizeof(p->cli), 0);
>> +		deleted += !bpf_map__delete_elem(b, &p->cli, sizeof(p->cli), 0);
>> +	}
>> +	ASSERT_GT(deleted, 0, "deleted");
>> +}
> 
> [Severity: Low]
> Can a scheduling delay between the main thread and ping_pong() make
> ASSERT_GT(deleted, 0, "deleted") fail spuriously?
> 
> ping_pong() runs continuously in a tight loopback round-trip loop without
> coordination with churn().  During the second churn() call, ping_pong() is
> already running at full speed:
> 
> main thread                       ping_pong thread
> churn()
>   done = READ_ONCE(trips) + 1000
>   (preempted)
>                                   round_trip() x 1000
>                                     WRITE_ONCE(trips, trips + 1)
>   while (READ_ONCE(trips) < done)
>     /* exits with deleted == 0 */
>   ASSERT_GT(deleted, 0, ...)  <-- spurious failure
> 
> On an oversubscribed or single-CPU VM, preemption of the main thread lets
> trips reach done before bpf_map__delete_elem() succeeds once, failing the
> test even though the kernel behaved correctly.
> 
> Looping while (READ_ONCE(trips) < done || !deleted), still bounded by
> !READ_ONCE(stop) and get_time_ns() < end, would avoid this race.

Agree.

> 


^ permalink raw reply	[flat|nested] 13+ messages in thread

end of thread, other threads:[~2026-12-04 21:40 UTC | newest]

Thread overview: 13+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04 20:03 [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before TCP transmit Mykyta Yatsenko
2026-12-04 20:03 ` [PATCH bpf-next 1/5] bpf: Make a NULL cache slot mean that local storage has no value Mykyta Yatsenko
2026-12-04 20:03 ` [PATCH bpf-next 2/5] selftests/bpf: Test sk storage maps that share cache slots Mykyta Yatsenko
2026-12-04 20:03 ` [PATCH bpf-next 3/5] bpf: tcp: Prefetch sk storage cache[] before TCP transmit Mykyta Yatsenko
2026-12-04 20:23   ` sashiko-bot
2026-12-04 21:25     ` Mykyta Yatsenko
2026-12-04 20:03 ` [PATCH bpf-next 4/5] bpf: tcp: Prefetch values of hot sk storage maps before transmit Mykyta Yatsenko
2026-12-04 20:18   ` sashiko-bot
2026-12-04 21:35     ` Mykyta Yatsenko
2026-12-04 20:03 ` [PATCH bpf-next 5/5] selftests/bpf: Test sk storage lookups during TCP transmit Mykyta Yatsenko
2026-12-04 20:17   ` sashiko-bot
2026-12-04 21:40     ` Mykyta Yatsenko
2026-12-04 21:38 ` [PATCH bpf-next 0/5] bpf: tcp: Prefetch sk storage before " Andrii Nakryiko

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox