Skip to contentSkip to conversation

bpf: refactor max_depth computation in bpf_get_stack()

PATCH In review Arnaud Lecomte 2 participants 10 messages Sep 12, 2025 – Oct 25, 2025 1 message not in the archive

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH v9 1/3 bpf: refactor max_depth computation in bpf_get_stack()

A new helper function stack_map_calculate_max_depth() that computes the max depth for a stackmap.

---
Changes in v2:
- Removed the checking 'map_size % map_elem_size' from stack_map_calculate_max_depth
- Changed stack_map_calculate_max_depth params name to be more generic

Changes in v3:
- Changed map size param to size in max depth helper

Changes in v4:
- Fixed indentation in max depth helper for args

Changes in v5:
- Bound back trace_nr to num_elem in __bpf_get_stack
- Make a copy of sysctl_perf_event_max_stack in stack_map_calculate_max_depth

Changes in v6:
- Restrained max_depth computation only when required
- Additional cleanup from Song in __bpf_get_stack

Changes in v7:
- Removed additional cleanup from v6

Changes in v9:
- Fixed incorrect removal of num_elem in get stack

Link to v8: https://lore.kernel.org/all/[email protected]/
---

---
 kernel/bpf/stackmap.c | 39 +++++++++++++++++++++++++++------------
 1 file changed, 27 insertions(+), 12 deletions(-)
kernel/bpf/stackmap.c +27 -12
index 3615c06b7dfa..a794e04f5ae9 100644
@@ -42,6 +42,28 @@ static inline int stack_map_data_size(struct bpf_map *map)
 		sizeof(struct bpf_stack_build_id) : sizeof(u64);
 }
 
+/**
+ * stack_map_calculate_max_depth - Calculate maximum allowed stack trace depth
+ * @size:  Size of the buffer/map value in bytes
+ * @elem_size:  Size of each stack trace element
+ * @flags:  BPF stack trace flags (BPF_F_USER_STACK, BPF_F_USER_BUILD_ID, ...)
+ *
+ * Return: Maximum number of stack trace entries that can be safely stored
+ */
+static u32 stack_map_calculate_max_depth(u32 size, u32 elem_size, u64 flags)
+{
+	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+	u32 max_depth;
+	u32 curr_sysctl_max_stack = READ_ONCE(sysctl_perf_event_max_stack);
+
+	max_depth = size / elem_size;
+	max_depth += skip;
+	if (max_depth > curr_sysctl_max_stack)
+		return curr_sysctl_max_stack;
+
+	return max_depth;
+}
+
 static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
 {
 	u64 elem_size = sizeof(struct stack_map_bucket) +
@@ -300,20 +322,17 @@ static long __bpf_get_stackid(struct bpf_map *map,
 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
 	   u64, flags)
 {
-	u32 max_depth = map->value_size / stack_map_data_size(map);
-	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+	u32 elem_size = stack_map_data_size(map);
 	bool user = flags & BPF_F_USER_STACK;
 	struct perf_callchain_entry *trace;
 	bool kernel = !user;
+	u32 max_depth;
 
 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
 			       BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
 		return -EINVAL;
 
-	max_depth += skip;
-	if (max_depth > sysctl_perf_event_max_stack)
-		max_depth = sysctl_perf_event_max_stack;
-
+	max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags);
 	trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
 				   false, false);
 
@@ -406,7 +425,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 			    struct perf_callchain_entry *trace_in,
 			    void *buf, u32 size, u64 flags, bool may_fault)
 {
-	u32 trace_nr, copy_len, elem_size, num_elem, max_depth;
+	u32 trace_nr, copy_len, elem_size, max_depth;
 	bool user_build_id = flags & BPF_F_USER_BUILD_ID;
 	bool crosstask = task && task != current;
 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
@@ -438,10 +457,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 		goto clear;
 	}
 
-	num_elem = size / elem_size;
-	max_depth = num_elem + skip;
-	if (sysctl_perf_event_max_stack < max_depth)
-		max_depth = sysctl_perf_event_max_stack;
+	max_depth = stack_map_calculate_max_depth(size, elem_size, flags);
 
 	if (may_fault)
 		rcu_read_lock(); /* need RCU for perf's callchain below */
@@ -461,7 +477,6 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 	}
 
 	trace_nr = trace->nr - skip;
-	trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;
 	copy_len = trace_nr * elem_size;
 
 	ips = trace->ip + skip;
Signature · 1 line
2.43.0
#1 lore raw

PATCH v9 2/3 bpf: clean-up bounds checking in __bpf_get_stack

Clean-up bounds checking for trace->nr in
__bpf_get_stack by limiting it only to
max_depth.

---
 kernel/bpf/stackmap.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
kernel/bpf/stackmap.c +5 -3
index a794e04f5ae9..9a86b5acac10 100644
@@ -462,13 +462,15 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 	if (may_fault)
 		rcu_read_lock(); /* need RCU for perf's callchain below */
 
-	if (trace_in)
+	if (trace_in) {
 		trace = trace_in;
-	else if (kernel && task)
+		trace->nr = min_t(u32, trace->nr, max_depth);
+	} else if (kernel && task) {
 		trace = get_callchain_entry_for_task(task, max_depth);
-	else
+	} else {
 		trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
 					   crosstask, false);
