mm: bpf kfuncs to access memcg data
Subsystems (6)
Roman Gushchin
maintainerv2 cover mm: bpf kfuncs to access memcg data
Introduce kfuncs to simplify the access to the memcg data. These kfuncs can be used to accelerate monitoring use cases and for implementing custom OOM policies once BPF OOM is landed.
This patchset was separated out from the BPF OOM patchset to simplify the logistics and accelerate the landing of the part which is useful by itself. No functional changes since BPF OOM v2.
v2:
- added mem_cgroup_disabled() checks (by Shakeel B.)
- added special handling of the root memcg in bpf_mem_cgroup_usage() (by Shakeel B.)
- minor fixes in the kselftest (by Shakeel B.)
- added a MAINTAINERS entry (by Shakeel B.)
v1:
https://lore.kernel.org/bpf/[email protected]/T/#t
JP Kobryn (2):
mm: introduce BPF kfunc to access memory events
bpf: selftests: selftests for memcg stat kfuncs
Roman Gushchin (5):
mm: declare memcg_page_state_output() in memcontrol.h
mm: introduce BPF kfuncs to deal with memcg pointers
mm: introduce bpf_get_root_mem_cgroup() BPF kfunc
mm: introduce BPF kfuncs to access memcg statistics and events
MAINTAINERS: add an entry for MM BPF extensions
MAINTAINERS | 7 + include/linux/memcontrol.h | 3 + mm/Makefile | 3 + mm/bpf_memcontrol.c | 179 ++++++++++++++ mm/memcontrol-v1.h | 1 - .../testing/selftests/bpf/cgroup_iter_memcg.h | 18 ++ .../bpf/prog_tests/cgroup_iter_memcg.c | 223 ++++++++++++++++++ .../selftests/bpf/progs/cgroup_iter_memcg.c | 39 +++ 8 files changed, 472 insertions(+), 1 deletion(-) create mode 100644 mm/bpf_memcontrol.c create mode 100644 tools/testing/selftests/bpf/cgroup_iter_memcg.h create mode 100644 tools/testing/selftests/bpf/prog_tests/cgroup_iter_memcg.c create mode 100644 tools/testing/selftests/bpf/progs/cgroup_iter_memcg.c
Signature · 1 line
2.52.0
Roman Gushchin
maintainerPATCH v2 1/7 mm: declare memcg_page_state_output() in memcontrol.h
To use memcg_page_state_output() in bpf_memcontrol.c move the declaration from v1-specific memcontrol-v1.h to memcontrol.h.
--- include/linux/memcontrol.h | 1 + mm/memcontrol-v1.h | 1 - 2 files changed, 1 insertion(+), 1 deletion(-)
include/linux/memcontrol.h +1 -0
@@ -950,6 +950,7 @@ static inline void mod_memcg_page_state(struct page *page, }unsigned long memcg_page_state (struct mem_cgroup *memcg,int idx); +unsigned long memcg_page_state_output (struct mem_cgroup *memcg,int item);unsigned long lruvec_page_state (struct lruvec *lruvec,enum node_stat_item idx);unsigned long lruvec_page_state_local (struct lruvec *lruvec,enum node_stat_item idx);
mm/memcontrol-v1.h +0 -1
@@ -27,7 +27,6 @@ unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap);void drain_all_stock (struct mem_cgroup *root_memcg);unsigned long memcg_events (struct mem_cgroup *memcg,int event); -unsigned long memcg_page_state_output (struct mem_cgroup *memcg,int item);int memory_stat_show (struct seq_file *m,void *v);void mem_cgroup_id_get_many (struct mem_cgroup *memcg,unsigned int n);
Signature · 1 line
2.52.0
Roman Gushchin
maintainerPATCH v2 2/7 mm: introduce BPF kfuncs to deal with memcg pointers
In reply to Roman GushchinTo effectively operate with memory cgroups in BPF there is a need to convert css pointers to memcg pointers. A simple container_of cast which is used in the kernel code can't be used in BPF because from the verifier's point of view that's a out-of-bounds memory access.
Introduce helper get/put kfuncs which can be used to get a refcounted memcg pointer from the css pointer:
- bpf_get_mem_cgroup,
- bpf_put_mem_cgroup.
bpf_get_mem_cgroup() can take both memcg's css and the corresponding cgroup's "self" css. It allows it to be used with the existing cgroup iterator which iterates over cgroup tree, not memcg tree.
--- mm/Makefile | 3 ++ mm/bpf_memcontrol.c | 88 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 mm/bpf_memcontrol.c
mm/Makefile +3 -0
@@ -106,6 +106,9 @@ obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o ifdef CONFIG_SWAP obj-$(CONFIG_MEMCG) += swap_cgroup.o endif +ifdef CONFIG_BPF_SYSCALL +obj-$(CONFIG_MEMCG) += bpf_memcontrol.o +endif obj-$(CONFIG_CGROUP_HUGETLB) += hugetlb_cgroup.o obj-$(CONFIG_GUP_TEST) += gup_test.o obj-$(CONFIG_DMAPOOL_TEST) += dmapool_test.o
mm/bpf_memcontrol.c new file +88 -0
88 lines not on this page · raw message
Signature · 1 line
2.52.0
Roman Gushchin
maintainerPATCH v2 3/7 mm: introduce bpf_get_root_mem_cgroup() BPF kfunc
In reply to Roman GushchinIntroduce a BPF kfunc to get a trusted pointer to the root memory cgroup. It's very handy to traverse the full memcg tree, e.g. for handling a system-wide OOM.
It's possible to obtain this pointer by traversing the memcg tree up from any known memcg, but it's sub-optimal and makes BPF programs more complex and less efficient.
bpf_get_root_mem_cgroup() has a KF_ACQUIRE | KF_RET_NULL semantics, however in reality it's not necessary to bump the corresponding reference counter - root memory cgroup is immortal, reference counting is skipped, see css_get(). Once set, root_mem_cgroup is always a valid memcg pointer. It's safe to call bpf_put_mem_cgroup() for the pointer obtained with bpf_get_root_mem_cgroup(), it's effectively a no-op.
--- mm/bpf_memcontrol.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)
mm/bpf_memcontrol.c +18 -0
@@ -10,6 +10,23 @@__bpf_kfunc_start_defs (); +/** +* bpf_get_root_mem_cgroup - Returns a pointer to the root memory cgroup +* +* The function has KF_ACQUIRE semantics, even though the root memory +* cgroup is never destroyed after being created and doesn't require +* reference counting. And it's perfectly safe to pass it to +* bpf_put_mem_cgroup() +*/ +__bpf_kfunc struct mem_cgroup *bpf_get_root_mem_cgroup(void) +{ +if (mem_cgroup_disabled ()) +return NULL ; + +/* css_get() is not needed */ +return root_mem_cgroup; +} +/** * bpf_get_mem_cgroup - Get a reference to a memory cgroup * @css: pointer to the css structure
@@ -64,6 +81,7 @@ __bpf_kfunc void bpf_put_mem_cgroup(struct mem_cgroup *memcg)__bpf_kfunc_end_defs (); BTF_KFUNCS_START(bpf_memcontrol_kfuncs) +BTF_ID_FLAGS(func, bpf_get_root_mem_cgroup, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_get_mem_cgroup, KF_TRUSTED_ARGS | KF_ACQUIRE | KF_RET_NULL | KF_RCU) BTF_ID_FLAGS(func, bpf_put_mem_cgroup, KF_TRUSTED_ARGS | KF_RELEASE)
Signature · 1 line
2.52.0
Roman Gushchin
maintainerPATCH v2 4/7 mm: introduce BPF kfuncs to access memcg statistics and events
In reply to Roman GushchinIntroduce BPF kfuncs to conveniently access memcg data:
- bpf_mem_cgroup_vm_events(),
- bpf_mem_cgroup_usage(),
- bpf_mem_cgroup_page_state(),
- bpf_mem_cgroup_flush_stats().
These functions are useful for implementing BPF OOM policies, but also can be used to accelerate access to the memcg data. Reading it through cgroupfs is much more expensive, roughly 5x, mostly because of the need to convert the data into the text and back.
JP Kobryn:
An experiment was setup to compare the performance of a program that uses the traditional method of reading memory.stat vs a program using the new kfuncs. The control program opens up the root memory.stat file and for 1M iterations reads, converts the string values to numeric data, then seeks back to the beginning. The experimental program sets up the requisite libbpf objects and for 1M iterations invokes a bpf program which uses the kfuncs to fetch all available stats for node_stat_item, memcg_stat_item, and vm_event_item types.
The results showed a significant perf benefit on the experimental side, outperforming the control side by a margin of 93%. In kernel mode, elapsed time was reduced by 80%, while in user mode, over 99% of time was saved.
control: elapsed time
real 0m38.318s user 0m25.131s sys 0m13.070s
experiment: elapsed time
real 0m2.789s user 0m0.187s sys 0m2.512s
control: perf data
33.43% a.out libc.so.6 [.] __vfscanf_internal
6.88% a.out [kernel.kallsyms] [k] vsnprintf
6.33% a.out libc.so.6 [.] _IO_fgets
5.51% a.out [kernel.kallsyms] [k] format_decode
4.31% a.out libc.so.6 [.] __GI_____strtoull_l_internal
3.78% a.out [kernel.kallsyms] [k] string
3.53% a.out [kernel.kallsyms] [k] number
2.71% a.out libc.so.6 [.] _IO_sputbackc
2.41% a.out [kernel.kallsyms] [k] strlen
1.98% a.out a.out [.] main 1.70% a.out libc.so.6 [.] _IO_getline_info 1.51% a.out libc.so.6 [.] __isoc99_sscanf
1.47% a.out [kernel.kallsyms] [k] memory_stat_format 1.47% a.out [kernel.kallsyms] [k] memcpy_orig 1.41% a.out [kernel.kallsyms] [k] seq_buf_printf
experiment: perf data
10.55% memcgstat bpf_prog_..._query [k] bpf_prog_16aab2f19fa982a7_query
6.90% memcgstat [kernel.kallsyms] [k] memcg_page_state_output 3.55% memcgstat [kernel.kallsyms] [k] _raw_spin_lock 3.12% memcgstat [kernel.kallsyms] [k] memcg_events 2.87% memcgstat [kernel.kallsyms] [k] __memcg_slab_post_alloc_hook 2.73% memcgstat [kernel.kallsyms] [k] kmem_cache_free 2.70% memcgstat [kernel.kallsyms] [k] entry_SYSRETQ_unsafe_stack 2.25% memcgstat [kernel.kallsyms] [k] __memcg_slab_free_hook 2.06% memcgstat [kernel.kallsyms] [k] get_page_from_freelist
--- include/linux/memcontrol.h | 2 ++ mm/bpf_memcontrol.c | 56 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+)
include/linux/memcontrol.h +2 -0
@@ -949,6 +949,8 @@ static inline void mod_memcg_page_state(struct page *page,rcu_read_unlock (); } +unsigned long memcg_events (struct mem_cgroup *memcg,int event); +unsigned long mem_cgroup_usage (struct mem_cgroup *memcg,bool swap);unsigned long memcg_page_state (struct mem_cgroup *memcg,int idx);unsigned long memcg_page_state_output (struct mem_cgroup *memcg,int item);unsigned long lruvec_page_state (struct lruvec *lruvec,enum node_stat_item idx);
mm/bpf_memcontrol.c +56 -0
68 lines not on this page · raw message
Signature · 1 line
2.52.0
Roman Gushchin
maintainerPATCH v2 5/7 mm: introduce BPF kfunc to access memory events
In reply to Roman GushchinFrom: JP Kobryn <[email protected]>
Introduce BPF kfunc to access memory events, e.g.:MEMCG_LOW, MEMCG_MAX, MEMCG_OOM, MEMCG_OOM_KILL etc.
--- mm/bpf_memcontrol.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
mm/bpf_memcontrol.c +17 -0
@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value +* @memcg: memory cgroup +* @event: memory event id +* +* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ; + +return atomic_long_read (&memcg->memory_events[event]); +} +/** * bpf_mem_cgroup_page_state - Read memory cgroup's page state counter * @memcg: memory cgroup
@@ -137,6 +153,7 @@ BTF_ID_FLAGS(func, bpf_get_mem_cgroup, KF_TRUSTED_ARGS | KF_ACQUIRE | KF_RET_NUL BTF_ID_FLAGS(func, bpf_put_mem_cgroup, KF_TRUSTED_ARGS | KF_RELEASE) BTF_ID_FLAGS(func, bpf_mem_cgroup_vm_events, KF_TRUSTED_ARGS) +BTF_ID_FLAGS(func, bpf_mem_cgroup_memory_events, KF_TRUSTED_ARGS) BTF_ID_FLAGS(func, bpf_mem_cgroup_usage, KF_TRUSTED_ARGS) BTF_ID_FLAGS(func, bpf_mem_cgroup_page_state, KF_TRUSTED_ARGS)BTF_ID_FLAGS (func, bpf_mem_cgroup_flush_stats,KF_TRUSTED_ARGS |KF_SLEEPABLE )
Signature · 1 line
2.52.0
Roman Gushchin
maintainerPATCH v2 6/7 bpf: selftests: selftests for memcg stat kfuncs
In reply to Roman GushchinFrom: JP Kobryn <[email protected]>
Add test coverage for the kfuncs that fetch memcg stats. Using some common stats, test scenarios ensuring that the given stat increases by some arbitrary amount. The stats selected cover the three categories represented by the enums: node_stat_item, memcg_stat_item, vm_event_item.
Since only a subset of all stats are queried, use a static struct made up of fields for each stat. Write to the struct with the fetched values when the bpf program is invoked and read the fields in the user mode program for verification.
--- .../testing/selftests/bpf/cgroup_iter_memcg.h | 18 ++ .../bpf/prog_tests/cgroup_iter_memcg.c | 223 ++++++++++++++++++ .../selftests/bpf/progs/cgroup_iter_memcg.c | 39 +++ 3 files changed, 280 insertions(+) create mode 100644 tools/testing/selftests/bpf/cgroup_iter_memcg.h create mode 100644 tools/testing/selftests/bpf/prog_tests/cgroup_iter_memcg.c create mode 100644 tools/testing/selftests/bpf/progs/cgroup_iter_memcg.c
tools/testing/selftests/bpf/cgroup_iter_memcg.h new file +18 -0
@@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */ +#ifndef __CGROUP_ITER_MEMCG_H +#define __CGROUP_ITER_MEMCG_H + +struct memcg_query { +/* some node_stat_item's */ +unsigned long nr_anon_mapped; +unsigned long nr_shmem; +unsigned long nr_file_pages; +unsigned long nr_file_mapped; +/* some memcg_stat_item */ +unsigned long memcg_kmem; +/* some vm_event_item */ +unsigned long pgfault; +}; + +#endif /* __CGROUP_ITER_MEMCG_H */
tools/testing/selftests/bpf/prog_tests/cgroup_iter_memcg.c new file +223 -0
223 lines not on this page · raw message
tools/testing/selftests/bpf/progs/cgroup_iter_memcg.c new file +39 -0
@@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */ +#include <vmlinux.h> +#include <bpf/bpf_core_read.h> +#include "cgroup_iter_memcg.h" + +char _license[] SEC("license") = "GPL"; + +/* The latest values read are stored here. */ +struct memcg_query memcg_query SEC(".data.query"); + +SEC("iter.s/cgroup") +int cgroup_memcg_query (struct bpf_iter__cgroup *ctx) +{ +struct cgroup *cgrp = ctx->cgroup; +struct cgroup_subsys_state *css; +struct mem_cgroup *memcg; + +if (!cgrp) +return 1 ; + + css = &cgrp->self; + memcg =bpf_get_mem_cgroup (css); +if (!memcg) +return 1 ; + +bpf_mem_cgroup_flush_stats (memcg); + + memcg_query.nr_anon_mapped =bpf_mem_cgroup_page_state (memcg,NR_ANON_MAPPED ); + memcg_query.nr_shmem =bpf_mem_cgroup_page_state (memcg,NR_SHMEM ); + memcg_query.nr_file_pages =bpf_mem_cgroup_page_state (memcg,NR_FILE_PAGES ); + memcg_query.nr_file_mapped =bpf_mem_cgroup_page_state (memcg,NR_FILE_MAPPED ); + memcg_query.memcg_kmem =bpf_mem_cgroup_page_state (memcg,MEMCG_KMEM ); + memcg_query.pgfault =bpf_mem_cgroup_vm_events (memcg,PGFAULT ); + +bpf_put_mem_cgroup (memcg); + +return 0 ; +}
Signature · 1 line
2.52.0
Roman Gushchin
maintainerPATCH v2 7/7 MAINTAINERS: add an entry for MM BPF extensions
In reply to Roman GushchinLet's create a separate entry for MM BPF extensions: these patches often require an attention from both bpf and mm communities.
--- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+)
MAINTAINERS +7 -0
@@ -4798,6 +4798,13 @@ L: [email protected] S: Maintained F: tools/lib/bpf/ +BPF [MEMORY MANAGEMENT EXTENSIONS] +M: Roman Gushchin <[email protected]> +L: [email protected] +L: [email protected] +S: Maintained +F: mm/bpf_memcontrol.c + BPF [MISC] L: [email protected] S: Odd Fixes
Signature · 1 line
2.52.0
[email protected]
AI reviewRe: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events
In reply to Roman GushchinShould this function validate the event parameter before passing it to memcg_events()?
Quoted 10 lines
mm/bpf_memcontrol.c +2
-0@@ -78,6 +78,57 @@ __bpf_kfunc void bpf_put_mem_cgroup(struct mem_cgroup *memcg)css_put (&memcg->css); } +/** +* bpf_mem_cgroup_vm_events - Read memory cgroup's vm event counter
mm/bpf_memcontrol.c __bpf_kfunc void bpf_put_mem_cgroup(struct mem_cgroup *memcg) · line 92
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* @memcg: memory cgroup +* @event: event id +* +* Allows to read memory cgroup event counters. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_vm_events (struct mem_cgroup *memcg, +enum vm_event_item event) +{ +return memcg_events (memcg, event); +}
Should this function validate the event parameter before passing it to memcg_events()?
The call chain bpf_mem_cgroup_vm_events()->memcg_events()->memcg_events_index() reaches an array access in memcg_events_index():
static inline int memcg_events_index(enum vm_event_item idx)
{
return mem_cgroup_events_index[idx];
}The array mem_cgroup_events_index is declared with size NR_VM_EVENT_ITEMS. If a BPF program passes an event value >= NR_VM_EVENT_ITEMS, this would cause an out-of-bounds array read.
For comparison, bpf_mem_cgroup_page_state() below validates its idx parameter before calling memcg_page_state_output(). A similar check here would prevent the potential out-of-bounds access:
if (event < 0 || event >= NR_VM_EVENT_ITEMS)
return (unsigned long)-1;Quoted 3 lines
mm/bpf_memcontrol.c +3
-0+ +/** +* bpf_mem_cgroup_usage - Read memory cgroup's usage
[ ... ]
mm/bpf_memcontrol.c __bpf_kfunc void bpf_put_mem_cgroup(struct mem_cgroup *memcg) · line 119
Quoted 7 lines
mm/bpf_memcontrol.c +7
-0+__bpf_kfunc unsigned long bpf_mem_cgroup_page_state (struct mem_cgroup *memcg,int idx) +{ +if (idx <0 || idx >=MEMCG_NR_STAT ) +return (unsigned long )-1 ; + +return memcg_page_state_output (memcg, idx); +}
[ ... ]
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/20389033088
[email protected]
AI reviewRe: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
In reply to Roman GushchinShould this also check for negative values? The enum type is typically signed, so a BPF program passing a negative event value would pass this check but cause an out-of-bounds read from…
Quoted 10 lines
mm/bpf_memcontrol.c +2
-0@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value
mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 117
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* @memcg: memory cgroup +* @event: memory event id +* +* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ;
Should this also check for negative values? The enum type is typically signed, so a BPF program passing a negative event value would pass this check but cause an out-of-bounds read from memcg->memory_events[].
The similar bpf_mem_cgroup_page_state() in this same file uses:
if (idx < 0 || idx >= MEMCG_NR_STAT)
which checks both bounds. Could the check here be changed to:
if (event < 0 || event >= MEMCG_NR_MEMORY_EVENTS)
to match that pattern?
mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 120
Quoted 3 lines
mm/bpf_memcontrol.c +3
-0+ +return atomic_long_read (&memcg->memory_events[event]); +}
[ ... ]
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/20389033088
Roman Gushchin
maintainerRe: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events
In reply to [email protected]Quoted 36 lines · [email protected] writes:
Quoted 10 lines
mm/bpf_memcontrol.c +2
-0@@ -78,6 +78,57 @@ __bpf_kfunc void bpf_put_mem_cgroup(struct mem_cgroup *memcg)css_put (&memcg->css); } +/** +* bpf_mem_cgroup_vm_events - Read memory cgroup's vm event counter mm/bpf_memcontrol.c __bpf_kfunc void bpf_put_mem_cgroup(struct mem_cgroup *memcg) · line 92
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* @memcg: memory cgroup +* @event: event id +* +* Allows to read memory cgroup event counters. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_vm_events (struct mem_cgroup *memcg, +enum vm_event_item event) +{ +return memcg_events (memcg, event); +}Should this function validate the event parameter before passing it to
memcg_events()?The call chain bpf_mem_cgroup_vm_events()->memcg_events()->memcg_events_index() reaches an array access in
memcg_events_index():static inline int memcg_events_index(enum vm_event_item idx) { return mem_cgroup_events_index[idx]; }The array
mem_cgroup_events_indexis declared with sizeNR_VM_EVENT_ITEMS. If a BPF program passes an event value >=NR_VM_EVENT_ITEMS, this would cause an out-of-bounds array read.
Quoted 6 lines
For comparison,
bpf_mem_cgroup_page_state()below validates its idx parameter before callingmemcg_page_state_output(). A similar check here would prevent the potential out-of-bounds access:if (event < 0 || event >= NR_VM_EVENT_ITEMS) return (unsigned long)-1;
No, it's a false positive, as explained in a reply to the similar comment to v1.
Roman Gushchin
maintainerRe: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
In reply to [email protected]Quoted 27 lines · [email protected] writes:
Quoted 10 lines
mm/bpf_memcontrol.c +2
-0@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 117
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* @memcg: memory cgroup +* @event: memory event id +* +* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ;Should this also check for negative values? The enum type is typically signed, so a BPF program passing a negative event value would pass this check but cause an out-of-bounds read from memcg->memory_events[].
The similar
bpf_mem_cgroup_page_state()in this same file uses:
Quoted 7 lines
if (idx < 0 || idx >= MEMCG_NR_STAT)which checks both bounds. Could the check here be changed to:
if (event < 0 || event >= MEMCG_NR_MEMORY_EVENTS)to match that pattern?
No, the bpf verifier enforces event > 0.
It's a false positive.
Re: [PATCH bpf-next v2 2/7] mm: introduce BPF kfuncs to deal with memcg pointers
In reply to Roman GushchinQuoted 10 lines · Roman Gushchin
To effectively operate with memory cgroups in BPF there is a need to convert css pointers to memcg pointers. A simple
container_ofcast which is used in the kernel code can't be used in BPF because from the verifier's point of view that's a out-of-bounds memory access.Introduce helper get/put kfuncs which can be used to get a refcounted memcg pointer from the css pointer:
-bpf_get_mem_cgroup,
-bpf_put_mem_cgroup.
Quoted 5 lines
bpf_get_mem_cgroup()can take both memcg's css and the corresponding cgroup's "self" css. It allows it to be used with the existing cgroup iterator which iterates over cgroup tree, not memcg tree.Signed-off-by Roman Gushchin <[email protected]>
Re: [PATCH bpf-next v2 3/7] mm: introduce bpf_get_root_mem_cgroup() BPF kfunc
In reply to Roman GushchinQuoted 8 lines · Roman Gushchin
Introduce a BPF kfunc to get a trusted pointer to the root memory cgroup. It's very handy to traverse the full memcg tree, e.g. for handling a system-wide OOM.
It's possible to obtain this pointer by traversing the memcg tree up from any known memcg, but it's sub-optimal and makes BPF programs more complex and less efficient.
Quoted 8 lines
bpf_get_root_mem_cgroup()has aKF_ACQUIRE|KF_RET_NULLsemantics, however in reality it's not necessary to bump the corresponding reference counter - root memory cgroup is immortal, reference counting is skipped, seecss_get(). Once set,root_mem_cgroupis always a valid memcg pointer. It's safe to callbpf_put_mem_cgroup()for the pointer obtained withbpf_get_root_mem_cgroup(), it's effectively a no-op.Signed-off-by Roman Gushchin <[email protected]>
Re: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events
In reply to Roman GushchinQuoted 64 lines · Roman Gushchin
Introduce BPF kfuncs to conveniently access memcg data:
-bpf_mem_cgroup_vm_events(),
-bpf_mem_cgroup_usage(),
-bpf_mem_cgroup_page_state(),
-bpf_mem_cgroup_flush_stats().These functions are useful for implementing BPF OOM policies, but also can be used to accelerate access to the memcg data. Reading it through cgroupfs is much more expensive, roughly 5x, mostly because of the need to convert the data into the text and back.
JP Kobryn:
An experiment was setup to compare the performance of a program that uses the traditional method of reading memory.stat vs a program using the new kfuncs. The control program opens up the root memory.stat file and for 1M iterations reads, converts the string values to numeric data, then seeks back to the beginning. The experimental program sets up the requisite libbpf objects and for 1M iterations invokes a bpf program which uses the kfuncs to fetch all available stats fornode_stat_item,memcg_stat_item, andvm_event_itemtypes.The results showed a significant perf benefit on the experimental side, outperforming the control side by a margin of 93%. In kernel mode, elapsed time was reduced by 80%, while in user mode, over 99% of time was saved.
control: elapsed time
real 0m38.318s user 0m25.131s sys 0m13.070sexperiment: elapsed time
real 0m2.789s user 0m0.187s sys 0m2.512scontrol: perf data
33.43% a.out libc.so.6 [.]__vfscanf_internal
6.88% a.out [kernel.kallsyms] [k] vsnprintf
6.33% a.out libc.so.6 [.]_IO_fgets
5.51% a.out [kernel.kallsyms] [k]format_decode
4.31% a.out libc.so.6 [.]__GI_____strtoull_l_internal
3.78% a.out [kernel.kallsyms] [k] string
3.53% a.out [kernel.kallsyms] [k] number
2.71% a.out libc.so.6 [.]_IO_sputbackc
2.41% a.out [kernel.kallsyms] [k] strlen1.98% a.out a.out [.] main 1.70% a.out libc.so.6 [.] _IO_getline_info 1.51% a.out libc.so.6 [.] __isoc99_sscanf1.47% a.out [kernel.kallsyms] [k]
memory_stat_format1.47% a.out [kernel.kallsyms] [k]memcpy_orig1.41% a.out [kernel.kallsyms] [k]seq_buf_printfexperiment: perf data
10.55% memcgstat bpf_prog_..._query [k]bpf_prog_16aab2f19fa982a7_query6.90% memcgstat [kernel.kallsyms] [k] memcg_page_state_output 3.55% memcgstat [kernel.kallsyms] [k] _raw_spin_lock 3.12% memcgstat [kernel.kallsyms] [k] memcg_events 2.87% memcgstat [kernel.kallsyms] [k] __memcg_slab_post_alloc_hook 2.73% memcgstat [kernel.kallsyms] [k] kmem_cache_free 2.70% memcgstat [kernel.kallsyms] [k] entry_SYSRETQ_unsafe_stack 2.25% memcgstat [kernel.kallsyms] [k] __memcg_slab_free_hook 2.06% memcgstat [kernel.kallsyms] [k] get_page_from_freelist
Quoted 4 lines
Signed-off-by Roman Gushchin <[email protected]>Co-developed-by JP Kobryn <[email protected]>Signed-off-by JP Kobryn <[email protected]>Acked-by Michal Hocko <[email protected]>
Re: [PATCH bpf-next v2 6/7] bpf: selftests: selftests for memcg stat kfuncs
In reply to Roman GushchinQuoted 7 lines · Roman Gushchin
From: JP Kobryn <[email protected]>
Add test coverage for the kfuncs that fetch memcg stats. Using some common stats, test scenarios ensuring that the given stat increases by some arbitrary amount. The stats selected cover the three categories represented by the enums:
node_stat_item,memcg_stat_item,vm_event_item.
Quoted 7 lines
Since only a subset of all stats are queried, use a static struct made up of fields for each stat. Write to the struct with the fetched values when the bpf program is invoked and read the fields in the user mode program for verification.
Signed-off-by JP Kobryn <[email protected]>Signed-off-by Roman Gushchin <[email protected]>
Re: [PATCH bpf-next v2 7/7] MAINTAINERS: add an entry for MM BPF extensions
In reply to Roman GushchinQuoted 13 lines · Roman Gushchin
Let's create a separate entry for MM BPF extensions: these patches often require an attention from both bpf and mm communities.
Signed-off-by Roman Gushchin <[email protected]>--- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+)MAINTAINERS +0
-0
MAINTAINERS L: [email protected] · line 4802
Quoted 5 lines
MAINTAINERS +2
-0@@ -4798,6 +4798,13 @@ L: [email protected] S: Maintained F: tools/lib/bpf/ +BPF [MEMORY MANAGEMENT EXTENSIONS] +M: Roman Gushchin <[email protected]>
If you don't mind, put JP and I here as well.
Re: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
In reply to Roman GushchinQuoted 31 lines · Roman Gushchin
Quoted 29 lines · [email protected] writes:
Quoted 10 lines
mm/bpf_memcontrol.c +2
-0@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 117
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* @memcg: memory cgroup +* @event: memory event id +* +* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ;Should this also check for negative values? The enum type is typically signed, so a BPF program passing a negative event value would pass this check but cause an out-of-bounds read from memcg->memory_events[].
The similar
bpf_mem_cgroup_page_state()in this same file uses:if (idx < 0 || idx >= MEMCG_NR_STAT)
Quoted 8 lines
Quoted 5 lines
which checks both bounds. Could the check here be changed to:
if (event < 0 || event >= MEMCG_NR_MEMORY_EVENTS)to match that pattern?
No, the bpf verifier enforces event > 0.
It's a false positive.
I'll add some words here to the bpf prompts, thanks Roman.
-chris
Roman Gushchin
maintainerRe: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
Quoted 34 lines · Chris Mason
Quoted 33 lines · Roman Gushchin
Quoted 31 lines · [email protected] writes:
Quoted 10 lines
mm/bpf_memcontrol.c +2
-0@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 117
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* @memcg: memory cgroup +* @event: memory event id +* +* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ;Should this also check for negative values? The enum type is typically signed, so a BPF program passing a negative event value would pass this check but cause an out-of-bounds read from memcg->memory_events[].
The similar
bpf_mem_cgroup_page_state()in this same file uses:if (idx < 0 || idx >= MEMCG_NR_STAT)which checks both bounds. Could the check here be changed to:
Quoted 8 lines
Quoted 6 lines
Quoted 3 lines
if (event < 0 || event >= MEMCG_NR_MEMORY_EVENTS)to match that pattern?
No, the bpf verifier enforces event > 0.
It's a false positive.I'll add some words here to the bpf prompts, thanks Roman.
I'll try to play with it too, hopefully we can fix it.
Thanks!
kernel test robot
build botRe: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events
In reply to Roman Gushchinkernel test robot noticed the following build errors:
Hi Roman,
kernel test robot noticed the following build errors:
[auto build test ERROR on akpm-mm/mm-everything]
url: https://github.com/intel-lab-lkp/linux/commits/Roman-Gushchin/mm-declare-memcg_page_state_output-in-memcontrol-h/20251220-121603 base: https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything patch link: https://lore.kernel.org/r/20251220041250.372179-5-roman.gushchin%40linux.dev patch subject: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events config: s390-allnoconfig-bpf (https://download.01.org/0day-ci/archive/20251220/[email protected]/config) compiler: s390-linux-gcc (GCC) 15.1.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251220/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
s390-linux-ld: mm/bpf_memcontrol.o: in function `bpf_mem_cgroup_usage':
>> mm/bpf_memcontrol.c:103:(.text+0x60a): undefined reference to `mem_cgroup_usage'
vim +103 mm/bpf_memcontrol.c
93
94 /**
95 * bpf_mem_cgroup_usage - Read memory cgroup's usage
96 * @memcg: memory cgroup
97 *
98 * Returns current memory cgroup size in bytes.
99 * For the root memory cgroup it returns an approximate value.
100 */
101 __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)
102 {
> 103 return mem_cgroup_usage(memcg, false) * PAGE_SIZE;
104 }
105
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
kernel test robot
build botRe: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events
In reply to Roman Gushchinkernel test robot noticed the following build errors:
Hi Roman,
kernel test robot noticed the following build errors:
[auto build test ERROR on akpm-mm/mm-everything]
url: https://github.com/intel-lab-lkp/linux/commits/Roman-Gushchin/mm-declare-memcg_page_state_output-in-memcontrol-h/20251220-121603 base: https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything patch link: https://lore.kernel.org/r/20251220041250.372179-5-roman.gushchin%40linux.dev patch subject: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events config: i386-allnoconfig-bpf (https://download.01.org/0day-ci/archive/20251220/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251220/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> ld.lld: error: undefined symbol: mem_cgroup_usage >>> referenced by bpf_memcontrol.c:103 (mm/bpf_memcontrol.c:103) >>> mm/bpf_memcontrol.o:(bpf_mem_cgroup_usage) in archive vmlinux.a
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Re: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
In reply to Roman GushchinQuoted 38 lines · Roman Gushchin
Quoted 36 lines · Chris Mason
Quoted 35 lines · Roman Gushchin
Quoted 33 lines · [email protected] writes:
Quoted 10 lines
mm/bpf_memcontrol.c +2
-0@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 117
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* @memcg: memory cgroup +* @event: memory event id +* +* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ;Should this also check for negative values? The enum type is typically signed, so a BPF program passing a negative event value would pass this check but cause an out-of-bounds read from memcg->memory_events[].
The similar
bpf_mem_cgroup_page_state()in this same file uses:if (idx < 0 || idx >= MEMCG_NR_STAT)which checks both bounds. Could the check here be changed to:
if (event < 0 || event >= MEMCG_NR_MEMORY_EVENTS)
Quoted 9 lines
Quoted 6 lines
Quoted 4 lines
Quoted 1 line
to match that pattern?
No, the bpf verifier enforces event > 0.
It's a false positive.I'll add some words here to the bpf prompts, thanks Roman.
I'll try to play with it too, hopefully we can fix it.
https://github.com/masoncl/review-prompts/commit/fcc3bf704798f6be64cbb2e28b05a5c91eee9c7b
Seems to do the trick here:
[ ... ]
6. Missing negative check:
- The function only checks event >= MEMCG_NR_MEMORY_EVENTS
- Unlike bpf_mem_cgroup_page_state() which checks idx < 0 || idx >= MEMCG_NR_STAT
- However, event is an enum memcg_memory_event, not int
- Enums in C are typically unsigned when all values are non-negative (starting from 0)
- The enum starts at MEMCG_LOW = 0 (implicit) and all values are positive
- A negative value passed to this enum parameter would be extremely unusual and would require explicit casting
Let me verify the enum values are all non-negative:
Looking at memcg_memory_event enum:
enum memcg_memory_event {
MEMCG_LOW, // 0
MEMCG_HIGH, // 1
MEMCG_MAX, // 2
MEMCG_OOM, // 3
MEMCG_OOM_KILL, // 4
MEMCG_OOM_GROUP_KILL, // 5
MEMCG_SWAP_HIGH, // 6
MEMCG_SWAP_MAX, // 7
MEMCG_SWAP_FAIL, // 8
MEMCG_SOCK_THROTTLED, // 9
MEMCG_NR_MEMORY_EVENTS, // 10
} All values are 0 or positive. Since the parameter is typed as enum memcg_memory_event (not int), and BPF programs use constants from vmlinux.h, the lack of a < 0 check is acceptable:
1. BPF programs using enum constants can only pass valid values (0-9)
2. Even if a computed value were used, the enum type constrains the interpretation
3. If a negative value were somehow cast to this enum, the unsigned comparison event >= MEMCG_NR_MEMORY_EVENTS would catch it (negative becomes large positive in unsigned comparison)
Wait, let me reconsider this. The function parameter is enum memcg_memory_event event. In C, enums are typically represented as int under the hood. If someone passes a negative value, the comparison event >= MEMCG_NR_MEMORY_EVENTS would be signed comparison if event is treated as signed int.
Let me check if this is a concern:
● plugin:semcode:semcode - grep_functions (MCP)(pattern: "memcg_memory_event", path_pattern: "bpf_memcontrol")
⎿ Searching function bodies for pattern: memcg_memory_event (filtering paths matching: bpf_memcontrol, limit: 100) at git commit 0f92b93b6e42765a13c933e4e9cb268f8d77cf3c
Found 1 matching line(s):
… +3 lines (ctrl+o to expand)
● Let me think more carefully about the signed/unsigned comparison issue. The comparison event >= MEMCG_NR_MEMORY_EVENTS involves:
- event - an enum (which in C is typically int, signed)
- MEMCG_NR_MEMORY_EVENTS - an enum constant (value 10)
If event were negative (e.g., -1), then -1 >= 10 is false, and the function would proceed to access memcg->memory_events[-1] - an out-of-bounds access.
However, I need to consider the BPF context:
1. Per bpf.md: BPF programs use enum constants from vmlinux.h, and the compiler substitutes valid values at compile time
2. The verifier tracks scalar values: Even if computed at runtime, the verifier tracks value ranges
3. KF_TRUSTED_ARGS: The memcg pointer is validated, but this doesn't affect the enum parameter
Let me compare with bpf_mem_cgroup_page_state() which takes int idx and explicitly checks idx < 0:
__bpf_kfunc unsigned long bpf_mem_cgroup_page_state(struct mem_cgroup *memcg, int idx)
{
if (idx < 0 || idx >= MEMCG_NR_STAT)
return (unsigned long)-1;
...
} The difference is:
- bpf_mem_cgroup_page_state takes int idx - explicitly signed, needs both checks
- bpf_mem_cgroup_memory_events takes enum memcg_memory_event event - enum typed
For the enum case, per the BPF documentation loaded earlier:
DO NOT report as bugs: Kfuncs that take enum-typed parameters and use constants from vmlinux.h without explicit bounds checks.
-chris
kernel test robot
build botRe: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events
In reply to Roman Gushchinkernel test robot noticed the following build warnings:
Hi Roman,
kernel test robot noticed the following build warnings:
[auto build test WARNING on akpm-mm/mm-everything]
url: https://github.com/intel-lab-lkp/linux/commits/Roman-Gushchin/mm-declare-memcg_page_state_output-in-memcontrol-h/20251220-121603 base: https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything patch link: https://lore.kernel.org/r/20251220041250.372179-5-roman.gushchin%40linux.dev patch subject: [PATCH bpf-next v2 4/7] mm: introduce BPF kfuncs to access memcg statistics and events config: powerpc64-allnoconfig-bpf (https://download.01.org/0day-ci/archive/20251220/[email protected]/config) compiler: powerpc64-linux-gcc (GCC) 15.1.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251220/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
>> powerpc64-linux-ld: warning: discarding dynamic section .glink >> powerpc64-linux-ld: warning: discarding dynamic section .plt
powerpc64-linux-ld: linkage table error against `mem_cgroup_usage'
powerpc64-linux-ld: stubs don't match calculated size
powerpc64-linux-ld: can not build stubs: bad value
powerpc64-linux-ld: mm/bpf_memcontrol.o: in function `bpf_mem_cgroup_usage':
mm/bpf_memcontrol.c:103:(.text+0x87c): undefined reference to `mem_cgroup_usage'
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Re: [PATCH bpf-next v2 2/7] mm: introduce BPF kfuncs to deal with memcg pointers
In reply to Roman GushchinQuoted 100 lines · Roman Gushchin
To effectively operate with memory cgroups in BPF there is a need to convert css pointers to memcg pointers. A simple
container_ofcast which is used in the kernel code can't be used in BPF because from the verifier's point of view that's a out-of-bounds memory access.Introduce helper get/put kfuncs which can be used to get a refcounted memcg pointer from the css pointer:
-bpf_get_mem_cgroup,
-bpf_put_mem_cgroup.
bpf_get_mem_cgroup()can take both memcg's css and the corresponding cgroup's "self" css. It allows it to be used with the existing cgroup iterator which iterates over cgroup tree, not memcg tree.Signed-off-by Roman Gushchin <[email protected]>--- mm/Makefile | 3 ++ mm/bpf_memcontrol.c | 88 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 mm/bpf_memcontrol.cmm/Makefile +3
-0@@ -106,6 +106,9 @@ obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o ifdef CONFIG_SWAP obj-$(CONFIG_MEMCG) += swap_cgroup.o endif +ifdef CONFIG_BPF_SYSCALL +obj-$(CONFIG_MEMCG) += bpf_memcontrol.o +endif obj-$(CONFIG_CGROUP_HUGETLB) += hugetlb_cgroup.o obj-$(CONFIG_GUP_TEST) += gup_test.o obj-$(CONFIG_DMAPOOL_TEST) += dmapool_test.omm/bpf_memcontrol.c new file +58
-0@@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Memory Controller-related BPF kfuncs and auxiliary code +* +* Author: Roman Gushchin <[email protected]> +*/ + +#include <linux/memcontrol.h> +#include <linux/bpf.h> + +__bpf_kfunc_start_defs (); + +/** +* bpf_get_mem_cgroup - Get a reference to a memory cgroup +* @css: pointer to the css structure +* +* Returns a pointer to a mem_cgroup structure after bumping +* the corresponding css's reference counter. +* +* It's fine to pass a css which belongs to any cgroup controller, +* e.g. unified hierarchy's main css. +* +* Implements KF_ACQUIRE semantics. +*/ +__bpf_kfunc struct mem_cgroup * +bpf_get_mem_cgroup (struct cgroup_subsys_state *css) +{ +struct mem_cgroup *memcg =NULL ; +bool rcu_unlock = false; + +if (mem_cgroup_disabled () || !root_mem_cgroup) +return NULL ; + +if (root_mem_cgroup->css.ss != css->ss) { +struct cgroup *cgroup = css->cgroup; +int ssid = root_mem_cgroup->css.ss->id; + +rcu_read_lock (); + rcu_unlock = true; + css =rcu_dereference_raw (cgroup->subsys[ssid]); + } + +if (css &&css_tryget (css)) + memcg = container_of(css, struct mem_cgroup, css); + +if (rcu_unlock) +rcu_read_unlock (); + +return memcg; +} + +/** +* bpf_put_mem_cgroup - Put a reference to a memory cgroup +* @memcg: memory cgroup to release +* +* Releases a previously acquired memcg reference. +* Implements KF_RELEASE semantics. +*/
mm/bpf_memcontrol.c line 68
Quoted 10 lines
mm/bpf_memcontrol.c new file +10
-0+__bpf_kfunc void bpf_put_mem_cgroup(struct mem_cgroup *memcg) +{ +css_put (&memcg->css); +} + +__bpf_kfunc_end_defs (); + +BTF_KFUNCS_START(bpf_memcontrol_kfuncs) +BTF_ID_FLAGS(func, bpf_get_mem_cgroup, KF_TRUSTED_ARGS | KF_ACQUIRE | KF_RET_NULL | KF_RCU) +BTF_ID_FLAGS(func, bpf_put_mem_cgroup, KF_TRUSTED_ARGS | KF_RELEASE)
This is an unusual combination of flags. KF_RCU is a weaker KF_TRUSTED_ARGS, so just use KF_RCU. We have an odd selftest kmod that specifies both, but it's unnecessary there as well.
Just KF_ACQUIRE | KF_RET_NULL | KF_RCU will do.
Similarly KF_RELEASE implies KF_TRUSTED_ARGS. That's even documented Documentation/bpf/kfuncs.rst, so just use KF_RELEASE for bpf_put_mem_cgroup.
pw-bot: cr
Re: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
In reply to Roman GushchinQuoted 26 lines · Roman Gushchin
From: JP Kobryn <[email protected]>
Introduce BPF kfunc to access memory events, e.g.:
MEMCG_LOW,MEMCG_MAX,MEMCG_OOM,MEMCG_OOM_KILLetc.Signed-off-by JP Kobryn <[email protected]>Signed-off-by Roman Gushchin <[email protected]>Acked-by Shakeel Butt <[email protected]>--- mm/bpf_memcontrol.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)mm/bpf_memcontrol.c +5
-0@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value +* @memcg: memory cgroup +* @event: memory event id +*
mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 120
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ; + +return atomic_long_read (&memcg->memory_events[event]); +}
Why is patch 5 not squashed with patch 4?
I'd think placing bpf_mem_cgroup_memory_events()
right next to bpf_mem_cgroup_vm_events() in the same patch will make the difference more clear.
For non-mm people the names are very close and on the first glance it looks like a duplicate.
Re: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
Quoted 37 lines · Alexei Starovoitov
Quoted 35 lines · Roman Gushchin
From: JP Kobryn <[email protected]>
Introduce BPF kfunc to access memory events, e.g.:
MEMCG_LOW,MEMCG_MAX,MEMCG_OOM,MEMCG_OOM_KILLetc.Signed-off-by JP Kobryn <[email protected]>Signed-off-by Roman Gushchin <[email protected]>Acked-by Shakeel Butt <[email protected]>--- mm/bpf_memcontrol.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)mm/bpf_memcontrol.c +14
-0@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value +* @memcg: memory cgroup +* @event: memory event id +* +* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ; + +return atomic_long_read (&memcg->memory_events[event]);
Quoted 8 lines
mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 120
Quoted 1 line
mm/bpf_memcontrol.c +1
-0+}Why is patch 5 not squashed with patch 4?
I'd think placingbpf_mem_cgroup_memory_events()
right next tobpf_mem_cgroup_vm_events()in the same patch will make the difference more clear.
For non-mm people the names are very close and on the first glance it looks like a duplicate.
Also see a bunch of kdoc warnings flagged by CI.
Roman Gushchin
maintainerRe: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
In reply to Chris MasonQuoted 44 lines · Chris Mason
Quoted 43 lines · Roman Gushchin
Quoted 41 lines · Chris Mason
Quoted 39 lines · Roman Gushchin
Quoted 27 lines · [email protected] writes:
Quoted 10 lines
mm/bpf_memcontrol.c +2
-0@@ -103,6 +103,22 @@ __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg)return mem_cgroup_usage (memcg, false) *PAGE_SIZE ; } +/** +* bpf_mem_cgroup_memory_events - Read memory cgroup's memory event value mm/bpf_memcontrol.c __bpf_kfunc unsigned long bpf_mem_cgroup_usage(struct mem_cgroup *memcg) · line 117
Quoted 10 lines
mm/bpf_memcontrol.c +10
-0+* @memcg: memory cgroup +* @event: memory event id +* +* Returns current memory event count. +*/ +__bpf_kfunc unsigned long bpf_mem_cgroup_memory_events (struct mem_cgroup *memcg, +enum memcg_memory_event event) +{ +if (event >=MEMCG_NR_MEMORY_EVENTS ) +return (unsigned long )-1 ;Should this also check for negative values? The enum type is typically signed, so a BPF program passing a negative event value would pass this check but cause an out-of-bounds read from memcg->memory_events[].
The similar
bpf_mem_cgroup_page_state()in this same file uses:Quoted 7 lines
if (idx < 0 || idx >= MEMCG_NR_STAT)which checks both bounds. Could the check here be changed to:
if (event < 0 || event >= MEMCG_NR_MEMORY_EVENTS)to match that pattern?
No, the bpf verifier enforces event > 0.
It's a false positive.
Quoted 6 lines
Quoted 4 lines
Quoted 1 line
I'll add some words here to the bpf prompts, thanks Roman.
I'll try to play with it too, hopefully we can fix it.
https://github.com/masoncl/review-prompts/commit/fcc3bf704798f6be64cbb2e28b05a5c91eee9c7b
Hi Chris!
I'm sorry, apparently I was dead wrong and overestimated the bpf verifier (and ai was correct, lol). Somebody told me that enums are fully covered as a feedback to an earlier version and I didn't check.
In reality the verifier doesn't guarantee the correctness of the value passed as an enum, only that it's a u32. So we need to check the value. I've added necessarily checks in v3 of my patchset. It passes the local ai review without your latest change. Please, revert it.
Thanks and sorry for the hassle
Re: [PATCH bpf-next v2 5/7] mm: introduce BPF kfunc to access memory events
Quoted 20 lines · Roman Gushchin
Quoted 10 lines · Chris Mason
Quoted 7 lines · Roman Gushchin
Quoted 4 lines
Quoted 2 lines
No, the bpf verifier enforces event > 0.
It's a false positive.I'll add some words here to the bpf prompts, thanks Roman.
I'll try to play with it too, hopefully we can fix it.
https://github.com/masoncl/review-prompts/commit/fcc3bf704798f6be64cbb2e28b05a5c91eee9c7b
Hi Chris!
I'm sorry, apparently I was dead wrong and overestimated the bpf verifier (and ai was correct, lol). Somebody told me that enums are fully covered as a feedback to an earlier version and I didn't check.
Quoted 6 lines
In reality the verifier doesn't guarantee the correctness of the value passed as an enum, only that it's a u32. So we need to check the value. I've added necessarily checks in v3 of my patchset. It passes the local ai review without your latest change. Please, revert it.
Thanks and sorry for the hassle
Thanks Roman, I adjusted the prompt changes and looked harder for proof of exactly what checks are done.
-chris