+	}
 
 	if (unlikely(!trace) || trace->nr < skip) {
 		if (may_fault)
Signature · 1 line
2.43.0
#2 lore raw

PATCH v9 3/3 bpf: fix stackmap overflow check in __bpf_get_stackid()

Syzkaller reported a KASAN slab-out-of-bounds write in __bpf_get_stackid() when copying stack trace data. The issue occurs when the perf trace
contains more stack entries than the stack map bucket can hold, leading to an out-of-bounds write in the bucket's data array.

Reported-by [email protected]
Fixes ee2a098851bf ("bpf: Adjust BPF stack helper functions to accommodate skip > 0")

---
Changes in v2:
- Fixed max_depth names across get stack id

Changes in v4:
- Removed unnecessary empty line in __bpf_get_stackid

Changes in v6:
- Added back trace_len computation in __bpf_get_stackid

Changes in v7:
- Removed usefull trace->nr assignation in bpf_get_stackid_pe
- Added restoration of trace->nr for both kernel and user traces in bpf_get_stackid_pe

Changes in v9:
- Fixed variable declarations in bpf_get_stackid_pe
- Added the missing truncate of trace_nr in __bpf_getstackid

Link to v8: https://lore.kernel.org/all/[email protected]/
---

---
 kernel/bpf/stackmap.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)
kernel/bpf/stackmap.c +16 -5
index 9a86b5acac10..ac5ec3253ce6 100644
@@ -251,8 +251,8 @@ static long __bpf_get_stackid(struct bpf_map *map,
 {
 	struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
 	struct stack_map_bucket *bucket, *new_bucket, *old_bucket;
+	u32 hash, id, trace_nr, trace_len, i, max_storable;
 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
-	u32 hash, id, trace_nr, trace_len, i;
 	bool user = flags & BPF_F_USER_STACK;
 	u64 *ips;
 	bool hash_matches;
@@ -261,7 +261,9 @@ static long __bpf_get_stackid(struct bpf_map *map,
 		/* skipping more than usable stack trace */
 		return -EFAULT;
 
+	max_storable = map->value_size / stack_map_data_size(map);
 	trace_nr = trace->nr - skip;
+	trace_nr = min_t(u32, trace_nr, max_storable);
 	trace_len = trace_nr * sizeof(u64);
 	ips = trace->ip + skip;
 	hash = jhash2((u32 *)ips, trace_len / sizeof(u32), 0);
@@ -369,6 +371,7 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 {
 	struct perf_event *event = ctx->event;
 	struct perf_callchain_entry *trace;
+	u32 elem_size, max_depth;
 	bool kernel, user;
 	__u64 nr_kernel;
 	int ret;
@@ -390,15 +393,16 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 		return -EFAULT;
 
 	nr_kernel = count_kernel_ip(trace);
+	elem_size = stack_map_data_size(map);
+	__u64 nr = trace->nr; /* save original */
 
 	if (kernel) {
-		__u64 nr = trace->nr;
-
 		trace->nr = nr_kernel;
+		max_depth =
+			stack_map_calculate_max_depth(map->value_size, elem_size, flags);
+		trace->nr = min_t(u32, nr_kernel, max_depth);
 		ret = __bpf_get_stackid(map, trace, flags);
 
-		/* restore nr */
-		trace->nr = nr;
 	} else { /* user */
 		u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
 
@@ -407,8 +411,15 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 			return -EFAULT;
 
 		flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
+		max_depth =
+			stack_map_calculate_max_depth(map->value_size, elem_size, flags);
+		trace->nr = min_t(u32, trace->nr, max_depth);
 		ret = __bpf_get_stackid(map, trace, flags);
 	}
+
+	/* restore nr */
+	trace->nr = nr;
+
 	return ret;
 }
 
Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH bpf-next v9 3/3] bpf: fix stackmap overflow check in __bpf_get_stackid()

Quoted 70 lines · Arnaud Lecomte

Syzkaller reported a KASAN slab-out-of-bounds write in __bpf_get_stackid() when copying stack trace data. The issue occurs when the perf trace
contains more stack entries than the stack map bucket can hold, leading to an out-of-bounds write in the bucket's data array.

Reported-by [email protected]
Fixes ee2a098851bf ("bpf: Adjust BPF stack helper functions to accommodate skip > 0")

---
Changes in v2:
- Fixed max_depth names across get stack id

Changes in v4:
- Removed unnecessary empty line in __bpf_get_stackid

Changes in v6:
- Added back trace_len computation in __bpf_get_stackid

Changes in v7:
- Removed usefull trace->nr assignation in bpf_get_stackid_pe
- Added restoration of trace->nr for both kernel and user traces in bpf_get_stackid_pe

Changes in v9:
- Fixed variable declarations in bpf_get_stackid_pe
- Added the missing truncate of trace_nr in __bpf_getstackid

Link to v8: https://lore.kernel.org/all/[email protected]/
---

---
 kernel/bpf/stackmap.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)
kernel/bpf/stackmap.c +4 -1
index 9a86b5acac10..ac5ec3253ce6 100644
@@ -251,8 +251,8 @@ static long __bpf_get_stackid(struct bpf_map *map,
 {
        struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
        struct stack_map_bucket *bucket, *new_bucket, *old_bucket;
+       u32 hash, id, trace_nr, trace_len, i, max_storable;
        u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
-       u32 hash, id, trace_nr, trace_len, i;
        bool user = flags & BPF_F_USER_STACK;
        u64 *ips;
        bool hash_matches;
@@ -261,7 +261,9 @@ static long __bpf_get_stackid(struct bpf_map *map,
                /* skipping more than usable stack trace */
                return -EFAULT;
 
+       max_storable = map->value_size / stack_map_data_size(map);
        trace_nr = trace->nr - skip;
+       trace_nr = min_t(u32, trace_nr, max_storable);
        trace_len = trace_nr * sizeof(u64);
        ips = trace->ip + skip;
        hash = jhash2((u32 *)ips, trace_len / sizeof(u32), 0);
@@ -369,6 +371,7 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 {
        struct perf_event *event = ctx->event;
        struct perf_callchain_entry *trace;
+       u32 elem_size, max_depth;
        bool kernel, user;
        __u64 nr_kernel;
        int ret;

kernel/bpf/stackmap.c BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx, · line 400

Quoted 10 lines
kernel/bpf/stackmap.c +2 -2
@@ -390,15 +393,16 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
                return -EFAULT;
 
        nr_kernel = count_kernel_ip(trace);
+       elem_size = stack_map_data_size(map);
+       __u64 nr = trace->nr; /* save original */
 
        if (kernel) {
-               __u64 nr = trace->nr;
-
                trace->nr = nr_kernel;

unnecessary, you'll be overriding it two lines below

kernel/bpf/stackmap.c BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx, · line 402

Quoted 2 lines
kernel/bpf/stackmap.c +2 -0
+               max_depth =
+                       stack_map_calculate_max_depth(map->value_size, elem_size, flags);

here and below, keep on the same line, it's under 100 characters

Quoted 27 lines
kernel/bpf/stackmap.c +8 -3
+               trace->nr = min_t(u32, nr_kernel, max_depth);
                ret = __bpf_get_stackid(map, trace, flags);
 
-               /* restore nr */
-               trace->nr = nr;
        } else { /* user */
                u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
 
@@ -407,8 +411,15 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
                        return -EFAULT;
 
                flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
+               max_depth =
+                       stack_map_calculate_max_depth(map->value_size, elem_size, flags);
+               trace->nr = min_t(u32, trace->nr, max_depth);
                ret = __bpf_get_stackid(map, trace, flags);
        }
+
+       /* restore nr */
+       trace->nr = nr;
+
        return ret;
 }
 
--

2.43.0

#4 lore raw
In reply to Arnaud Lecomte
Quoted 119 lines · Arnaud Lecomte

A new helper function stack_map_calculate_max_depth() that computes the max depth for a stackmap.

---
Changes in v2:
- Removed the checking 'map_size % map_elem_size' from stack_map_calculate_max_depth
- Changed stack_map_calculate_max_depth params name to be more generic

Changes in v3:
- Changed map size param to size in max depth helper

Changes in v4:
- Fixed indentation in max depth helper for args

Changes in v5:
- Bound back trace_nr to num_elem in __bpf_get_stack
- Make a copy of sysctl_perf_event_max_stack in stack_map_calculate_max_depth

Changes in v6:
- Restrained max_depth computation only when required
- Additional cleanup from Song in __bpf_get_stack

Changes in v7:
- Removed additional cleanup from v6

Changes in v9:
- Fixed incorrect removal of num_elem in get stack

Link to v8: https://lore.kernel.org/all/[email protected]/
---

---
 kernel/bpf/stackmap.c | 39 +++++++++++++++++++++++++++------------
 1 file changed, 27 insertions(+), 12 deletions(-)
kernel/bpf/stackmap.c +27 -11
index 3615c06b7dfa..a794e04f5ae9 100644
@@ -42,6 +42,28 @@ static inline int stack_map_data_size(struct bpf_map *map)
                sizeof(struct bpf_stack_build_id) : sizeof(u64);
 }
 
+/**
+ * stack_map_calculate_max_depth - Calculate maximum allowed stack trace depth
+ * @size:  Size of the buffer/map value in bytes
+ * @elem_size:  Size of each stack trace element
+ * @flags:  BPF stack trace flags (BPF_F_USER_STACK, BPF_F_USER_BUILD_ID, ...)
+ *
+ * Return: Maximum number of stack trace entries that can be safely stored
+ */
+static u32 stack_map_calculate_max_depth(u32 size, u32 elem_size, u64 flags)
+{
+       u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+       u32 max_depth;
+       u32 curr_sysctl_max_stack = READ_ONCE(sysctl_perf_event_max_stack);
+
+       max_depth = size / elem_size;
+       max_depth += skip;
+       if (max_depth > curr_sysctl_max_stack)
+               return curr_sysctl_max_stack;
+
+       return max_depth;
+}
+
 static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
 {
        u64 elem_size = sizeof(struct stack_map_bucket) +
@@ -300,20 +322,17 @@ static long __bpf_get_stackid(struct bpf_map *map,
 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
           u64, flags)
 {
-       u32 max_depth = map->value_size / stack_map_data_size(map);
-       u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+       u32 elem_size = stack_map_data_size(map);
        bool user = flags & BPF_F_USER_STACK;
        struct perf_callchain_entry *trace;
        bool kernel = !user;
+       u32 max_depth;
 
        if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
                               BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
                return -EINVAL;
 
-       max_depth += skip;
-       if (max_depth > sysctl_perf_event_max_stack)
-               max_depth = sysctl_perf_event_max_stack;
-
+       max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags);
        trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
                                   false, false);
 
@@ -406,7 +425,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
                            struct perf_callchain_entry *trace_in,
                            void *buf, u32 size, u64 flags, bool may_fault)
 {
-       u32 trace_nr, copy_len, elem_size, num_elem, max_depth;
+       u32 trace_nr, copy_len, elem_size, max_depth;
        bool user_build_id = flags & BPF_F_USER_BUILD_ID;
        bool crosstask = task && task != current;
        u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
@@ -438,10 +457,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
                goto clear;
        }
 
-       num_elem = size / elem_size;
-       max_depth = num_elem + skip;
-       if (sysctl_perf_event_max_stack < max_depth)
-               max_depth = sysctl_perf_event_max_stack;
+       max_depth = stack_map_calculate_max_depth(size, elem_size, flags);
 
        if (may_fault)
                rcu_read_lock(); /* need RCU for perf's callchain below */

kernel/bpf/stackmap.c static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, · line 464

Quoted 4 lines
kernel/bpf/stackmap.c +0 -1
@@ -461,7 +477,6 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
        }
 
        trace_nr = trace->nr - skip;
-       trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;

Is this also part of refactoring? If yes, it deserves a mention on why it's ok to just drop this.

pw-bot: cr

Quoted 6 lines
kernel/bpf/stackmap.c +0 -1
        copy_len = trace_nr * elem_size;
 
        ips = trace->ip + skip;
--

2.43.0

#5 lore raw
Quoted 121 lines · Andrii Nakryiko
Quoted 120 lines · Arnaud Lecomte

A new helper function stack_map_calculate_max_depth() that computes the max depth for a stackmap.

---
Changes in v2:
- Removed the checking 'map_size % map_elem_size' from stack_map_calculate_max_depth
- Changed stack_map_calculate_max_depth params name to be more generic

Changes in v3:
- Changed map size param to size in max depth helper

Changes in v4:
- Fixed indentation in max depth helper for args

Changes in v5:
- Bound back trace_nr to num_elem in __bpf_get_stack
- Make a copy of sysctl_perf_event_max_stack in stack_map_calculate_max_depth

Changes in v6:
- Restrained max_depth computation only when required
- Additional cleanup from Song in __bpf_get_stack

Changes in v7:
- Removed additional cleanup from v6

Changes in v9:
- Fixed incorrect removal of num_elem in get stack

Link to v8: https://lore.kernel.org/all/[email protected]/
---

---
  kernel/bpf/stackmap.c | 39 +++++++++++++++++++++++++++------------
  1 file changed, 27 insertions(+), 12 deletions(-)
kernel/bpf/stackmap.c +27 -11
index 3615c06b7dfa..a794e04f5ae9 100644
@@ -42,6 +42,28 @@ static inline int stack_map_data_size(struct bpf_map *map)
                 sizeof(struct bpf_stack_build_id) : sizeof(u64);
  }
 
+/**
+ * stack_map_calculate_max_depth - Calculate maximum allowed stack trace depth
+ * @size:  Size of the buffer/map value in bytes
+ * @elem_size:  Size of each stack trace element
+ * @flags:  BPF stack trace flags (BPF_F_USER_STACK, BPF_F_USER_BUILD_ID, ...)
+ *
+ * Return: Maximum number of stack trace entries that can be safely stored
+ */
+static u32 stack_map_calculate_max_depth(u32 size, u32 elem_size, u64 flags)
+{
+       u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+       u32 max_depth;
+       u32 curr_sysctl_max_stack = READ_ONCE(sysctl_perf_event_max_stack);
+
+       max_depth = size / elem_size;
+       max_depth += skip;
+       if (max_depth > curr_sysctl_max_stack)
+               return curr_sysctl_max_stack;
+
+       return max_depth;
+}
+
  static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
  {
         u64 elem_size = sizeof(struct stack_map_bucket) +
@@ -300,20 +322,17 @@ static long __bpf_get_stackid(struct bpf_map *map,
  BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
            u64, flags)
  {
-       u32 max_depth = map->value_size / stack_map_data_size(map);
-       u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+       u32 elem_size = stack_map_data_size(map);
         bool user = flags & BPF_F_USER_STACK;
         struct perf_callchain_entry *trace;
         bool kernel = !user;
+       u32 max_depth;
 
         if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
                                BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
                 return -EINVAL;
 
-       max_depth += skip;
-       if (max_depth > sysctl_perf_event_max_stack)
-               max_depth = sysctl_perf_event_max_stack;
-
+       max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags);
         trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
                                    false, false);
 
@@ -406,7 +425,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
                             struct perf_callchain_entry *trace_in,
                             void *buf, u32 size, u64 flags, bool may_fault)
  {
-       u32 trace_nr, copy_len, elem_size, num_elem, max_depth;
+       u32 trace_nr, copy_len, elem_size, max_depth;
         bool user_build_id = flags & BPF_F_USER_BUILD_ID;
         bool crosstask = task && task != current;
         u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
@@ -438,10 +457,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
                 goto clear;
         }
 
-       num_elem = size / elem_size;
-       max_depth = num_elem + skip;
-       if (sysctl_perf_event_max_stack < max_depth)
-               max_depth = sysctl_perf_event_max_stack;
+       max_depth = stack_map_calculate_max_depth(size, elem_size, flags);
 
         if (may_fault)
                 rcu_read_lock(); /* need RCU for perf's callchain below */
@@ -461,7 +477,6 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
         }
 
Quoted 7 lines

kernel/bpf/stackmap.c static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, · line 464

Quoted 2 lines
kernel/bpf/stackmap.c +0 -1
         trace_nr = trace->nr - skip;
-       trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;

Is this also part of refactoring? If yes, it deserves a mention on why it's ok to just drop this.

pw-bot: cr

Yes it is also part of the refactoring as stack_map_calculate_max_depth now already curtains the trace->nr to the max possible number of elements, there is no need to do the clamping twice. This is valid assuming that get_perf_callchain and get_callchain_entry_for_task correctly set this limit.

Quoted 7 lines
Quoted 7 lines
kernel/bpf/stackmap.c +0 -1
         copy_len = trace_nr * elem_size;
 
         ips = trace->ip + skip;
--

2.43.0

Thanks,
Arnaud

A message that is not in the archive (sent off-list or not yet received): [email protected]

#7 lore raw
Quoted 132 lines · Arnaud

On 19/09/2025 23:50, Andrii Nakryiko wrote:

On Fri, Sep 12, 2025 at 4:34 PM Arnaud Lecomte <[email protected]> wrote:

A new helper function stack_map_calculate_max_depth() that computes the max depth for a stackmap.

---
Changes in v2:
- Removed the checking 'map_size % map_elem_size' from stack_map_calculate_max_depth
- Changed stack_map_calculate_max_depth params name to be more generic

Changes in v3:
- Changed map size param to size in max depth helper

Changes in v4:
- Fixed indentation in max depth helper for args

Changes in v5:
- Bound back trace_nr to num_elem in __bpf_get_stack
- Make a copy of sysctl_perf_event_max_stack in stack_map_calculate_max_depth

Changes in v6:
- Restrained max_depth computation only when required
- Additional cleanup from Song in __bpf_get_stack

Changes in v7:
- Removed additional cleanup from v6

Changes in v9:
- Fixed incorrect removal of num_elem in get stack

Link to v8: https://lore.kernel.org/all/[email protected]/
---

---
 kernel/bpf/stackmap.c | 39 +++++++++++++++++++++++++++------------
 1 file changed, 27 insertions(+), 12 deletions(-)
kernel/bpf/stackmap.c +27 -12
index 3615c06b7dfa..a794e04f5ae9 100644
@@ -42,6 +42,28 @@ static inline int stack_map_data_size(struct bpf_map *map)
                sizeof(struct bpf_stack_build_id) : sizeof(u64);
 }
 
+/**
+ * stack_map_calculate_max_depth - Calculate maximum allowed stack trace depth
+ * @size:  Size of the buffer/map value in bytes
+ * @elem_size:  Size of each stack trace element
+ * @flags:  BPF stack trace flags (BPF_F_USER_STACK, BPF_F_USER_BUILD_ID, ...)
+ *
+ * Return: Maximum number of stack trace entries that can be safely stored
+ */
+static u32 stack_map_calculate_max_depth(u32 size, u32 elem_size, u64 flags)
+{
+       u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+       u32 max_depth;
+       u32 curr_sysctl_max_stack = READ_ONCE(sysctl_perf_event_max_stack);
+
+       max_depth = size / elem_size;
+       max_depth += skip;
+       if (max_depth > curr_sysctl_max_stack)
+               return curr_sysctl_max_stack;
+
+       return max_depth;
+}
+
 static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
 {
        u64 elem_size = sizeof(struct stack_map_bucket) +
@@ -300,20 +322,17 @@ static long __bpf_get_stackid(struct bpf_map *map,
 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
           u64, flags)
 {
-       u32 max_depth = map->value_size / stack_map_data_size(map);
-       u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+       u32 elem_size = stack_map_data_size(map);
        bool user = flags & BPF_F_USER_STACK;
        struct perf_callchain_entry *trace;
        bool kernel = !user;
+       u32 max_depth;
 
        if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
                               BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
                return -EINVAL;
 
-       max_depth += skip;
-       if (max_depth > sysctl_perf_event_max_stack)
-               max_depth = sysctl_perf_event_max_stack;
-
+       max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags);
        trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
                                   false, false);
 
@@ -406,7 +425,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
                            struct perf_callchain_entry *trace_in,
                            void *buf, u32 size, u64 flags, bool may_fault)
 {
-       u32 trace_nr, copy_len, elem_size, num_elem, max_depth;
+       u32 trace_nr, copy_len, elem_size, max_depth;
        bool user_build_id = flags & BPF_F_USER_BUILD_ID;
        bool crosstask = task && task != current;
        u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
@@ -438,10 +457,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
                goto clear;
        }
 
-       num_elem = size / elem_size;
-       max_depth = num_elem + skip;
-       if (sysctl_perf_event_max_stack < max_depth)
-               max_depth = sysctl_perf_event_max_stack;
+       max_depth = stack_map_calculate_max_depth(size, elem_size, flags);
 
        if (may_fault)
                rcu_read_lock(); /* need RCU for perf's callchain below */
@@ -461,7 +477,6 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
        }
 
        trace_nr = trace->nr - skip;
-       trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;
 

Is this also part of refactoring? If yes, it deserves a mention on why it's ok to just drop this.

Quoted 4 lines

pw-bot: cr

Yes it is also part of the refactoring as stack_map_calculate_max_depth now already curtains the trace->nr to the max possible number of elements, there is no need to do the clamping twice. This is valid assuming that get_perf_callchain and get_callchain_entry_for_task correctly set this limit.

What about that third case:

if (trace_in)

    trace = trace_in;

Did you analyze if that gets its trace->nr set properly as well (as of this patch, without taking into account changes in the follow up patches). Because it looks like this removal belongs in patch #2, no?

In either case, all the other changes in this patch except the removal of this line is refactoring and as far as I can tell don't change the logic. This line removal does (potentially) change the logic, so it would be good to do it separately, explaining why you think it's the correct thing to do.

Quoted 8 lines
        copy_len = trace_nr * elem_size;

        ips = trace->ip + skip;

--
2.43.0

Thanks,
Arnaud

#8 lore raw
Quoted 145 lines · Andrii Nakryiko
Quoted 131 lines · Arnaud

On 19/09/2025 23:50, Andrii Nakryiko wrote:

On Fri, Sep 12, 2025 at 4:34 PM Arnaud Lecomte <[email protected]> wrote:

A new helper function stack_map_calculate_max_depth() that computes the max depth for a stackmap.

---
Changes in v2:
- Removed the checking 'map_size % map_elem_size' from stack_map_calculate_max_depth
- Changed stack_map_calculate_max_depth params name to be more generic

Changes in v3:
- Changed map size param to size in max depth helper

Changes in v4:
- Fixed indentation in max depth helper for args

Changes in v5:
- Bound back trace_nr to num_elem in __bpf_get_stack
- Make a copy of sysctl_perf_event_max_stack in stack_map_calculate_max_depth

Changes in v6:
- Restrained max_depth computation only when required
- Additional cleanup from Song in __bpf_get_stack

Changes in v7:
- Removed additional cleanup from v6

Changes in v9:
- Fixed incorrect removal of num_elem in get stack

Link to v8: https://lore.kernel.org/all/[email protected]/
---

---
  kernel/bpf/stackmap.c | 39 +++++++++++++++++++++++++++------------
  1 file changed, 27 insertions(+), 12 deletions(-)
kernel/bpf/stackmap.c +27 -12
index 3615c06b7dfa..a794e04f5ae9 100644
@@ -42,6 +42,28 @@ static inline int stack_map_data_size(struct bpf_map *map)
                 sizeof(struct bpf_stack_build_id) : sizeof(u64);
  }
 
+/**
+ * stack_map_calculate_max_depth - Calculate maximum allowed stack trace depth
+ * @size:  Size of the buffer/map value in bytes
+ * @elem_size:  Size of each stack trace element
+ * @flags:  BPF stack trace flags (BPF_F_USER_STACK, BPF_F_USER_BUILD_ID, ...)
+ *
+ * Return: Maximum number of stack trace entries that can be safely stored
+ */
+static u32 stack_map_calculate_max_depth(u32 size, u32 elem_size, u64 flags)
+{
+       u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+       u32 max_depth;
+       u32 curr_sysctl_max_stack = READ_ONCE(sysctl_perf_event_max_stack);
+
+       max_depth = size / elem_size;
+       max_depth += skip;
+       if (max_depth > curr_sysctl_max_stack)
+               return curr_sysctl_max_stack;
+
+       return max_depth;
+}
+
  static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
  {
         u64 elem_size = sizeof(struct stack_map_bucket) +
@@ -300,20 +322,17 @@ static long __bpf_get_stackid(struct bpf_map *map,
  BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
            u64, flags)
  {
-       u32 max_depth = map->value_size / stack_map_data_size(map);
-       u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+       u32 elem_size = stack_map_data_size(map);
         bool user = flags & BPF_F_USER_STACK;
         struct perf_callchain_entry *trace;
         bool kernel = !user;
+       u32 max_depth;
 
         if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
                                BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
                 return -EINVAL;
 
-       max_depth += skip;
-       if (max_depth > sysctl_perf_event_max_stack)
-               max_depth = sysctl_perf_event_max_stack;
-
+       max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags);
         trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
                                    false, false);
 
@@ -406,7 +425,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
                             struct perf_callchain_entry *trace_in,
                             void *buf, u32 size, u64 flags, bool may_fault)
  {
-       u32 trace_nr, copy_len, elem_size, num_elem, max_depth;
+       u32 trace_nr, copy_len, elem_size, max_depth;
         bool user_build_id = flags & BPF_F_USER_BUILD_ID;
         bool crosstask = task && task != current;
         u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
@@ -438,10 +457,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
                 goto clear;
         }
 
-       num_elem = size / elem_size;
-       max_depth = num_elem + skip;
-       if (sysctl_perf_event_max_stack < max_depth)
-               max_depth = sysctl_perf_event_max_stack;
+       max_depth = stack_map_calculate_max_depth(size, elem_size, flags);
 
         if (may_fault)
                 rcu_read_lock(); /* need RCU for perf's callchain below */
@@ -461,7 +477,6 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
         }
 
         trace_nr = trace->nr - skip;
-       trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;
 

Is this also part of refactoring? If yes, it deserves a mention on why it's ok to just drop this.

Quoted 4 lines

pw-bot: cr

Yes it is also part of the refactoring as stack_map_calculate_max_depth now already curtains the trace->nr to the max possible number of elements, there is no need to do the clamping twice. This is valid assuming that get_perf_callchain and get_callchain_entry_for_task correctly set this limit.

What about that third case:

if (trace_in)

     trace = trace_in;

Did you analyze if that gets its trace->nr set properly as well (as of this patch, without taking into account changes in the follow up patches). Because it looks like this removal belongs in patch #2, no?

Quoted 5 lines

In either case, all the other changes in this patch except the removal of this line is refactoring and as far as I can tell don't change the logic. This line removal does (potentially) change the logic, so it would be good to do it separately, explaining why you think it's the correct thing to do.

Back from holidays, catching up now :)
You are indeed totally right Andrii, thanks for pointing it out. We should squash the 2 first patch together.

Quoted 10 lines
Quoted 10 lines

         copy_len = trace_nr * elem_size;

         ips = trace->ip + skip;

--
2.43.0

Thanks,
Arnaud

Thanks,
Arnaud

#9 lore raw

PATCH 1/2 bpf: refactor stack map trace depth calculation into helper function

Extract the duplicated maximum allowed depth computation for stack traces stored in BPF stacks from bpf_get_stackid() and __bpf_get_stack() into a dedicated stack_map_calculate_max_depth() helper function.

This unifies the logic for:
- The max depth computation
- Enforcing the sysctl_perf_event_max_stack limit

No functional changes for existing code paths.

---
Changes in v2:
- Removed the checking 'map_size % map_elem_size' from stack_map_calculate_max_depth
- Changed stack_map_calculate_max_depth params name to be more generic

Changes in v3:
- Changed map size param to size in max depth helper

Changes in v4:
- Fixed indentation in max depth helper for args

Changes in v5:
- Bound back trace_nr to num_elem in __bpf_get_stack
- Make a copy of sysctl_perf_event_max_stack in stack_map_calculate_max_depth

Changes in v6:
- Restrained max_depth computation only when required
- Additional cleanup from Song in __bpf_get_stack

Changes in v7:
- Removed additional cleanup from v6

Changes in v9:
- Fixed incorrect removal of num_elem in get stack

Changes in v10:
- Squashed 2 previous patch 1 and 2

Link to v9:
https://lore.kernel.org/all/[email protected]/
---

---
 kernel/bpf/stackmap.c | 47 +++++++++++++++++++++++++++++--------------
 1 file changed, 32 insertions(+), 15 deletions(-)
kernel/bpf/stackmap.c +32 -15
index 3615c06b7dfa..9a86b5acac10 100644
@@ -42,6 +42,28 @@ static inline int stack_map_data_size(struct bpf_map *map)
 		sizeof(struct bpf_stack_build_id) : sizeof(u64);
 }
 
+/**
+ * stack_map_calculate_max_depth - Calculate maximum allowed stack trace depth
+ * @size:  Size of the buffer/map value in bytes
+ * @elem_size:  Size of each stack trace element
+ * @flags:  BPF stack trace flags (BPF_F_USER_STACK, BPF_F_USER_BUILD_ID, ...)
+ *
+ * Return: Maximum number of stack trace entries that can be safely stored
+ */
+static u32 stack_map_calculate_max_depth(u32 size, u32 elem_size, u64 flags)
+{
+	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+	u32 max_depth;
+	u32 curr_sysctl_max_stack = READ_ONCE(sysctl_perf_event_max_stack);
+
+	max_depth = size / elem_size;
+	max_depth += skip;
+	if (max_depth > curr_sysctl_max_stack)
+		return curr_sysctl_max_stack;
+
+	return max_depth;
+}
+
 static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
 {
 	u64 elem_size = sizeof(struct stack_map_bucket) +
@@ -300,20 +322,17 @@ static long __bpf_get_stackid(struct bpf_map *map,
 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
 	   u64, flags)
 {
-	u32 max_depth = map->value_size / stack_map_data_size(map);
-	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
+	u32 elem_size = stack_map_data_size(map);
 	bool user = flags & BPF_F_USER_STACK;
 	struct perf_callchain_entry *trace;
 	bool kernel = !user;
+	u32 max_depth;
 
 	if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
 			       BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
 		return -EINVAL;
 
-	max_depth += skip;
-	if (max_depth > sysctl_perf_event_max_stack)
-		max_depth = sysctl_perf_event_max_stack;
-
+	max_depth = stack_map_calculate_max_depth(map->value_size, elem_size, flags);
 	trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
 				   false, false);
 
@@ -406,7 +425,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 			    struct perf_callchain_entry *trace_in,
 			    void *buf, u32 size, u64 flags, bool may_fault)
 {
-	u32 trace_nr, copy_len, elem_size, num_elem, max_depth;
+	u32 trace_nr, copy_len, elem_size, max_depth;
 	bool user_build_id = flags & BPF_F_USER_BUILD_ID;
 	bool crosstask = task && task != current;
 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
@@ -438,21 +457,20 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 		goto clear;
 	}
 
-	num_elem = size / elem_size;
-	max_depth = num_elem + skip;
-	if (sysctl_perf_event_max_stack < max_depth)
-		max_depth = sysctl_perf_event_max_stack;
+	max_depth = stack_map_calculate_max_depth(size, elem_size, flags);
 
 	if (may_fault)
 		rcu_read_lock(); /* need RCU for perf's callchain below */
 
-	if (trace_in)
+	if (trace_in) {
 		trace = trace_in;
-	else if (kernel && task)
+		trace->nr = min_t(u32, trace->nr, max_depth);
+	} else if (kernel && task) {
 		trace = get_callchain_entry_for_task(task, max_depth);
-	else
+	} else {
 		trace = get_perf_callchain(regs, 0, kernel, user, max_depth,
 					   crosstask, false);
+	}
 
 	if (unlikely(!trace) || trace->nr < skip) {
 		if (may_fault)
@@ -461,7 +479,6 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 	}
 
 	trace_nr = trace->nr - skip;
-	trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;
 	copy_len = trace_nr * elem_size;
 
 	ips = trace->ip + skip;
Signature · 1 line
2.47.3
#10 lore raw

PATCH 2/2 bpf: fix stackmap overflow check in __bpf_get_stackid()

Syzkaller reported a KASAN slab-out-of-bounds write in __bpf_get_stackid() when copying stack trace data. The issue occurs when the perf trace
contains more stack entries than the stack map bucket can hold, leading to an out-of-bounds write in the bucket's data array.

Reported-by [email protected]
Fixes ee2a098851bf ("bpf: Adjust BPF stack helper functions to accommodate skip > 0")

---
Changes in v2:
- Fixed max_depth names across get stack id

Changes in v4:
- Removed unnecessary empty line in __bpf_get_stackid

Changes in v6:
- Added back trace_len computation in __bpf_get_stackid

Changes in v7:
- Removed usefull trace->nr assignation in bpf_get_stackid_pe
- Added restoration of trace->nr for both kernel and user traces in bpf_get_stackid_pe

Changes in v9:
- Fixed variable declarations in bpf_get_stackid_pe
- Added the missing truncate of trace_nr in __bpf_getstackid

Changes in v10:
- Remove not required trace->nr = nr_kernel; in bpf_get_stackid_pe

Link to v9:
https://lore.kernel.org/all/[email protected]/
---

---
 kernel/bpf/stackmap.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
kernel/bpf/stackmap.c +8 -7
index 9a86b5acac10..c0ee51db8eed 100644
@@ -251,8 +251,8 @@ static long __bpf_get_stackid(struct bpf_map *map,
 {
 	struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
 	struct stack_map_bucket *bucket, *new_bucket, *old_bucket;
+	u32 hash, id, trace_nr, trace_len, i, max_depth;
 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
-	u32 hash, id, trace_nr, trace_len, i;
 	bool user = flags & BPF_F_USER_STACK;
 	u64 *ips;
 	bool hash_matches;
@@ -261,7 +261,8 @@ static long __bpf_get_stackid(struct bpf_map *map,
 		/* skipping more than usable stack trace */
 		return -EFAULT;
 
-	trace_nr = trace->nr - skip;
+	max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags);
+	trace_nr = min_t(u32, trace->nr - skip, max_depth - skip);
 	trace_len = trace_nr * sizeof(u64);
 	ips = trace->ip + skip;
 	hash = jhash2((u32 *)ips, trace_len / sizeof(u32), 0);
@@ -390,15 +391,11 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 		return -EFAULT;
 
 	nr_kernel = count_kernel_ip(trace);
+	__u64 nr = trace->nr; /* save original */
 
 	if (kernel) {
-		__u64 nr = trace->nr;
-
 		trace->nr = nr_kernel;
 		ret = __bpf_get_stackid(map, trace, flags);
-
-		/* restore nr */
-		trace->nr = nr;
 	} else { /* user */
 		u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
 
@@ -409,6 +406,10 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 		flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
 		ret = __bpf_get_stackid(map, trace, flags);
 	}
+
+	/* restore nr */
+	trace->nr = nr;
+
 	return ret;
 }
 
Signature · 1 line
2.47.3