Skip to contentSkip to conversation

bpf: rstat: cgroup hierarchical stats

PATCH Superseded Yosry Ahmed 3 participants 28 messages Jul 9, 2022 – Jul 21, 2022

Subsystems (8)

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v3 cover bpf: rstat: cgroup hierarchical stats

s patch series allows for using bpf to collect hierarchical cgroup stats efficiently by integrating with the rstat framework. The rstat framework provides an efficient way to collect cgroup stats percpu and propagate them through the cgroup hierarchy.

The stats are exposed to userspace in textual form by reading files in bpffs, similar to cgroupfs stats by using a cgroup_iter program. cgroup_iter is a type of bpf_iter. It walks over cgroups in three modes:
- walking a cgroup's descendants in pre-order.
- walking a cgroup's descendants in post-order.
- walking a cgroup's ancestors.

When attaching cgroup_iter, one needs to set a cgroup to the iter_link created from attaching. This cgroup is passed as a file descriptor and serves as the starting point of the walk.

One can also terminate the walk early by returning 1 from the iter program.

Note that because walking cgroup hierarchy holds cgroup_mutex, the iter program is called with cgroup_mutex held.

** Background on rstat for stats collection **
(I am using a subscriber analogy that is not commonly used)

The rstat framework maintains a tree of cgroups that have updates and which cpus have updates. A subscriber to the rstat framework maintains their own stats. The framework is used to tell the subscriber when and what to flush, for the most efficient stats propagation. The workflow is as follows:

- When a subscriber updates a cgroup on a cpu, it informs the rstat framework by calling cgroup_rstat_updated(cgrp, cpu).

- When a subscriber wants to read some stats for a cgroup, it asks the rstat framework to initiate a stats flush (propagation) by calling cgroup_rstat_flush(cgrp).

- When the rstat framework initiates a flush, it makes callbacks to subscribers to aggregate stats on cpus that have updates, and propagate updates to their parent.

Currently, the main subscribers to the rstat framework are cgroup subsystems (e.g. memory, block). This patch series allow bpf programs to become subscribers as well.

This patch series includes a resend of a patch from the mailing list by Benjamin Tissoires to support sleepable kfuncs [1].

Patches in this series are organized as follows:
* Patch 1 is the resend of the sleepable kfuncs patch [1].
* Patch 2 enables the use of cgroup_get_from_file() in cgroup1. This is useful because it enables cgroup_iter to work with cgroup1, and allows the entire stat collection workflow to be cgroup1-compatible.
* Patches 3-5 introduce cgroup_iter prog, and a selftest.
* Patches 6-8 allow bpf programs to integrate with rstat by adding the necessary hook points and kfunc. A comprehensive selftest that demonstrates the entire workflow for using bpf and rstat to efficiently collect and output cgroup stats is added.

---
Changelog:

v2 -> v3:
- cgroup_iter:
* Added conditional compilation of cgroup_iter.c in kernel/bpf/Makefile (kernel test) and dropped the !CONFIG_CGROUP patch.
* Added validation of traversal_order when attaching (Yonghong).
* Fixed previous wording "two modes" to "three modes" (Yonghong).
* Fixed the btf_dump selftest broken by this patch (Yonghong).
* Fixed ctx_arg_info[0] to use "PTR_TO_BTF_ID_OR_NULL" instead of "PTR_TO_BTF_ID", because the "cgroup" pointer passed to iter prog can be null.
- Use __diag_push to eliminate __weak noinline warning in bpf_rstat_flush().
- cgroup_hierarchical_stats selftest:
* Added write_cgroup_file_parent() helper.
* Added error handling for failed map updates.
* Added null check for cgroup in vmscan_flush.
* Fixed the signature of vmscan_[start/end].
* Correctly return error code when attaching trace programs fail.
* Make sure all links are destroyed correctly and not leaking in cgroup_hierarchical_stats selftest.
* Use memory.reclaim instead of memory.high as a more reliable way to invoke reclaim.
* Eliminated sleeps, the test now runs faster.

v1 -> v2:
- Redesign of cgroup_iter from v1, based on Alexei's idea [2]:
* supports walking cgroup subtree.
* supports walking ancestors of a cgroup. (Andrii)
* supports terminating the walk early.
* uses fd instead of cgroup_id as parameter for iter_link. Using fd is a convention in bpf.
* gets cgroup's ref at attach time and deref at detach.
* brought back cgroup1 support for cgroup_iter.
- Squashed the patches adding the rstat flush hook points and kfuncs (Tejun).
- Added a comment explaining why bpf_rstat_flush() needs to be weak (Tejun).
- Updated the final selftest with the new cgroup_iter design.
- Changed CHECKs in the selftest with ASSERTs (Yonghong, Andrii).
- Removed empty line at the end of the selftest (Yonghong).
- Renamed test files to cgroup_hierarchical_stats.c.
- Reordered CGROUP_PATH params order to match struct declaration in the selftest (Michal).
- Removed memory_subsys_enabled() and made sure memcg controller enablement checks make sense and are documented (Michal).

RFC v2 -> v1:
- Instead of introducing a new program type for rstat flushing, add an empty hook point, bpf_rstat_flush(), and use fentry bpf programs to attach to it and flush bpf stats.
- Instead of using helpers, use kfuncs for rstat functions.
- These changes simplify the patchset greatly, with minimal changes to uapi.

RFC v1 -> RFC v2:
- Instead of rstat flush programs attach to subsystems, they now attach to rstat (global flushers, not per-subsystem), based on discussions with Tejun. The first patch is entirely rewritten.
- Pass cgroup pointers to rstat flushers instead of cgroup ids. This is much more flexibility and less likely to need a uapi update later.
- rstat helpers are now only defined if CGROUP_CONFIG.
- Most of the code is now only defined if CGROUP_CONFIG and CONFIG_BPF_SYSCALL.
- Move rstat helper protos from bpf_base_func_proto() to tracing_prog_func_proto().
- rstat helpers argument (cgroup pointer) is now ARG_PTR_TO_BTF_ID, not ARG_ANYTHING.
- Rewrote the selftest to use the cgroup helpers.
- Dropped bpf_map_lookup_percpu_elem (already added by Feng).
- Dropped patch to support cgroup v1 for cgroup_iter.
- Dropped patch to define some cgroup_put() when !CONFIG_CGROUP. The code that calls it is no longer compiled when !CONFIG_CGROUP.

cgroup_iter was originally introduced in a different patch series[3]. Hao and I agreed that it fits better as part of this series. RFC v1 of this patch series had the following changes from [3]:
- Getting the cgroup's reference at the time at attaching, instead of at the time when iterating. (Yonghong)
- Remove .init_seq_private and .fini_seq_private callbacks for cgroup_iter. They are not needed now. (Yonghong)

[1] https://lore.kernel.org/bpf/20220421140740.459558-5-benjamin.tissoires-H+wXaHxf7aLQT0dZR+AlfA@public.gmane.org/
[2] https://lore.kernel.org/bpf/20220520221919.jnqgv52k4ajlgzcl-X1x1UtSlSMLFI8N7WmjKSuzkJ6j1vHJkzR5nVSMtm21iLUuM0BA3LQ@public.gmane.org/
[3] https://lore.kernel.org/lkml/20220225234339.2386398-9-haoluo-hpIqsD4AKlfQT0dZR+AlfA@public.gmane.org/
---

Benjamin Tissoires (1):
btf: Add a new kfunc set which allows to mark a function to be
sleepable

Hao Luo (3):
bpf, iter: Fix the condition on p when calling stop.
bpf: Introduce cgroup iter
selftests/bpf: Test cgroup_iter.

Yosry Ahmed (4):
cgroup: enable cgroup_get_from_file() on cgroup1
cgroup: bpf: enable bpf programs to integrate with rstat selftests/bpf: extend cgroup helpers
bpf: add a selftest for cgroup hierarchical stats collection

 include/linux/bpf.h                           |   8 +
 include/linux/btf.h                           |   2 +
 include/uapi/linux/bpf.h                      |  21 +
 kernel/bpf/Makefile                           |   3 +
 kernel/bpf/bpf_iter.c                         |   5 +
 kernel/bpf/btf.c                              |  13 +-
 kernel/bpf/cgroup_iter.c                      | 242 ++++++++++++
 kernel/cgroup/cgroup.c                        |   5 -
 kernel/cgroup/rstat.c                         |  54 +++
 tools/include/uapi/linux/bpf.h                |  21 +
 tools/testing/selftests/bpf/cgroup_helpers.c  | 201 ++++++++--
 tools/testing/selftests/bpf/cgroup_helpers.h  |  19 +-
 .../selftests/bpf/prog_tests/btf_dump.c       |   4 +-
 .../prog_tests/cgroup_hierarchical_stats.c    | 362 ++++++++++++++++++
 .../selftests/bpf/prog_tests/cgroup_iter.c    | 190 +++++++++
 tools/testing/selftests/bpf/progs/bpf_iter.h  |   7 +
 .../bpf/progs/cgroup_hierarchical_stats.c     | 235 ++++++++++++
 .../testing/selftests/bpf/progs/cgroup_iter.c |  39 ++
 18 files changed, 1375 insertions(+), 56 deletions(-)
 create mode 100644 kernel/bpf/cgroup_iter.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/cgroup_iter.c
 create mode 100644 tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c
 create mode 100644 tools/testing/selftests/bpf/progs/cgroup_iter.c
Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#1 lore raw

PATCH v3 1/8 btf: Add a new kfunc set which allows to mark a function to be sleepable

From: Benjamin Tissoires <[email protected]>

This allows to declare a kfunc as sleepable and prevents its use in a non sleepable program.

---
 include/linux/btf.h |  2 ++
 kernel/bpf/btf.c    | 13 +++++++++++--
 2 files changed, 13 insertions(+), 2 deletions(-)
include/linux/btf.h +2 -0
index 1bfed7fa04287..6e7517573d9e4 100644
@@ -18,6 +18,7 @@ enum btf_kfunc_type {
 	BTF_KFUNC_TYPE_RELEASE,
 	BTF_KFUNC_TYPE_RET_NULL,
 	BTF_KFUNC_TYPE_KPTR_ACQUIRE,
+	BTF_KFUNC_TYPE_SLEEPABLE,
 	BTF_KFUNC_TYPE_MAX,
 };
 
@@ -37,6 +38,7 @@ struct btf_kfunc_id_set {
 			struct btf_id_set *release_set;
 			struct btf_id_set *ret_null_set;
 			struct btf_id_set *kptr_acquire_set;
+			struct btf_id_set *sleepable_set;
 		};
 		struct btf_id_set *sets[BTF_KFUNC_TYPE_MAX];
 	};
kernel/bpf/btf.c +11 -2
index 4f2408a4df08b..2a4b4e50b6fb7 100644
@@ -6172,7 +6172,7 @@ static int btf_check_func_arg_match(struct bpf_verifier_env *env,
 	struct bpf_verifier_log *log = &env->log;
 	u32 i, nargs, ref_id, ref_obj_id = 0;
 	bool is_kfunc = btf_is_kernel(btf);
-	bool rel = false, kptr_get = false;
+	bool rel = false, kptr_get = false, sleepable = false;
 	const char *func_name, *ref_tname;
 	const struct btf_type *t, *ref_t;
 	const struct btf_param *args;
@@ -6203,11 +6203,13 @@ static int btf_check_func_arg_match(struct bpf_verifier_env *env,
 	}
 
 	if (is_kfunc) {
-		/* Only kfunc can be release func */
+		/* Only kfunc can be release, kptr acquire, or sleepable func */
 		rel = btf_kfunc_id_set_contains(btf, resolve_prog_type(env->prog),
 						BTF_KFUNC_TYPE_RELEASE, func_id);
 		kptr_get = btf_kfunc_id_set_contains(btf, resolve_prog_type(env->prog),
 						     BTF_KFUNC_TYPE_KPTR_ACQUIRE, func_id);
+		sleepable = btf_kfunc_id_set_contains(btf, resolve_prog_type(env->prog),
+						      BTF_KFUNC_TYPE_SLEEPABLE, func_id);
 	}
 
 	/* check that BTF function arguments match actual types that the
@@ -6405,6 +6407,13 @@ static int btf_check_func_arg_match(struct bpf_verifier_env *env,
 			func_name);
 		return -EINVAL;
 	}
+
+	if (sleepable && !env->prog->aux->sleepable) {
+		bpf_log(log, "kernel function %s is sleepable but the program is not\n",
+			func_name);
+		return -EINVAL;
+	}
+
 	/* returns argument register number > 0 in case of reference release kfunc */
 	return rel ? ref_regno : 0;
 }
Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#2 lore raw

PATCH v3 2/8 cgroup: enable cgroup_get_from_file() on cgroup1

In reply to Yosry Ahmed

cgroup_get_from_file() currently fails with -EBADF if called on cgroup v1. However, the current implementation works on cgroup v1 as well, so the restriction is unnecessary.

This enabled cgroup_get_from_fd() to work on cgroup v1, which would be the only thing stopping bpf cgroup_iter from supporting cgroup v1.

---
 kernel/cgroup/cgroup.c | 5 -----
 1 file changed, 5 deletions(-)
kernel/cgroup/cgroup.c +0 -5
index 1779ccddb734d..9943fcb1e574d 100644
@@ -6090,11 +6090,6 @@ static struct cgroup *cgroup_get_from_file(struct file *f)
 		return ERR_CAST(css);
 
 	cgrp = css->cgroup;
-	if (!cgroup_on_dfl(cgrp)) {
-		cgroup_put(cgrp);
-		return ERR_PTR(-EBADF);
-	}
-
 	return cgrp;
 }
 
Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#3 lore raw

PATCH v3 3/8 bpf, iter: Fix the condition on p when calling stop.

In reply to Yosry Ahmed

From: Hao Luo <[email protected]>

In bpf_seq_read, seq->op->next() could return an ERR and jump to the label stop. However, the existing code in stop does not handle the case when p (returned from next()) is an ERR. Adds the handling of ERR of p by converting p into an error and jumping to done.

Because all the current implementations do not have a case that returns ERR from next(), so this patch doesn't have behavior changes right now.

---
 kernel/bpf/bpf_iter.c | 5 +++++
 1 file changed, 5 insertions(+)
kernel/bpf/bpf_iter.c +5 -0
index 7e8fd49406f64..4688ba39ef25c 100644
@@ -198,6 +198,11 @@ static ssize_t bpf_seq_read(struct file *file, char __user *buf, size_t size,
 	}
 stop:
 	offs = seq->count;
+	if (IS_ERR(p)) {
+		seq->op->stop(seq, NULL);
+		err = PTR_ERR(p);
+		goto done;
+	}
 	/* bpf program called if !p */
 	seq->op->stop(seq, p);
 	if (!p) {
Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#4 lore raw

PATCH v3 4/8 bpf: Introduce cgroup iter

In reply to Yosry Ahmed

From: Hao Luo <[email protected]>

Cgroup_iter is a type of bpf_iter. It walks over cgroups in three modes:

- walking a cgroup's descendants in pre-order.
- walking a cgroup's descendants in post-order.
- walking a cgroup's ancestors.

When attaching cgroup_iter, one can set a cgroup to the iter_link created from attaching. This cgroup is passed as a file descriptor and serves as the starting point of the walk. If no cgroup is specified, the starting point will be the root cgroup.

For walking descendants, one can specify the order: either pre-order or post-order. For walking ancestors, the walk starts at the specified cgroup and ends at the root.

One can also terminate the walk early by returning 1 from the iter program.

Note that because walking cgroup hierarchy holds cgroup_mutex, the iter program is called with cgroup_mutex held.

---
 include/linux/bpf.h                           |   8 +
 include/uapi/linux/bpf.h                      |  21 ++
 kernel/bpf/Makefile                           |   3 +
 kernel/bpf/cgroup_iter.c                      | 242 ++++++++++++++++++
 tools/include/uapi/linux/bpf.h                |  21 ++
 .../selftests/bpf/prog_tests/btf_dump.c       |   4 +-
 6 files changed, 297 insertions(+), 2 deletions(-)
 create mode 100644 kernel/bpf/cgroup_iter.c
include/linux/bpf.h +8 -0
index 2b21f2a3452ff..5de9de06e2551 100644
@@ -47,6 +47,7 @@ struct kobject;
 struct mem_cgroup;
 struct module;
 struct bpf_func_state;
+struct cgroup;
 
 extern struct idr btf_idr;
 extern spinlock_t btf_idr_lock;
@@ -1714,7 +1715,14 @@ int bpf_obj_get_user(const char __user *pathname, int flags);
 	int __init bpf_iter_ ## target(args) { return 0; }
 
 struct bpf_iter_aux_info {
+	/* for map_elem iter */
 	struct bpf_map *map;
+
+	/* for cgroup iter */
+	struct {
+		struct cgroup *start; /* starting cgroup */
+		int order;
+	} cgroup;
 };
 
 typedef int (*bpf_iter_attach_target_t)(struct bpf_prog *prog,
include/uapi/linux/bpf.h +21 -0
index 379e68fb866fc..6f5979e221927 100644
@@ -87,10 +87,27 @@ struct bpf_cgroup_storage_key {
 	__u32	attach_type;		/* program attach type (enum bpf_attach_type) */
 };
 
+enum bpf_iter_cgroup_traversal_order {
+	BPF_ITER_CGROUP_PRE = 0,	/* pre-order traversal */
+	BPF_ITER_CGROUP_POST,		/* post-order traversal */
+	BPF_ITER_CGROUP_PARENT_UP,	/* traversal of ancestors up to the root */
+};
+
 union bpf_iter_link_info {
 	struct {
 		__u32	map_fd;
 	} map;
+
+	/* cgroup_iter walks either the live descendants of a cgroup subtree, or the ancestors
+	 * of a given cgroup.
+	 */
+	struct {
+		/* Cgroup file descriptor. This is root of the subtree if for walking the
+		 * descendants; this is the starting cgroup if for walking the ancestors.
+		 */
+		__u32	cgroup_fd;
+		__u32	traversal_order;
+	} cgroup;
 };
 
 /* BPF syscall commands, see bpf(2) man-page for more details. */
@@ -6134,6 +6151,10 @@ struct bpf_link_info {
 				struct {
 					__u32 map_id;
 				} map;
+				struct {
+					__u32 traversal_order;
+					__aligned_u64 cgroup_id;
+				} cgroup;
 			};
 		} iter;
 		struct  {
kernel/bpf/Makefile +3 -0
index 057ba8e01e70f..00e05b69a4df1 100644
@@ -24,6 +24,9 @@ endif
 ifeq ($(CONFIG_PERF_EVENTS),y)
 obj-$(CONFIG_BPF_SYSCALL) += stackmap.o
 endif
+ifeq ($(CONFIG_CGROUPS),y)
+obj-$(CONFIG_BPF_SYSCALL) += cgroup_iter.o
+endif
 obj-$(CONFIG_CGROUP_BPF) += cgroup.o
 ifeq ($(CONFIG_INET),y)
 obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o
kernel/bpf/cgroup_iter.c new file +242 -0

242 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +21 -0
index 379e68fb866fc..6f5979e221927 100644
@@ -87,10 +87,27 @@ struct bpf_cgroup_storage_key {
 	__u32	attach_type;		/* program attach type (enum bpf_attach_type) */
 };
 
+enum bpf_iter_cgroup_traversal_order {
+	BPF_ITER_CGROUP_PRE = 0,	/* pre-order traversal */
+	BPF_ITER_CGROUP_POST,		/* post-order traversal */
+	BPF_ITER_CGROUP_PARENT_UP,	/* traversal of ancestors up to the root */
+};
+
 union bpf_iter_link_info {
 	struct {
 		__u32	map_fd;
 	} map;
+
+	/* cgroup_iter walks either the live descendants of a cgroup subtree, or the ancestors
+	 * of a given cgroup.
+	 */
+	struct {
+		/* Cgroup file descriptor. This is root of the subtree if for walking the
+		 * descendants; this is the starting cgroup if for walking the ancestors.
+		 */
+		__u32	cgroup_fd;
+		__u32	traversal_order;
+	} cgroup;
 };
 
 /* BPF syscall commands, see bpf(2) man-page for more details. */
@@ -6134,6 +6151,10 @@ struct bpf_link_info {
 				struct {
 					__u32 map_id;
 				} map;
+				struct {
+					__u32 traversal_order;
+					__aligned_u64 cgroup_id;
+				} cgroup;
 			};
 		} iter;
 		struct  {
tools/testing/selftests/bpf/prog_tests/btf_dump.c +2 -2
index 5fce7008d1ff3..604a40777cfa8 100644
@@ -764,8 +764,8 @@ static void test_btf_dump_struct_data(struct btf *btf, struct btf_dump *d,
 
 	/* union with nested struct */
 	TEST_BTF_DUMP_DATA(btf, d, "union", str, union bpf_iter_link_info, BTF_F_COMPACT,
-			   "(union bpf_iter_link_info){.map = (struct){.map_fd = (__u32)1,},}",
-			   { .map = { .map_fd = 1 }});
+			   "(union bpf_iter_link_info){.map = (struct){.map_fd = (__u32)1,},.cgroup = (struct){.cgroup_fd = (__u32)1,.traversal_order = (__u32)1,},}",
+			   { .cgroup = { .cgroup_fd = 1, .traversal_order = 1, }});
 
 	/* struct skb with nested structs/unions; because type output is so
 	 * complex, we don't do a string comparison, just verify we return
Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#5 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 78 lines · Yosry Ahmed

From: Hao Luo <[email protected]>

Cgroup_iter is a type of bpf_iter. It walks over cgroups in three modes:

- walking a cgroup's descendants in pre-order.
- walking a cgroup's descendants in post-order.
- walking a cgroup's ancestors.

When attaching cgroup_iter, one can set a cgroup to the iter_link created from attaching. This cgroup is passed as a file descriptor and serves as the starting point of the walk. If no cgroup is specified, the starting point will be the root cgroup.

For walking descendants, one can specify the order: either pre-order or post-order. For walking ancestors, the walk starts at the specified cgroup and ends at the root.

One can also terminate the walk early by returning 1 from the iter program.

Note that because walking cgroup hierarchy holds cgroup_mutex, the iter program is called with cgroup_mutex held.

---
  include/linux/bpf.h                           |   8 +
  include/uapi/linux/bpf.h                      |  21 ++
  kernel/bpf/Makefile                           |   3 +
  kernel/bpf/cgroup_iter.c                      | 242 ++++++++++++++++++
  tools/include/uapi/linux/bpf.h                |  21 ++
  .../selftests/bpf/prog_tests/btf_dump.c       |   4 +-
  6 files changed, 297 insertions(+), 2 deletions(-)

create mode 100644 kernel/bpf/cgroup_iter.c

include/linux/bpf.h +8 -0
index 2b21f2a3452ff..5de9de06e2551 100644
@@ -47,6 +47,7 @@ struct kobject;
  struct mem_cgroup;
  struct module;
  struct bpf_func_state;
+struct cgroup;
 
  extern struct idr btf_idr;
  extern spinlock_t btf_idr_lock;
@@ -1714,7 +1715,14 @@ int bpf_obj_get_user(const char __user *pathname, int flags);
  	int __init bpf_iter_ ## target(args) { return 0; }
 
  struct bpf_iter_aux_info {
+	/* for map_elem iter */
  	struct bpf_map *map;
+
+	/* for cgroup iter */
+	struct {
+		struct cgroup *start; /* starting cgroup */
+		int order;
+	} cgroup;
  };
 
  typedef int (*bpf_iter_attach_target_t)(struct bpf_prog *prog,
include/uapi/linux/bpf.h +6 -0
index 379e68fb866fc..6f5979e221927 100644
@@ -87,10 +87,27 @@ struct bpf_cgroup_storage_key {
  	__u32	attach_type;		/* program attach type (enum bpf_attach_type) */
  };
 
+enum bpf_iter_cgroup_traversal_order {
+	BPF_ITER_CGROUP_PRE = 0,	/* pre-order traversal */
+	BPF_ITER_CGROUP_POST,		/* post-order traversal */
+	BPF_ITER_CGROUP_PARENT_UP,	/* traversal of ancestors up to the root */
+};
+
  union bpf_iter_link_info {

include/uapi/linux/bpf.h struct bpf_cgroup_storage_key { · line 106

Quoted 10 lines
include/uapi/linux/bpf.h +7 -0
  	struct {
  		__u32	map_fd;
  	} map;
+
+	/* cgroup_iter walks either the live descendants of a cgroup subtree, or the ancestors
+	 * of a given cgroup.
+	 */
+	struct {
+		/* Cgroup file descriptor. This is root of the subtree if for walking the
+		 * descendants; this is the starting cgroup if for walking the ancestors.

Adding comment that cgroup_fd 0 means starting from root cgroup?
Also, if I understand correctly, cgroup v1 is also supported here, right? If this is the case, for cgroup v1 which root cgroup will be used for cgroup_fd? It would be good to clarify here too.

Quoted 8 lines
include/uapi/linux/bpf.h +4 -0
+		 */
+		__u32	cgroup_fd;
+		__u32	traversal_order;
+	} cgroup;
  };
 
  /* BPF syscall commands, see bpf(2) man-page for more details. */

include/uapi/linux/bpf.h struct bpf_link_info { · line 6157

Quoted 7 lines
include/uapi/linux/bpf.h +4 -0
@@ -6134,6 +6151,10 @@ struct bpf_link_info {
  				struct {
  					__u32 map_id;
  				} map;
+				struct {
+					__u32 traversal_order;
+					__aligned_u64 cgroup_id;
+				} cgroup;

We actually has a problem here although I don't have a solution yet.

Without this patch, for bpf_link_info structure, the output of pahole,

                struct { 


                        __u64              target_name 

__attribute__((__aligned__(8))); /* 0 8 */

__u32 target_name_len; /*
8 4 */

                        union { 


                                struct { 


                                        __u32 map_id;            /* 

12 4 */

                                } map;                           /* 
12     4 */
                        };                                       /* 
12     4 */
                        union {
                                struct {
                                        __u32      map_id; 
  /*     0     4 */
                                } map; 
  /*     0     4 */
                        };

                } iter;

You can see map_id has the offset 12 from the beginning of 'iter' structure.

With this patch,

                struct {
                        __u64              target_name 

__attribute__((__aligned__(8))); /* 0 8 */
__u32 target_name_len; /*
8 4 */

                        /* XXX 4 bytes hole, try to pack */

                        union {
                                struct {
                                        __u32 map_id;            /* 
16     4 */
                                } map;                           /* 
16     4 */
                                struct {
                                        __u32 traversal_order;   /* 

16 4 */

                                        /* XXX 4 bytes hole, try to pack */

                                        __u64 cgroup_id;         /* 
24     8 */
                                } cgroup;                        /* 
16    16 */
                        };                                       /* 
16    16 */
                        union {
                                struct {
                                        __u32      map_id; 
  /*     0     4 */
                                } map; 
  /*     0     4 */
                                struct {
                                        __u32      traversal_order; 

/* 0 4 */

                                        /* XXX 4 bytes hole, try to pack */

                                        __u64      cgroup_id; 
  /*     8     8 */
                                } cgroup; 
  /*     0    16 */
                        };

                } iter;

There is a 4 byte hole after member 'target_name_len'. So map_id will have a offset 16 from the start of structure 'iter'.

This will break uapi. We probably won't be able to change the existing uapi with adding a ':32' after member 'target_name_len'. I don't have a good solution yet, but any suggestion is welcome.

Also, for '__aligned_u64 cgroup_id', '__u64 cgroup_id' is enough. '__aligned_u64' mostly used for pointers.

Quoted 64 lines
include/uapi/linux/bpf.h +0 -0
  			};
  		} iter;
  		struct  {
kernel/bpf/Makefile +3 -0
index 057ba8e01e70f..00e05b69a4df1 100644
@@ -24,6 +24,9 @@ endif
  ifeq ($(CONFIG_PERF_EVENTS),y)
  obj-$(CONFIG_BPF_SYSCALL) += stackmap.o
  endif
+ifeq ($(CONFIG_CGROUPS),y)
+obj-$(CONFIG_BPF_SYSCALL) += cgroup_iter.o
+endif
  obj-$(CONFIG_CGROUP_BPF) += cgroup.o
  ifeq ($(CONFIG_INET),y)
  obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o
kernel/bpf/cgroup_iter.c new file +41 -0
new file mode 100644
index 0000000000000..8f50b326016e6
@@ -0,0 +1,242 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2022 Google */
+#include <linux/bpf.h>
+#include <linux/btf_ids.h>
+#include <linux/cgroup.h>
+#include <linux/kernel.h>
+#include <linux/seq_file.h>
+
+#include "../cgroup/cgroup-internal.h"  /* cgroup_mutex and cgroup_is_dead */
+
+/* cgroup_iter provides three modes of traversal to the cgroup hierarchy.
+ *
+ *  1. Walk the descendants of a cgroup in pre-order.
+ *  2. Walk the descendants of a cgroup in post-order.
+ *  2. Walk the ancestors of a cgroup.
+ *
+ * For walking descendants, cgroup_iter can walk in either pre-order or
+ * post-order. For walking ancestors, the iter walks up from a cgroup to
+ * the root.
+ *
+ * The iter program can terminate the walk early by returning 1. Walk
+ * continues if prog returns 0.
+ *
+ * The prog can check (seq->num == 0) to determine whether this is
+ * the first element. The prog may also be passed a NULL cgroup,
+ * which means the walk has completed and the prog has a chance to
+ * do post-processing, such as outputing an epilogue.
+ *
+ * Note: the iter_prog is called with cgroup_mutex held.
+ */
+
+struct bpf_iter__cgroup {
+	__bpf_md_ptr(struct bpf_iter_meta *, meta);
+	__bpf_md_ptr(struct cgroup *, cgroup);
+};
+
+struct cgroup_iter_priv {
+	struct cgroup_subsys_state *start_css;
+	bool terminate;
+	int order;
+};

kernel/bpf/cgroup_iter.c line 51

Quoted 10 lines
kernel/bpf/cgroup_iter.c new file +10 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+	struct cgroup_iter_priv *p = seq->private;
+
+	mutex_lock(&cgroup_mutex);
+
+	/* support only one session */
+	if (*pos > 0)
+		return NULL;

This might be okay. But want to check what is
the practical upper limit for cgroups in a system
and whether we may miss some cgroups. If this
happens, it will be a surprise to the user.

Quoted 22 lines
kernel/bpf/cgroup_iter.c new file +22 -0
+
+	++*pos;
+	p->terminate = false;
+	if (p->order == BPF_ITER_CGROUP_PRE)
+		return css_next_descendant_pre(NULL, p->start_css);
+	else if (p->order == BPF_ITER_CGROUP_POST)
+		return css_next_descendant_post(NULL, p->start_css);
+	else /* BPF_ITER_CGROUP_PARENT_UP */
+		return p->start_css;
+}
+
+static int __cgroup_iter_seq_show(struct seq_file *seq,
+				  struct cgroup_subsys_state *css, int in_stop);
+
+static void cgroup_iter_seq_stop(struct seq_file *seq, void *v)
+{
+	/* pass NULL to the prog for post-processing */
+	if (!v)
+		__cgroup_iter_seq_show(seq, NULL, true);
+	mutex_unlock(&cgroup_mutex);
+}
+

[...]

#6 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 195 lines · Yonghong Song
Quoted 81 lines · Yosry Ahmed

From: Hao Luo <[email protected]>

Cgroup_iter is a type of bpf_iter. It walks over cgroups in three modes:

  - walking a cgroup's descendants in pre-order.
  - walking a cgroup's descendants in post-order.
  - walking a cgroup's ancestors.

When attaching cgroup_iter, one can set a cgroup to the iter_link created from attaching. This cgroup is passed as a file descriptor and serves as the starting point of the walk. If no cgroup is specified, the starting point will be the root cgroup.

For walking descendants, one can specify the order: either pre-order or post-order. For walking ancestors, the walk starts at the specified cgroup and ends at the root.

One can also terminate the walk early by returning 1 from the iter program.

Note that because walking cgroup hierarchy holds cgroup_mutex, the iter program is called with cgroup_mutex held.

---
  include/linux/bpf.h                           |   8 + include/uapi/linux/bpf.h                      |  21 ++ kernel/bpf/Makefile                           |   3 + kernel/bpf/cgroup_iter.c                      | 242 ++++++++++++++++++ tools/include/uapi/linux/bpf.h                |  21 ++ .../selftests/bpf/prog_tests/btf_dump.c       |   4 +-

  6 files changed, 297 insertions(+), 2 deletions(-)

  create mode 100644 kernel/bpf/cgroup_iter.c

include/linux/bpf.h +8 -0
index 2b21f2a3452ff..5de9de06e2551 100644
@@ -47,6 +47,7 @@ struct kobject;
   struct mem_cgroup;
   struct module;
   struct bpf_func_state;
+struct cgroup;
   extern struct idr btf_idr;
   extern spinlock_t btf_idr_lock;
@@ -1714,7 +1715,14 @@ int bpf_obj_get_user(const char __user 
 *pathname, int flags);
       int __init bpf_iter_ ## target(args) { return 0; }
   struct bpf_iter_aux_info {
+    /* for map_elem iter */
       struct bpf_map *map;
+
+    /* for cgroup iter */
+    struct {
+        struct cgroup *start; /* starting cgroup */
+        int order;
+    } cgroup;
   };
   typedef int (*bpf_iter_attach_target_t)(struct bpf_prog *prog,
include/uapi/linux/bpf.h +0 -0
index 379e68fb866fc..6f5979e221927 100644
@@ -87,10 +87,27 @@ struct bpf_cgroup_storage_key {

      __u32    attach_type;        /* program attach type (enum bpf_attach_type) */ };
+enum bpf_iter_cgroup_traversal_order {
+    BPF_ITER_CGROUP_PRE = 0,    /* pre-order traversal */
+    BPF_ITER_CGROUP_POST,        /* post-order traversal */
+    BPF_ITER_CGROUP_PARENT_UP,    /* traversal of ancestors up to the root */

include/uapi/linux/bpf.h +2 -0
+};
+

  union bpf_iter_link_info {
      struct {
          __u32    map_fd;
      } map;
+
+    /* cgroup_iter walks either the live descendants of a cgroup

Quoted 8 lines

subtree, or the ancestors
+     * of a given cgroup.
+     */
+    struct {
+        /* Cgroup file descriptor. This is root of the subtree if for walking the
+         * descendants; this is the starting cgroup if for walking the ancestors.

Adding comment that cgroup_fd 0 means starting from root cgroup?
Also, if I understand correctly, cgroup v1 is also supported here, right? If this is the case, for cgroup v1 which root cgroup will be used for cgroup_fd? It would be good to clarify here too.

Quoted 7 lines

+         */
+        __u32    cgroup_fd;
+        __u32    traversal_order;
+    } cgroup;
  };
  /* BPF syscall commands, see bpf(2) man-page for more details. */

include/uapi/linux/bpf.h struct bpf_link_info { · line 6157

Quoted 7 lines
include/uapi/linux/bpf.h +4 -0
@@ -6134,6 +6151,10 @@ struct bpf_link_info {
                   struct {
                       __u32 map_id;
                   } map;
+                struct {
+                    __u32 traversal_order;
+                    __aligned_u64 cgroup_id;
+                } cgroup;

We actually has a problem here although I don't have a solution yet.

Without this patch, for bpf_link_info structure, the output of pahole,

                struct {

                        __u64              target_name
__attribute__((__aligned__(8))); /*     0     8 */
                        __u32              target_name_len;      /* 8     4 */
                        union {

                                struct {

                                        __u32 map_id;            /*
12     4 */
                                } map;                           /*
12     4 */
                        };                                       /*
12     4 */
                        union {
                                struct {
                                        __u32      map_id;   /*
0     4 */
                                } map;   /*     0     4 */ };

                } iter;

You can see map_id has the offset 12 from the beginning of 'iter' structure.

With this patch,

                struct {
                        __u64              target_name
__attribute__((__aligned__(8))); /*     0     8 */
                        __u32              target_name_len;      /* 8     4 */

                        /* XXX 4 bytes hole, try to pack */

                        union {
                                struct {
                                        __u32 map_id;            /*
16     4 */
                                } map;                           /*
16     4 */
                                struct {
                                        __u32 traversal_order;   /*
16     4 */

                                        /* XXX 4 bytes hole, try to
pack */

                                        __u64 cgroup_id;         /*
24     8 */
                                } cgroup;                        /*
16    16 */
                        };                                       /*
16    16 */
                        union {
                                struct {
                                        __u32      map_id;   /*
0     4 */
                                } map;   /*     0     4 */ struct {
                                        __u32      traversal_order;
/*     0     4 */

                                        /* XXX 4 bytes hole, try to
pack */

                                        __u64      cgroup_id;   /*
8     8 */
                                } cgroup;   /*     0    16 */ };

                } iter;

There is a 4 byte hole after member 'target_name_len'. So map_id will have a offset 16 from the start of structure 'iter'.

Quoted 6 lines

This will break uapi. We probably won't be able to change the existing uapi with adding a ':32' after member 'target_name_len'. I don't have a good solution yet, but any suggestion is welcome.

Also, for '__aligned_u64 cgroup_id', '__u64 cgroup_id' is enough. '__aligned_u64' mostly used for pointers.

Briefly discussed with Alexei, the following structure iter definition should work. Later on, if we need to addition fields for other iter's, for a single __u32, the field can be added to either the first or the second union. If fields are more than __u32, they can be placed in the second union.

                struct {
                        __aligned_u64 target_name; /* in/out: 
target_name buffer ptr */
                        __u32 target_name_len;     /* in/out: 
target_name buffer len */
                        union {
                                struct {
                                        __u32 map_id;
                                } map;
                        };
                        union {
                                struct {
                                        __u64 cgroup_id;
                                        __u32 traversal_order;
                                } cgroup;
                        };
                } iter;
Quoted 107 lines
Quoted 68 lines
include/uapi/linux/bpf.h +0 -0
               };
           } iter;
           struct  {
kernel/bpf/Makefile +0 -0
index 057ba8e01e70f..00e05b69a4df1 100644
@@ -24,6 +24,9 @@ endif
   ifeq ($(CONFIG_PERF_EVENTS),y)

  obj-$(CONFIG_BPF_SYSCALL) += stackmap.o
  endif

kernel/bpf/Makefile +3 -0
+ifeq ($(CONFIG_CGROUPS),y)
+obj-$(CONFIG_BPF_SYSCALL) += cgroup_iter.o
+endif

  obj-$(CONFIG_CGROUP_BPF) += cgroup.o
  ifeq ($(CONFIG_INET),y)
  obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o

kernel/bpf/cgroup_iter.c new file +9 -0
new file mode 100644
index 0000000000000..8f50b326016e6
@@ -0,0 +1,242 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2022 Google */
+#include <linux/bpf.h>
+#include <linux/btf_ids.h>
+#include <linux/cgroup.h>
+#include <linux/kernel.h>
+#include <linux/seq_file.h>
+
+#include "../cgroup/cgroup-internal.h"  /* cgroup_mutex and 

cgroup_is_dead */

kernel/bpf/cgroup_iter.c new file +2 -0
+
+/* cgroup_iter provides three modes of traversal to the cgroup 

hierarchy.
+ *
+ *  1. Walk the descendants of a cgroup in pre-order.
+ *  2. Walk the descendants of a cgroup in post-order.
+ *  2. Walk the ancestors of a cgroup.
+ *
+ * For walking descendants, cgroup_iter can walk in either pre-order or
+ * post-order. For walking ancestors, the iter walks up from a cgroup to
+ * the root.
+ *
+ * The iter program can terminate the walk early by returning 1. Walk
+ * continues if prog returns 0.
+ *
+ * The prog can check (seq->num == 0) to determine whether this is
+ * the first element. The prog may also be passed a NULL cgroup,
+ * which means the walk has completed and the prog has a chance to
+ * do post-processing, such as outputing an epilogue.
+ *
+ * Note: the iter_prog is called with cgroup_mutex held.
+ */

kernel/bpf/cgroup_iter.c new file +11 -0
+
+struct bpf_iter__cgroup {
+    __bpf_md_ptr(struct bpf_iter_meta *, meta);
+    __bpf_md_ptr(struct cgroup *, cgroup);
+};
+
+struct cgroup_iter_priv {
+    struct cgroup_subsys_state *start_css;
+    bool terminate;
+    int order;
+};

kernel/bpf/cgroup_iter.c line 51

Quoted 10 lines
kernel/bpf/cgroup_iter.c new file +10 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+    struct cgroup_iter_priv *p = seq->private;
+
+    mutex_lock(&cgroup_mutex);
+
+    /* support only one session */
+    if (*pos > 0)
+        return NULL;

This might be okay. But want to check what is
the practical upper limit for cgroups in a system
and whether we may miss some cgroups. If this
happens, it will be a surprise to the user.

Quoted 22 lines
kernel/bpf/cgroup_iter.c new file +22 -0
+
+    ++*pos;
+    p->terminate = false;
+    if (p->order == BPF_ITER_CGROUP_PRE)
+        return css_next_descendant_pre(NULL, p->start_css);
+    else if (p->order == BPF_ITER_CGROUP_POST)
+        return css_next_descendant_post(NULL, p->start_css);
+    else /* BPF_ITER_CGROUP_PARENT_UP */
+        return p->start_css;
+}
+
+static int __cgroup_iter_seq_show(struct seq_file *seq,
+                  struct cgroup_subsys_state *css, int in_stop);
+
+static void cgroup_iter_seq_stop(struct seq_file *seq, void *v)
+{
+    /* pass NULL to the prog for post-processing */
+    if (!v)
+        __cgroup_iter_seq_show(seq, NULL, true);
+    mutex_unlock(&cgroup_mutex);
+}
+

[...]

#7 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 4 lines · Yonghong Song
Quoted 2 lines · Yonghong Song

[...]

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
include/uapi/linux/bpf.h +3 -0
+
  union bpf_iter_link_info {
      struct {
          __u32    map_fd;
      } map;
+
+    /* cgroup_iter walks either the live descendants of a cgroup

subtree, or the ancestors
+ * of a given cgroup.

Quoted 8 lines
Quoted 8 lines
Quoted 6 lines
include/uapi/linux/bpf.h +3 -0
+     */
+    struct {
+        /* Cgroup file descriptor. This is root of the subtree if for

walking the
+ * descendants; this is the starting cgroup if for walking
the ancestors.

Adding comment that cgroup_fd 0 means starting from root cgroup?

Sure.

Quoted 4 lines
Quoted 4 lines

Also, if I understand correctly, cgroup v1 is also supported here, right? If this is the case, for cgroup v1 which root cgroup will be used for cgroup_fd? It would be good to clarify here too.

IMO, the case of cgroup_fd = 0 combined with cgroup v1 should return errors. It's an invalid case. If anyone wants to use cgroup_iter on cgroup v1 hierarchy, they could explicitly open the subsystems' root directory and pass the fd. With that said, Yosry and I will test and confirm the behavior in this situation and clarify in the comment. Thanks for pointing this out.

Quoted 17 lines
Quoted 17 lines
Quoted 7 lines
include/uapi/linux/bpf.h +4 -0
+         */
+        __u32    cgroup_fd;
+        __u32    traversal_order;
+    } cgroup;
  };
  /* BPF syscall commands, see bpf(2) man-page for more details. */

include/uapi/linux/bpf.h struct bpf_link_info { · line 6157

Quoted 7 lines
include/uapi/linux/bpf.h +4 -0
@@ -6134,6 +6151,10 @@ struct bpf_link_info {
                  struct {
                      __u32 map_id;
                  } map;
+                struct {
+                    __u32 traversal_order;
+                    __aligned_u64 cgroup_id;
+                } cgroup;

We actually has a problem here although I don't have a solution yet.

[...]

Quoted 27 lines
Quoted 11 lines

There is a 4 byte hole after member 'target_name_len'. So map_id will have a offset 16 from the start of structure 'iter'.

This will break uapi. We probably won't be able to change the existing uapi with adding a ':32' after member 'target_name_len'. I don't have a good solution yet, but any suggestion is welcome.

Also, for '__aligned_u64 cgroup_id', '__u64 cgroup_id' is enough. '__aligned_u64' mostly used for pointers.

Briefly discussed with Alexei, the following structure iter definition should work. Later on, if we need to addition fields for other iter's, for a single __u32, the field can be added to either the first or the second union. If fields are more than __u32, they can be placed in the second union.

                 struct {
                         __aligned_u64 target_name; /* in/out:
target_name buffer ptr */
                         __u32 target_name_len;     /* in/out:
target_name buffer len */
                         union {
                                 struct {
                                         __u32 map_id;
                                 } map;
Quoted 9 lines
                         };
                         union {
                                 struct {
                                         __u64 cgroup_id;
                                         __u32 traversal_order;
                                 } cgroup;
                         };
                 } iter;

Thanks Yonghong for seeking the solution here. The solution looks good. I'm going to put your heads-up as comments there. One thing I'd like to confirm, when we query bpf_link_info for cgroup iter, do we also need to zero those fields for map_elem?

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines


              };
          } iter;
          struct  {

[...]

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
kernel/bpf/cgroup_iter.c new file +8 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+    struct cgroup_iter_priv *p = seq->private;
+
+    mutex_lock(&cgroup_mutex);
+
+    /* support only one session */
Quoted 8 lines
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    if (*pos > 0)
+        return NULL;

This might be okay. But want to check what is
the practical upper limit for cgroups in a system
and whether we may miss some cgroups. If this
happens, it will be a surprise to the user.

Ok. What's the max number of items supported in a single session?

Quoted 23 lines
Quoted 23 lines
Quoted 22 lines
kernel/bpf/cgroup_iter.c new file +22 -0
+
+    ++*pos;
+    p->terminate = false;
+    if (p->order == BPF_ITER_CGROUP_PRE)
+        return css_next_descendant_pre(NULL, p->start_css);
+    else if (p->order == BPF_ITER_CGROUP_POST)
+        return css_next_descendant_post(NULL, p->start_css);
+    else /* BPF_ITER_CGROUP_PARENT_UP */
+        return p->start_css;
+}
+
+static int __cgroup_iter_seq_show(struct seq_file *seq,
+                  struct cgroup_subsys_state *css, int in_stop);
+
+static void cgroup_iter_seq_stop(struct seq_file *seq, void *v)
+{
+    /* pass NULL to the prog for post-processing */
+    if (!v)
+        __cgroup_iter_seq_show(seq, NULL, true);
+    mutex_unlock(&cgroup_mutex);
+}
+

[...]

#8 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 31 lines · Hao Luo
Quoted 4 lines · Yonghong Song
Quoted 2 lines · Yonghong Song

[...]

Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
include/uapi/linux/bpf.h +3 -0
+
   union bpf_iter_link_info {
       struct {
           __u32    map_fd;
       } map;
+
+    /* cgroup_iter walks either the live descendants of a cgroup

subtree, or the ancestors
+ * of a given cgroup.

Quoted 8 lines
Quoted 8 lines
Quoted 6 lines
include/uapi/linux/bpf.h +3 -0
+     */
+    struct {
+        /* Cgroup file descriptor. This is root of the subtree if for

walking the
+ * descendants; this is the starting cgroup if for walking
the ancestors.

Adding comment that cgroup_fd 0 means starting from root cgroup?

Sure.

Quoted 4 lines
Quoted 4 lines

Also, if I understand correctly, cgroup v1 is also supported here, right? If this is the case, for cgroup v1 which root cgroup will be used for cgroup_fd? It would be good to clarify here too.

Quoted 6 lines

IMO, the case of cgroup_fd = 0 combined with cgroup v1 should return errors. It's an invalid case. If anyone wants to use cgroup_iter on cgroup v1 hierarchy, they could explicitly open the subsystems' root directory and pass the fd. With that said, Yosry and I will test and confirm the behavior in this situation and clarify in the comment. Thanks for pointing this out.

sounds good.

Quoted 56 lines
Quoted 18 lines
Quoted 18 lines
Quoted 8 lines
include/uapi/linux/bpf.h +4 -0
+         */
+        __u32    cgroup_fd;
+        __u32    traversal_order;
+    } cgroup;
   };
   /* BPF syscall commands, see bpf(2) man-page for more details. */

include/uapi/linux/bpf.h struct bpf_link_info { · line 6157

Quoted 7 lines
include/uapi/linux/bpf.h +4 -0
@@ -6134,6 +6151,10 @@ struct bpf_link_info {
                   struct {
                       __u32 map_id;
                   } map;
+                struct {
+                    __u32 traversal_order;
+                    __aligned_u64 cgroup_id;
+                } cgroup;

We actually has a problem here although I don't have a solution yet.

[...]

Quoted 27 lines
Quoted 11 lines

There is a 4 byte hole after member 'target_name_len'. So map_id will have a offset 16 from the start of structure 'iter'.

This will break uapi. We probably won't be able to change the existing uapi with adding a ':32' after member 'target_name_len'. I don't have a good solution yet, but any suggestion is welcome.

Also, for '__aligned_u64 cgroup_id', '__u64 cgroup_id' is enough. '__aligned_u64' mostly used for pointers.

Briefly discussed with Alexei, the following structure iter definition should work. Later on, if we need to addition fields for other iter's, for a single __u32, the field can be added to either the first or the second union. If fields are more than __u32, they can be placed in the second union.

                  struct {
                          __aligned_u64 target_name; /* in/out:
target_name buffer ptr */
                          __u32 target_name_len;     /* in/out:
target_name buffer len */
                          union {
                                  struct {
                                          __u32 map_id;
                                  } map;
Quoted 9 lines
                          };
                          union {
                                  struct {
                                          __u64 cgroup_id;
                                          __u32 traversal_order;
                                  } cgroup;
                          };
                  } iter;
Quoted 4 lines

Thanks Yonghong for seeking the solution here. The solution looks good. I'm going to put your heads-up as comments there. One thing I'd like to confirm, when we query bpf_link_info for cgroup iter, do we also need to zero those fields for map_elem?

I think we don't need to do that. User space expected to check target_name/target_name_len/cgroup only. For cgroup_iter, the 'map' value should be ignored.

Quoted 25 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines



               };
           } iter;
           struct  {

[...]

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
kernel/bpf/cgroup_iter.c new file +8 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+    struct cgroup_iter_priv *p = seq->private;
+
+    mutex_lock(&cgroup_mutex);
+
+    /* support only one session */
Quoted 8 lines
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    if (*pos > 0)
+        return NULL;

This might be okay. But want to check what is
the practical upper limit for cgroups in a system
and whether we may miss some cgroups. If this
happens, it will be a surprise to the user.

Quoted 1 line

Ok. What's the max number of items supported in a single session?

The max number of items (cgroups) in a single session is determined
by kernel_buffer_size which equals to 8 * PAGE_SIZE. So it really
depends on how much data bpf program intends to send to user space.
If each bpf program run intends to send 64B to user space, e.g., for
cpu, memory, cpu pressure, mem pressure, io pressure, read rate, write rate, read/write rate. Then each session can support 512 cgroups.

Quoted 24 lines
Quoted 24 lines
Quoted 24 lines
Quoted 23 lines
kernel/bpf/cgroup_iter.c new file +22 -0
+
+    ++*pos;
+    p->terminate = false;
+    if (p->order == BPF_ITER_CGROUP_PRE)
+        return css_next_descendant_pre(NULL, p->start_css);
+    else if (p->order == BPF_ITER_CGROUP_POST)
+        return css_next_descendant_post(NULL, p->start_css);
+    else /* BPF_ITER_CGROUP_PARENT_UP */
+        return p->start_css;
+}
+
+static int __cgroup_iter_seq_show(struct seq_file *seq,
+                  struct cgroup_subsys_state *css, int in_stop);
+
+static void cgroup_iter_seq_stop(struct seq_file *seq, void *v)
+{
+    /* pass NULL to the prog for post-processing */
+    if (!v)
+        __cgroup_iter_seq_show(seq, NULL, true);
+    mutex_unlock(&cgroup_mutex);
+}
+

[...]

#9 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 2 lines · Yonghong Song

On 7/11/22 5:42 PM, Hao Luo wrote:

[...]

Quoted 17 lines
Quoted 17 lines
Quoted 16 lines
Quoted 16 lines

kernel/bpf/cgroup_iter.c line 51

Quoted 10 lines
kernel/bpf/cgroup_iter.c new file +10 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+    struct cgroup_iter_priv *p = seq->private;
+
+    mutex_lock(&cgroup_mutex);
+
+    /* support only one session */
+    if (*pos > 0)
+        return NULL;

This might be okay. But want to check what is the practical upper limit for cgroups in a system and whether we may miss some cgroups. If this happens, it will be a surprise to the user.

Quoted 9 lines
Quoted 1 line

Ok. What's the max number of items supported in a single session?

The max number of items (cgroups) in a single session is determined by kernel_buffer_size which equals to 8 * PAGE_SIZE. So it really depends on how much data bpf program intends to send to user space. If each bpf program run intends to send 64B to user space, e.g., for cpu, memory, cpu pressure, mem pressure, io pressure, read rate, write rate, read/write rate. Then each session can support 512 cgroups.

Hi Yonghong,

Sorry about the late reply. It's possible that the number of cgroup can be large, 1000+, in our production environment. But that may not be common. Would it be good to leave handling large number of cgroups as follow up for this patch? If it turns out to be a problem, to alleviate it, we could:

1. tell users to write program to skip a certain uninteresting cgroups.
2. support requesting large kernel_buffer_size for bpf_iter, maybe as a new bpf_iter flag.

Hao

Quoted 1 line
Quoted 1 line

[...]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

[...]

#10 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 39 lines · Hao Luo
Quoted 2 lines · Yonghong Song

On 7/11/22 5:42 PM, Hao Luo wrote:

[...]

Quoted 17 lines
Quoted 17 lines
Quoted 16 lines
Quoted 16 lines

kernel/bpf/cgroup_iter.c line 51

Quoted 10 lines
kernel/bpf/cgroup_iter.c new file +10 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+    struct cgroup_iter_priv *p = seq->private;
+
+    mutex_lock(&cgroup_mutex);
+
+    /* support only one session */
+    if (*pos > 0)
+        return NULL;

This might be okay. But want to check what is the practical upper limit for cgroups in a system and whether we may miss some cgroups. If this happens, it will be a surprise to the user.

Quoted 9 lines
Quoted 1 line

Ok. What's the max number of items supported in a single session?

The max number of items (cgroups) in a single session is determined by kernel_buffer_size which equals to 8 * PAGE_SIZE. So it really depends on how much data bpf program intends to send to user space. If each bpf program run intends to send 64B to user space, e.g., for cpu, memory, cpu pressure, mem pressure, io pressure, read rate, write rate, read/write rate. Then each session can support 512 cgroups.

Hi Yonghong,

Sorry about the late reply. It's possible that the number of cgroup can be large, 1000+, in our production environment. But that may not be common. Would it be good to leave handling large number of cgroups as follow up for this patch? If it turns out to be a problem, to alleviate it, we could:

Quoted 3 lines

1. tell users to write program to skip a certain uninteresting cgroups.
2. support requesting large kernel_buffer_size for bpf_iter, maybe as a new bpf_iter flag.

Currently if we intend to support multiple read() for cgroup_iter, the following is a very inefficient approach:

in seq_file private data structure, remember the last cgroup visited
and for the second read() syscall, do the traversal again (but not calling bpf program) until the last cgroup and proceed from there. This is inefficient and probably works. But if the last cgroup is
gone from the hierarchy, that the above approach won't work. One
possibility is to rememobe the last two cgroups. If the last cgroup
is gone, check the 'next' cgroup based on the one before the last
cgroup. If both are gone, we return NULL.

But in any case, if there are additional cgroups not visited, in the second read(), we should not return NULL which indicates done with all cgroups. We may return EOPNOTSUPP to indicate there are missing cgroups due to not supported.

Once users see EOPNOTSUPP which indicates there are missing cgroups, they can do more filtering in bpf program to avoid large data volume to user space.

To provide a way to truely visit *all* cgroups,
we can either use bpf_iter link_create->flags
to increase the buffer size as your suggested in the above so user can try to allocate more kernel buffer size. Or implement proper second read() traversal which I don't have a good idea how to do it efficiently.

Quoted 6 lines

Hao

Quoted 1 line
Quoted 1 line

[...]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

[...]

#11 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 50 lines · Yonghong Song
Quoted 39 lines · Hao Luo
Quoted 2 lines · Yonghong Song

On 7/11/22 5:42 PM, Hao Luo wrote:

[...]

Quoted 17 lines
Quoted 17 lines
Quoted 16 lines
Quoted 16 lines

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+    struct cgroup_iter_priv *p = seq->private;
+
+    mutex_lock(&cgroup_mutex);
+
+    /* support only one session */
+    if (*pos > 0)
+        return NULL;

This might be okay. But want to check what is the practical upper limit for cgroups in a system and whether we may miss some cgroups. If this happens, it will be a surprise to the user.

Quoted 9 lines
Quoted 1 line

Ok. What's the max number of items supported in a single session?

The max number of items (cgroups) in a single session is determined by kernel_buffer_size which equals to 8 * PAGE_SIZE. So it really depends on how much data bpf program intends to send to user space. If each bpf program run intends to send 64B to user space, e.g., for cpu, memory, cpu pressure, mem pressure, io pressure, read rate, write rate, read/write rate. Then each session can support 512 cgroups.

Hi Yonghong,

Sorry about the late reply. It's possible that the number of cgroup can be large, 1000+, in our production environment. But that may not be common. Would it be good to leave handling large number of cgroups as follow up for this patch? If it turns out to be a problem, to alleviate it, we could:

Quoted 3 lines

1. tell users to write program to skip a certain uninteresting cgroups.
2. support requesting large kernel_buffer_size for bpf_iter, maybe as a new bpf_iter flag.

Currently if we intend to support multiple read() for cgroup_iter, the following is a very inefficient approach:

Quoted 9 lines

in seq_file private data structure, remember the last cgroup visited and for the second read() syscall, do the traversal again (but not calling bpf program) until the last cgroup and proceed from there. This is inefficient and probably works. But if the last cgroup is gone from the hierarchy, that the above approach won't work. One possibility is to remember the last two cgroups. If the last cgroup is gone, check the 'next' cgroup based on the one before the last cgroup. If both are gone, we return NULL.

I suspect in reality, just remembering the last cgroup (or two cgroups) may not be sufficient. First, I don't want to hold cgroup_mutex across multiple sessions. I assume it's also not safe to release cgroup_mutex in the middle of walking cgroup hierarchy. Supporting multiple read() can be nasty for cgroup_iter.

Quoted 9 lines

But in any case, if there are additional cgroups not visited, in the second read(), we should not return NULL which indicates done with all cgroups. We may return EOPNOTSUPP to indicate there are missing cgroups due to not supported.

Once users see EOPNOTSUPP which indicates there are missing cgroups, they can do more filtering in bpf program to avoid large data volume to user space.

Makes sense. Yonghong, one question to confirm, if the first read() overflows, does the user still get partial data?

I'll change the return code to EOPNOTSUPP in v4 of this patchset.

Quoted 6 lines

To provide a way to truely visit *all* cgroups,
we can either use bpf_iter link_create->flags
to increase the buffer size as your suggested in the above so user can try to allocate more kernel buffer size. Or implement proper second read() traversal which I don't have a good idea how to do it efficiently.

I will try the buffer size increase first. Looks more doable. Do you mind putting this support as a follow-up?

Quoted 6 lines
Quoted 6 lines

Hao

Quoted 1 line
Quoted 1 line

[...]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

[...]

#12 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 61 lines · Hao Luo
Quoted 50 lines · Yonghong Song
Quoted 39 lines · Hao Luo
Quoted 2 lines · Yonghong Song

On 7/11/22 5:42 PM, Hao Luo wrote:

[...]

Quoted 17 lines
Quoted 17 lines
Quoted 16 lines
Quoted 16 lines

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+    struct cgroup_iter_priv *p = seq->private;
+
+    mutex_lock(&cgroup_mutex);
+
+    /* support only one session */
+    if (*pos > 0)
+        return NULL;

This might be okay. But want to check what is the practical upper limit for cgroups in a system and whether we may miss some cgroups. If this happens, it will be a surprise to the user.

Quoted 9 lines
Quoted 1 line

Ok. What's the max number of items supported in a single session?

The max number of items (cgroups) in a single session is determined by kernel_buffer_size which equals to 8 * PAGE_SIZE. So it really depends on how much data bpf program intends to send to user space. If each bpf program run intends to send 64B to user space, e.g., for cpu, memory, cpu pressure, mem pressure, io pressure, read rate, write rate, read/write rate. Then each session can support 512 cgroups.

Hi Yonghong,

Sorry about the late reply. It's possible that the number of cgroup can be large, 1000+, in our production environment. But that may not be common. Would it be good to leave handling large number of cgroups as follow up for this patch? If it turns out to be a problem, to alleviate it, we could:

Quoted 3 lines

1. tell users to write program to skip a certain uninteresting cgroups.
2. support requesting large kernel_buffer_size for bpf_iter, maybe as a new bpf_iter flag.

Currently if we intend to support multiple read() for cgroup_iter, the following is a very inefficient approach:

Quoted 9 lines

in seq_file private data structure, remember the last cgroup visited and for the second read() syscall, do the traversal again (but not calling bpf program) until the last cgroup and proceed from there. This is inefficient and probably works. But if the last cgroup is gone from the hierarchy, that the above approach won't work. One possibility is to remember the last two cgroups. If the last cgroup is gone, check the 'next' cgroup based on the one before the last cgroup. If both are gone, we return NULL.

Quoted 5 lines

I suspect in reality, just remembering the last cgroup (or two cgroups) may not be sufficient. First, I don't want to hold cgroup_mutex across multiple sessions. I assume it's also not safe to release cgroup_mutex in the middle of walking cgroup hierarchy. Supporting multiple read() can be nasty for cgroup_iter.

Right, holding cgroup_mutex across sessions is not bad idea and I didn't recommend it either.

I am aware of remembering last (one or two) cgroups are not 100% reliable. All other iters have similar issues w.r.t. across multiple sessions. But the idea is to find a *reasonable* start for the second and later session. For example, for task related iter, the previous session last tid can be remember and the next session starts with next tid after last tid based on idr. Some old processes might be gone, but we got a reasonable approximation. But cgroup is different, holding the cgroup pointer with an additional reference across sessions is not good. but holding cgroup
id requires to traverse the cgroup hierarchy
again and this is not efficient. Maybe other people has a better idea how to do this.

Quoted 6 lines
Quoted 6 lines

But in any case, if there are additional cgroups not visited, in the second read(), we should not return NULL which indicates done with all cgroups. We may return EOPNOTSUPP to indicate there are missing cgroups due to not supported.

Quoted 7 lines
Quoted 4 lines

Once users see EOPNOTSUPP which indicates there are missing cgroups, they can do more filtering in bpf program to avoid large data volume to user space.

Makes sense. Yonghong, one question to confirm, if the first read() overflows, does the user still get partial data?

Yes, the first read() and subsequent read()'s will be okay until user space receives all 8KB data where 8KB is the kernel buffer size. For example, if user provides 1KB buffer size, the first 8 read() syscalls will return proper data to user space.

After that, read() should return EOPNOTSUPP instead of return 0 where '0' indicates no more data.

Quoted 10 lines

I'll change the return code to EOPNOTSUPP in v4 of this patchset.

Quoted 6 lines

To provide a way to truely visit *all* cgroups,
we can either use bpf_iter link_create->flags
to increase the buffer size as your suggested in the above so user can try to allocate more kernel buffer size. Or implement proper second read() traversal which I don't have a good idea how to do it efficiently.

Quoted 2 lines

I will try the buffer size increase first. Looks more doable. Do you mind putting this support as a follow-up?

If we cannot finalize the solution to completely support arbitrary user output for cgroup_iter, we need to support EOPNOTSUPP so user knows it should adjust the bpf program to have less data to user space through seq_file. For example, they can put data into mmap-ed array map. Please explain such a limitation and how to workaround this in commit message clearly.

So yes, to support buffer size increase through link_create flags or to support a better way to start iteration after 8KB user data can be a followup.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

Hao

Quoted 1 line
Quoted 1 line

[...]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

[...]

#13 lore raw

Re: [PATCH bpf-next v3 4/8] bpf: Introduce cgroup iter

Quoted 74 lines · Yonghong Song
Quoted 61 lines · Hao Luo
Quoted 50 lines · Yonghong Song
Quoted 39 lines · Hao Luo
Quoted 2 lines · Yonghong Song

On 7/11/22 5:42 PM, Hao Luo wrote:

[...]

Quoted 17 lines
Quoted 17 lines
Quoted 16 lines
Quoted 16 lines

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+static void *cgroup_iter_seq_start(struct seq_file *seq, loff_t *pos)
+{
+    struct cgroup_iter_priv *p = seq->private;
+
+    mutex_lock(&cgroup_mutex);
+
+    /* support only one session */
+    if (*pos > 0)
+        return NULL;

This might be okay. But want to check what is the practical upper limit for cgroups in a system and whether we may miss some cgroups. If this happens, it will be a surprise to the user.

Quoted 9 lines
Quoted 1 line

Ok. What's the max number of items supported in a single session?

The max number of items (cgroups) in a single session is determined by kernel_buffer_size which equals to 8 * PAGE_SIZE. So it really depends on how much data bpf program intends to send to user space. If each bpf program run intends to send 64B to user space, e.g., for cpu, memory, cpu pressure, mem pressure, io pressure, read rate, write rate, read/write rate. Then each session can support 512 cgroups.

Hi Yonghong,

Sorry about the late reply. It's possible that the number of cgroup can be large, 1000+, in our production environment. But that may not be common. Would it be good to leave handling large number of cgroups as follow up for this patch? If it turns out to be a problem, to alleviate it, we could:

Quoted 3 lines

1. tell users to write program to skip a certain uninteresting cgroups.
2. support requesting large kernel_buffer_size for bpf_iter, maybe as a new bpf_iter flag.

Currently if we intend to support multiple read() for cgroup_iter, the following is a very inefficient approach:

Quoted 9 lines

in seq_file private data structure, remember the last cgroup visited and for the second read() syscall, do the traversal again (but not calling bpf program) until the last cgroup and proceed from there. This is inefficient and probably works. But if the last cgroup is gone from the hierarchy, that the above approach won't work. One possibility is to remember the last two cgroups. If the last cgroup is gone, check the 'next' cgroup based on the one before the last cgroup. If both are gone, we return NULL.

Quoted 5 lines

I suspect in reality, just remembering the last cgroup (or two cgroups) may not be sufficient. First, I don't want to hold cgroup_mutex across multiple sessions. I assume it's also not safe to release cgroup_mutex in the middle of walking cgroup hierarchy. Supporting multiple read() can be nasty for cgroup_iter.

Right, holding cgroup_mutex across sessions is not bad idea and I didn't recommend it either.

Quoted 15 lines

I am aware of remembering last (one or two) cgroups are not 100% reliable. All other iters have similar issues w.r.t. across multiple sessions. But the idea is to find a *reasonable* start for the second and later session. For example, for task related iter, the previous session last tid can be remember and the next session starts with next tid after last tid based on idr. Some old processes might be gone, but we got a reasonable approximation. But cgroup is different, holding the cgroup pointer with an additional reference across sessions is not good. but holding cgroup
id requires to traverse the cgroup hierarchy
again and this is not efficient. Maybe other people has a better idea how to do this.

Makes sense.

Quoted 20 lines
Quoted 6 lines
Quoted 6 lines

But in any case, if there are additional cgroups not visited, in the second read(), we should not return NULL which indicates done with all cgroups. We may return EOPNOTSUPP to indicate there are missing cgroups due to not supported.

Quoted 7 lines
Quoted 4 lines

Once users see EOPNOTSUPP which indicates there are missing cgroups, they can do more filtering in bpf program to avoid large data volume to user space.

Makes sense. Yonghong, one question to confirm, if the first read() overflows, does the user still get partial data?

Yes, the first read() and subsequent read()'s will be okay until user space receives all 8KB data where 8KB is the kernel buffer size. For example, if user provides 1KB buffer size, the first 8 read() syscalls will return proper data to user space.

Quoted 4 lines

After that, read() should return EOPNOTSUPP instead of return 0 where '0' indicates no more data.

Sounds good. Will do that.

Quoted 14 lines
Quoted 11 lines

I'll change the return code to EOPNOTSUPP in v4 of this patchset.

Quoted 6 lines

To provide a way to truely visit *all* cgroups,
we can either use bpf_iter link_create->flags
to increase the buffer size as your suggested in the above so user can try to allocate more kernel buffer size. Or implement proper second read() traversal which I don't have a good idea how to do it efficiently.

Quoted 2 lines

I will try the buffer size increase first. Looks more doable. Do you mind putting this support as a follow-up?

Quoted 8 lines

If we cannot finalize the solution to completely support arbitrary user output for cgroup_iter, we need to support EOPNOTSUPP so user knows it should adjust the bpf program to have less data to user space through seq_file. For example, they can put data into mmap-ed array map. Please explain such a limitation and how to workaround this in commit message clearly.

Acknowledged. I will put a comment in the code and also explain in the commit message. Thanks!

Quoted 11 lines

So yes, to support buffer size increase through link_create flags or to support a better way to start iteration after 8KB user data can be a followup.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

Hao

Quoted 1 line
Quoted 1 line

[...]

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

[...]

#14 lore raw

PATCH v3 5/8 selftests/bpf: Test cgroup_iter.

In reply to Yosry Ahmed

From: Hao Luo <[email protected]>

Add a selftest for cgroup_iter. The selftest creates a mini cgroup tree of the following structure:

ROOT (working cgroup)
|
PARENT
/ \
CHILD1 CHILD2

and tests the following scenarios:

- invalid cgroup fd.
- pre-order walk over descendants from PARENT.
- post-order walk over descendants from PARENT.
- walk of ancestors from PARENT.
- early termination.

---
 .../selftests/bpf/prog_tests/cgroup_iter.c    | 190 ++++++++++++++++++
 tools/testing/selftests/bpf/progs/bpf_iter.h  |   7 +
 .../testing/selftests/bpf/progs/cgroup_iter.c |  39 ++++
 3 files changed, 236 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/cgroup_iter.c
 create mode 100644 tools/testing/selftests/bpf/progs/cgroup_iter.c
tools/testing/selftests/bpf/prog_tests/cgroup_iter.c new file +190 -0
new file mode 100644
index 0000000000000..4c8f11f784915
@@ -0,0 +1,190 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2022 Google */
+
+#include <test_progs.h>
+#include <bpf/libbpf.h>
+#include <bpf/btf.h>
+#include "cgroup_iter.skel.h"
+#include "cgroup_helpers.h"
+
+#define ROOT		0
+#define PARENT		1
+#define CHILD1		2
+#define CHILD2		3
+#define NUM_CGROUPS	4
+
+#define PROLOGUE	"prologue\n"
+#define EPILOGUE	"epilogue\n"
+
+#define format_expected_output1(cg_id1) \
+	snprintf(expected_output, sizeof(expected_output), \
+		 PROLOGUE "%8llu\n" EPILOGUE, (cg_id1))
+
+#define format_expected_output2(cg_id1, cg_id2) \
+	snprintf(expected_output, sizeof(expected_output), \
+		 PROLOGUE "%8llu\n%8llu\n" EPILOGUE, \
+		 (cg_id1), (cg_id2))
+
+#define format_expected_output3(cg_id1, cg_id2, cg_id3) \
+	snprintf(expected_output, sizeof(expected_output), \
+		 PROLOGUE "%8llu\n%8llu\n%8llu\n" EPILOGUE, \
+		 (cg_id1), (cg_id2), (cg_id3))
+
+const char *cg_path[] = {
+	"/", "/parent", "/parent/child1", "/parent/child2"
+};
+
+static int cg_fd[] = {-1, -1, -1, -1};
+static unsigned long long cg_id[] = {0, 0, 0, 0};
+static char expected_output[64];
+
+int setup_cgroups(void)
+{
+	int fd, i = 0;
+
+	for (i = 0; i < NUM_CGROUPS; i++) {
+		fd = create_and_get_cgroup(cg_path[i]);
+		if (fd < 0)
+			return fd;
+
+		cg_fd[i] = fd;
+		cg_id[i] = get_cgroup_id(cg_path[i]);
+	}
+	return 0;
+}
+
+void cleanup_cgroups(void)
+{
+	int i;
+
+	for (i = 0; i < NUM_CGROUPS; i++)
+		close(cg_fd[i]);
+}
+
+static void read_from_cgroup_iter(struct bpf_program *prog, int cgroup_fd,
+				  int order, const char *testname)
+{
+	DECLARE_LIBBPF_OPTS(bpf_iter_attach_opts, opts);
+	union bpf_iter_link_info linfo;
+	struct bpf_link *link;
+	int len, iter_fd;
+	static char buf[64];
+
+	memset(&linfo, 0, sizeof(linfo));
+	linfo.cgroup.cgroup_fd = cgroup_fd;
+	linfo.cgroup.traversal_order = order;
+	opts.link_info = &linfo;
+	opts.link_info_len = sizeof(linfo);
+
+	link = bpf_program__attach_iter(prog, &opts);
+	if (!ASSERT_OK_PTR(link, "attach_iter"))
+		return;
+
+	iter_fd = bpf_iter_create(bpf_link__fd(link));
+	if (iter_fd < 0)
+		goto free_link;
+
+	memset(buf, 0, sizeof(buf));
+	while ((len = read(iter_fd, buf, sizeof(buf))) > 0)
+		;
+
+	ASSERT_STREQ(buf, expected_output, testname);
+
+	close(iter_fd);
+free_link:
+	bpf_link__destroy(link);
+}
+
+/* Invalid cgroup. */
+static void test_invalid_cgroup(struct cgroup_iter *skel)
+{
+
+	DECLARE_LIBBPF_OPTS(bpf_iter_attach_opts, opts);
+	union bpf_iter_link_info linfo;
+	struct bpf_link *link;
+
+	memset(&linfo, 0, sizeof(linfo));
+	linfo.cgroup.cgroup_fd = (__u32)-1;
+	opts.link_info = &linfo;
+	opts.link_info_len = sizeof(linfo);
+
+	link = bpf_program__attach_iter(skel->progs.cgroup_id_printer, &opts);
+	if (!ASSERT_ERR_PTR(link, "attach_iter"))
+		bpf_link__destroy(link);
+}
+
+/* Preorder walk prints parent and child in order. */
+static void test_walk_preorder(struct cgroup_iter *skel)
+{
+	format_expected_output3(cg_id[PARENT], cg_id[CHILD1], cg_id[CHILD2]);
+
+	read_from_cgroup_iter(skel->progs.cgroup_id_printer, cg_fd[PARENT],
+			      BPF_ITER_CGROUP_PRE, "preorder");
+}
+
+/* Postorder walk prints child and parent in order. */
+static void test_walk_postorder(struct cgroup_iter *skel)
+{
+	format_expected_output3(cg_id[CHILD1], cg_id[CHILD2], cg_id[PARENT]);
+
+	read_from_cgroup_iter(skel->progs.cgroup_id_printer, cg_fd[PARENT],
+			      BPF_ITER_CGROUP_POST, "postorder");
+}
+
+/* Walking parents prints parent and then root. */
+static void test_walk_parent_up(struct cgroup_iter *skel)
+{
+	/* terminate the walk when ROOT is met. */
+	skel->bss->terminal_cgroup = cg_id[ROOT];
+
+	format_expected_output2(cg_id[PARENT], cg_id[ROOT]);
+
+	read_from_cgroup_iter(skel->progs.cgroup_id_printer, cg_fd[PARENT],
+			      BPF_ITER_CGROUP_PARENT_UP, "parent_up");
+
+	skel->bss->terminal_cgroup = 0;
+}
+
+/* Early termination prints parent only. */
+static void test_early_termination(struct cgroup_iter *skel)
+{
+	/* terminate the walk after the first element is processed. */
+	skel->bss->terminate_early = 1;
+
+	format_expected_output1(cg_id[PARENT]);
+
+	read_from_cgroup_iter(skel->progs.cgroup_id_printer, cg_fd[PARENT],
+			      BPF_ITER_CGROUP_PRE, "early_termination");
+
+	skel->bss->terminate_early = 0;
+}
+
+void test_cgroup_iter(void)
+{
+	struct cgroup_iter *skel = NULL;
+
+	if (setup_cgroup_environment() < 0)
+		return;
+
+	if (setup_cgroups() < 0)
+		goto out;
+
+	skel = cgroup_iter__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "cgroup_iter__open_and_load"))
+		goto out;
+
+	if (test__start_subtest("cgroup_iter__invalid_cgroup"))
+		test_invalid_cgroup(skel);
+	if (test__start_subtest("cgroup_iter__preorder"))
+		test_walk_preorder(skel);
+	if (test__start_subtest("cgroup_iter__postorder"))
+		test_walk_postorder(skel);
+	if (test__start_subtest("cgroup_iter__parent_up_walk"))
+		test_walk_parent_up(skel);
+	if (test__start_subtest("cgroup_iter__early_termination"))
+		test_early_termination(skel);
+out:
+	cgroup_iter__destroy(skel);
+	cleanup_cgroups();
+	cleanup_cgroup_environment();
+}
tools/testing/selftests/bpf/progs/bpf_iter.h +7 -0
index 97ec8bc76ae62..bfcb0e0e3b1aa 100644
@@ -17,6 +17,7 @@
 #define bpf_iter__bpf_sk_storage_map bpf_iter__bpf_sk_storage_map___not_used
 #define bpf_iter__sockmap bpf_iter__sockmap___not_used
 #define bpf_iter__bpf_link bpf_iter__bpf_link___not_used
+#define bpf_iter__cgroup bpf_iter__cgroup___not_used
 #define btf_ptr btf_ptr___not_used
 #define BTF_F_COMPACT BTF_F_COMPACT___not_used
 #define BTF_F_NONAME BTF_F_NONAME___not_used
@@ -39,6 +40,7 @@
 #undef bpf_iter__bpf_sk_storage_map
 #undef bpf_iter__sockmap
 #undef bpf_iter__bpf_link
+#undef bpf_iter__cgroup
 #undef btf_ptr
 #undef BTF_F_COMPACT
 #undef BTF_F_NONAME
@@ -139,6 +141,11 @@ struct bpf_iter__bpf_link {
 	struct bpf_link *link;
 };
 
+struct bpf_iter__cgroup {
+	struct bpf_iter_meta *meta;
+	struct cgroup *cgroup;
+} __attribute__((preserve_access_index));
+
 struct btf_ptr {
 	void *ptr;
 	__u32 type_id;
tools/testing/selftests/bpf/progs/cgroup_iter.c new file +39 -0
new file mode 100644
index 0000000000000..2a34d146d6df0
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2022 Google */
+
+#include "bpf_iter.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+char _license[] SEC("license") = "GPL";
+volatile int terminate_early = 0;
+volatile u64 terminal_cgroup = 0;
+
+static inline u64 cgroup_id(struct cgroup *cgrp)
+{
+	return cgrp->kn->id;
+}
+
+SEC("iter/cgroup")
+int cgroup_id_printer(struct bpf_iter__cgroup *ctx)
+{
+	struct seq_file *seq = ctx->meta->seq;
+	struct cgroup *cgrp = ctx->cgroup;
+
+	/* epilogue */
+	if (cgrp == NULL) {
+		BPF_SEQ_PRINTF(seq, "epilogue\n");
+		return 0;
+	}
+
+	/* prologue */
+	if (ctx->meta->seq_num == 0)
+		BPF_SEQ_PRINTF(seq, "prologue\n");
+
+	BPF_SEQ_PRINTF(seq, "%8llu\n", cgroup_id(cgrp));
+
+	if (terminal_cgroup == cgroup_id(cgrp))
+		return 1;
+
+	return terminate_early ? 1 : 0;
+}
Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#15 lore raw

PATCH v3 6/8 cgroup: bpf: enable bpf programs to integrate with rstat

In reply to Yosry Ahmed

Enable bpf programs to make use of rstat to collect cgroup hierarchical stats efficiently:
- Add cgroup_rstat_updated() kfunc, for bpf progs that collect stats.
- Add cgroup_rstat_flush() kfunc, for bpf progs that read stats.
- Add an empty bpf_rstat_flush() hook that is called during rstat flushing, for bpf progs that flush stats to attach to. Attaching a bpf prog to this hook effectively registers it as a flush callback.

---
 kernel/cgroup/rstat.c | 54 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 54 insertions(+)
kernel/cgroup/rstat.c +54 -0
index 24b5c2ab55983..0f87c31eecc27 100644
@@ -3,6 +3,11 @@
 
 #include <linux/sched/cputime.h>
 
+#include <linux/bpf.h>
+#include <linux/btf.h>
+#include <linux/btf_ids.h>
+
+
 static DEFINE_SPINLOCK(cgroup_rstat_lock);
 static DEFINE_PER_CPU(raw_spinlock_t, cgroup_rstat_cpu_lock);
 
@@ -141,6 +146,31 @@ static struct cgroup *cgroup_rstat_cpu_pop_updated(struct cgroup *pos,
 	return pos;
 }
 
+/*
+ * A hook for bpf stat collectors to attach to and flush their stats.
+ * Together with providing bpf kfuncs for cgroup_rstat_updated() and
+ * cgroup_rstat_flush(), this enables a complete workflow where bpf progs that
+ * collect cgroup stats can integrate with rstat for efficient flushing.
+ *
+ * A static noinline declaration here could cause the compiler to optimize away
+ * the function. A global noinline declaration will keep the definition, but may
+ * optimize away the callsite. Therefore, __weak is needed to ensure that the
+ * call is still emitted, by telling the compiler that we don't know what the
+ * function might eventually be.
+ *
+ * __diag_* below are needed to dismiss the missing prototype warning.
+ */
+__diag_push();
+__diag_ignore_all("-Wmissing-prototypes",
+		  "kfuncs which will be used in BPF programs");
+
+__weak noinline void bpf_rstat_flush(struct cgroup *cgrp,
+				     struct cgroup *parent, int cpu)
+{
+}
+
+__diag_pop();
+
 /* see cgroup_rstat_flush() */
 static void cgroup_rstat_flush_locked(struct cgroup *cgrp, bool may_sleep)
 	__releases(&cgroup_rstat_lock) __acquires(&cgroup_rstat_lock)
@@ -168,6 +198,7 @@ static void cgroup_rstat_flush_locked(struct cgroup *cgrp, bool may_sleep)
 			struct cgroup_subsys_state *css;
 
 			cgroup_base_stat_flush(pos, cpu);
+			bpf_rstat_flush(pos, cgroup_parent(pos), cpu);
 
 			rcu_read_lock();
 			list_for_each_entry_rcu(css, &pos->rstat_css_list,
@@ -469,3 +500,26 @@ void cgroup_base_stat_cputime_show(struct seq_file *seq)
 		   "system_usec %llu\n",
 		   usage, utime, stime);
 }
+
+/* Add bpf kfuncs for cgroup_rstat_updated() and cgroup_rstat_flush() */
+BTF_SET_START(bpf_rstat_check_kfunc_ids)
+BTF_ID(func, cgroup_rstat_updated)
+BTF_ID(func, cgroup_rstat_flush)
+BTF_SET_END(bpf_rstat_check_kfunc_ids)
+
+BTF_SET_START(bpf_rstat_sleepable_kfunc_ids)
+BTF_ID(func, cgroup_rstat_flush)
+BTF_SET_END(bpf_rstat_sleepable_kfunc_ids)
+
+static const struct btf_kfunc_id_set bpf_rstat_kfunc_set = {
+	.owner		= THIS_MODULE,
+	.check_set	= &bpf_rstat_check_kfunc_ids,
+	.sleepable_set	= &bpf_rstat_sleepable_kfunc_ids,
+};
+
+static int __init bpf_rstat_kfunc_init(void)
+{
+	return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
+					 &bpf_rstat_kfunc_set);
+}
+late_initcall(bpf_rstat_kfunc_init);
Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#16 lore raw

PATCH v3 7/8 selftests/bpf: extend cgroup helpers

In reply to Yosry Ahmed

This patch extends bpf selftests cgroup helpers in various ways:
- Add enable_controllers() that allows tests to enable all or a subset of controllers for a specific cgroup.
- Add join_cgroup_parent(). The cgroup workdir is based on the pid, therefore a spawned child cannot join the same cgroup hierarchy of the test through join_cgroup(). join_cgroup_parent() is used in child processes to join a cgroup under the parent's workdir.
- Add write_cgroup_file() and write_cgroup_file_parent() (similar to join_cgroup_parent() above).
- Add get_root_cgroup() for tests that need to do checks on root cgroup.
- Distinguish relative and absolute cgroup paths in function arguments. Now relative paths are called relative_path, and absolute paths are called cgroup_path.

---
 tools/testing/selftests/bpf/cgroup_helpers.c | 201 +++++++++++++++----
 tools/testing/selftests/bpf/cgroup_helpers.h |  19 +-
 2 files changed, 173 insertions(+), 47 deletions(-)
tools/testing/selftests/bpf/cgroup_helpers.c +160 -41
index 9d59c3990ca8d..f06a5a255e195 100644
@@ -33,49 +33,51 @@
 #define CGROUP_MOUNT_DFLT		"/sys/fs/cgroup"
 #define NETCLS_MOUNT_PATH		CGROUP_MOUNT_DFLT "/net_cls"
 #define CGROUP_WORK_DIR			"/cgroup-test-work-dir"
-#define format_cgroup_path(buf, path) \
+
+#define format_cgroup_path_pid(buf, path, pid) \
 	snprintf(buf, sizeof(buf), "%s%s%d%s", CGROUP_MOUNT_PATH, \
-	CGROUP_WORK_DIR, getpid(), path)
+	CGROUP_WORK_DIR, pid, path)
+
+#define format_cgroup_path(buf, path) \
+	format_cgroup_path_pid(buf, path, getpid())
+
+#define format_parent_cgroup_path(buf, path) \
+	format_cgroup_path_pid(buf, path, getppid())
 
 #define format_classid_path(buf)				\
 	snprintf(buf, sizeof(buf), "%s%s", NETCLS_MOUNT_PATH,	\
 		 CGROUP_WORK_DIR)
 
-/**
- * enable_all_controllers() - Enable all available cgroup v2 controllers
- *
- * Enable all available cgroup v2 controllers in order to increase
- * the code coverage.
- *
- * If successful, 0 is returned.
- */
-static int enable_all_controllers(char *cgroup_path)
+
+static int __enable_controllers(const char *cgroup_path, const char *controllers)
 {
 	char path[PATH_MAX + 1];
-	char buf[PATH_MAX];
+	char enable[PATH_MAX + 1];
 	char *c, *c2;
 	int fd, cfd;
 	ssize_t len;
 
-	snprintf(path, sizeof(path), "%s/cgroup.controllers", cgroup_path);
-	fd = open(path, O_RDONLY);
-	if (fd < 0) {
-		log_err("Opening cgroup.controllers: %s", path);
-		return 1;
-	}
+	/* If not controllers are passed, enable all available controllers */
+	if (!controllers) {
+		snprintf(path, sizeof(path), "%s/cgroup.controllers",
+			 cgroup_path);
+		fd = open(path, O_RDONLY);
+		if (fd < 0) {
+			log_err("Opening cgroup.controllers: %s", path);
+			return 1;
+		}
 
-	len = read(fd, buf, sizeof(buf) - 1);
-	if (len < 0) {
+		len = read(fd, enable, sizeof(enable) - 1);
+		if (len < 0) {
+			close(fd);
+			log_err("Reading cgroup.controllers: %s", path);
+			return 1;
+		} else if (len == 0) /* No controllers to enable */
+			return 0;
+		enable[len] = 0;
 		close(fd);
-		log_err("Reading cgroup.controllers: %s", path);
-		return 1;
-	}
-	buf[len] = 0;
-	close(fd);
-
-	/* No controllers available? We're probably on cgroup v1. */
-	if (len == 0)
-		return 0;
+	} else
+		strncpy(enable, controllers, sizeof(enable));
 
 	snprintf(path, sizeof(path), "%s/cgroup.subtree_control", cgroup_path);
 	cfd = open(path, O_RDWR);
@@ -84,7 +86,7 @@ static int enable_all_controllers(char *cgroup_path)
 		return 1;
 	}
 
-	for (c = strtok_r(buf, " ", &c2); c; c = strtok_r(NULL, " ", &c2)) {
+	for (c = strtok_r(enable, " ", &c2); c; c = strtok_r(NULL, " ", &c2)) {
 		if (dprintf(cfd, "+%s\n", c) <= 0) {
 			log_err("Enabling controller %s: %s", c, path);
 			close(cfd);
@@ -95,6 +97,87 @@ static int enable_all_controllers(char *cgroup_path)
 	return 0;
 }
 
+/**
+ * enable_controllers() - Enable cgroup v2 controllers
+ * @relative_path: The cgroup path, relative to the workdir
+ * @controllers: List of controllers to enable in cgroup.controllers format
+ *
+ *
+ * Enable given cgroup v2 controllers, if @controllers is NULL, enable all
+ * available controllers.
+ *
+ * If successful, 0 is returned.
+ */
+int enable_controllers(const char *relative_path, const char *controllers)
+{
+	char cgroup_path[PATH_MAX + 1];
+
+	format_cgroup_path(cgroup_path, relative_path);
+	return __enable_controllers(cgroup_path, controllers);
+}
+
+static int __write_cgroup_file(const char *cgroup_path, const char *file,
+			       const char *buf)
+{
+	char file_path[PATH_MAX + 1];
+	int fd;
+
+	snprintf(file_path, sizeof(file_path), "%s/%s", cgroup_path, file);
+	fd = open(file_path, O_RDWR);
+	if (fd < 0) {
+		log_err("Opening %s", file_path);
+		return 1;
+	}
+
+	if (dprintf(fd, "%s", buf) <= 0) {
+		log_err("Writing to %s", file_path);
+		close(fd);
+		return 1;
+	}
+	close(fd);
+	return 0;
+}
+
+/**
+ * write_cgroup_file() - Write to a cgroup file
+ * @relative_path: The cgroup path, relative to the workdir
+ * @file: The name of the file in cgroupfs to write to
+ * @buf: Buffer to write to the file
+ *
+ * Write to a file in the given cgroup's directory.
+ *
+ * If successful, 0 is returned.
+ */
+int write_cgroup_file(const char *relative_path, const char *file,
+		      const char *buf)
+{
+	char cgroup_path[PATH_MAX - 24];
+
+	format_cgroup_path(cgroup_path, relative_path);
+	return __write_cgroup_file(cgroup_path, file, buf);
+}
+
+/**
+ * write_cgroup_file_parent() - Write to a cgroup file in the parent process
+ *                              workdir
+ * @relative_path: The cgroup path, relative to the parent process workdir
+ * @file: The name of the file in cgroupfs to write to
+ * @buf: Buffer to write to the file
+ *
+ * Write to a file in the given cgroup's directory under the parent process
+ * workdir.
+ *
+ * If successful, 0 is returned.
+ */
+int write_cgroup_file_parent(const char *relative_path, const char *file,
+			     const char *buf)
+{
+	char cgroup_path[PATH_MAX - 24];
+
+	format_parent_cgroup_path(cgroup_path, relative_path);
+	return __write_cgroup_file(cgroup_path, file, buf);
+}
+
 /**
  * setup_cgroup_environment() - Setup the cgroup environment
  *
@@ -133,7 +216,9 @@ int setup_cgroup_environment(void)
 		return 1;
 	}
 
-	if (enable_all_controllers(cgroup_workdir))
+	/* Enable all available controllers to increase test coverage */
+	if (__enable_controllers(CGROUP_MOUNT_PATH, NULL) ||
+	    __enable_controllers(cgroup_workdir, NULL))
 		return 1;
 
 	return 0;
@@ -173,7 +258,7 @@ static int join_cgroup_from_top(const char *cgroup_path)
 
 /**
  * join_cgroup() - Join a cgroup
- * @path: The cgroup path, relative to the workdir, to join
+ * @relative_path: The cgroup path, relative to the workdir, to join
  *
  * This function expects a cgroup to already be created, relative to the cgroup
  * work dir, and it joins it. For example, passing "/my-cgroup" as the path
@@ -182,11 +267,27 @@ static int join_cgroup_from_top(const char *cgroup_path)
  *
  * On success, it returns 0, otherwise on failure it returns 1.
  */
-int join_cgroup(const char *path)
+int join_cgroup(const char *relative_path)
+{
+	char cgroup_path[PATH_MAX + 1];
+
+	format_cgroup_path(cgroup_path, relative_path);
+	return join_cgroup_from_top(cgroup_path);
+}
+
+/**
+ * join_parent_cgroup() - Join a cgroup in the parent process workdir
+ * @relative_path: The cgroup path, relative to parent process workdir, to join
+ *
+ * See join_cgroup().
+ *
+ * On success, it returns 0, otherwise on failure it returns 1.
+ */
+int join_parent_cgroup(const char *relative_path)
 {
 	char cgroup_path[PATH_MAX + 1];
 
-	format_cgroup_path(cgroup_path, path);
+	format_parent_cgroup_path(cgroup_path, relative_path);
 	return join_cgroup_from_top(cgroup_path);
 }
 
@@ -212,9 +313,27 @@ void cleanup_cgroup_environment(void)
 	nftw(cgroup_workdir, nftwfunc, WALK_FD_LIMIT, FTW_DEPTH | FTW_MOUNT);
 }
 
+/**
+ * get_root_cgroup() - Get the FD of the root cgroup
+ *
+ * On success, it returns the file descriptor. On failure, it returns -1.
+ * If there is a failure, it prints the error to stderr.
+ */
+int get_root_cgroup(void)
+{
+	int fd;
+
+	fd = open(CGROUP_MOUNT_PATH, O_RDONLY);
+	if (fd < 0) {
+		log_err("Opening root cgroup");
+		return -1;
+	}
+	return fd;
+}
+
 /**
  * create_and_get_cgroup() - Create a cgroup, relative to workdir, and get the FD
- * @path: The cgroup path, relative to the workdir, to join
+ * @relative_path: The cgroup path, relative to the workdir, to join
  *
  * This function creates a cgroup under the top level workdir and returns the
  * file descriptor. It is idempotent.
@@ -222,14 +341,14 @@ void cleanup_cgroup_environment(void)
  * On success, it returns the file descriptor. On failure it returns -1.
  * If there is a failure, it prints the error to stderr.
  */
-int create_and_get_cgroup(const char *path)
+int create_and_get_cgroup(const char *relative_path)
 {
 	char cgroup_path[PATH_MAX + 1];
 	int fd;
 
-	format_cgroup_path(cgroup_path, path);
+	format_cgroup_path(cgroup_path, relative_path);
 	if (mkdir(cgroup_path, 0777) && errno != EEXIST) {
-		log_err("mkdiring cgroup %s .. %s", path, cgroup_path);
+		log_err("mkdiring cgroup %s .. %s", relative_path, cgroup_path);
 		return -1;
 	}
 
@@ -244,13 +363,13 @@ int create_and_get_cgroup(const char *path)
 
 /**
  * get_cgroup_id() - Get cgroup id for a particular cgroup path
- * @path: The cgroup path, relative to the workdir, to join
+ * @relative_path: The cgroup path, relative to the workdir, to join
  *
  * On success, it returns the cgroup id. On failure it returns 0,
  * which is an invalid cgroup id.
  * If there is a failure, it prints the error to stderr.
  */
-unsigned long long get_cgroup_id(const char *path)
+unsigned long long get_cgroup_id(const char *relative_path)
 {
 	int dirfd, err, flags, mount_id, fhsize;
 	union {
@@ -261,7 +380,7 @@ unsigned long long get_cgroup_id(const char *path)
 	struct file_handle *fhp, *fhp2;
 	unsigned long long ret = 0;
 
-	format_cgroup_path(cgroup_workdir, path);
+	format_cgroup_path(cgroup_workdir, relative_path);
 
 	dirfd = AT_FDCWD;
 	flags = 0;
tools/testing/selftests/bpf/cgroup_helpers.h +13 -6
index fcc9cb91b2111..3358734356ab7 100644
@@ -10,11 +10,18 @@
 	__FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
 
 /* cgroupv2 related */
-int cgroup_setup_and_join(const char *path);
-int create_and_get_cgroup(const char *path);
-unsigned long long get_cgroup_id(const char *path);
-
-int join_cgroup(const char *path);
+int enable_controllers(const char *relative_path, const char *controllers);
+int write_cgroup_file(const char *relative_path, const char *file,
+		      const char *buf);
+int write_cgroup_file_parent(const char *relative_path, const char *file,
+			     const char *buf);
+int cgroup_setup_and_join(const char *relative_path);
+int get_root_cgroup(void);
+int create_and_get_cgroup(const char *relative_path);
+unsigned long long get_cgroup_id(const char *relative_path);
+
+int join_cgroup(const char *relative_path);
+int join_parent_cgroup(const char *relative_path);
 
 int setup_cgroup_environment(void);
 void cleanup_cgroup_environment(void);
@@ -26,4 +33,4 @@ int join_classid(void);
 int setup_classid_environment(void);
 void cleanup_classid_environment(void);
 
-#endif /* __CGROUP_HELPERS_H */
\ No newline at end of file
+#endif /* __CGROUP_HELPERS_H */
Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#17 lore raw

PATCH v3 8/8 bpf: add a selftest for cgroup hierarchical stats collection

In reply to Yosry Ahmed

Add a selftest that tests the whole workflow for collecting, aggregating (flushing), and displaying cgroup hierarchical stats.

TL;DR:
- Userspace program creates a cgroup hierarchy and induces memcg reclaim in parts of it.
- Whenever reclaim happens, vmscan_start and vmscan_end update per-cgroup percpu readings, and tell rstat which (cgroup, cpu) pairs have updates.
- When userspace tries to read the stats, vmscan_dump calls rstat to flush the stats, and outputs the stats in text format to userspace (similar to cgroupfs stats).
- rstat calls vmscan_flush once for every (cgroup, cpu) pair that has updates, vmscan_flush aggregates cpu readings and propagates updates to parents.
- Userspace program makes sure the stats are aggregated and read correctly.

Detailed explanation:
- The test loads tracing bpf programs, vmscan_start and vmscan_end, to measure the latency of cgroup reclaim. Per-cgroup readings are stored in percpu maps for efficiency. When a cgroup reading is updated on a cpu, cgroup_rstat_updated(cgroup, cpu) is called to add the cgroup to the rstat updated tree on that cpu.

- A cgroup_iter program, vmscan_dump, is loaded and pinned to a file, for each cgroup. Reading this file invokes the program, which calls cgroup_rstat_flush(cgroup) to ask rstat to propagate the updates for all cpus and cgroups that have updates in this cgroup's subtree. Afterwards, the stats are exposed to the user. vmscan_dump returns 1 to terminate iteration early, so that we only expose stats for one cgroup per read.

- An ftrace program, vmscan_flush, is also loaded and attached to bpf_rstat_flush. When rstat flushing is ongoing, vmscan_flush is invoked once for each (cgroup, cpu) pair that has updates. cgroups are popped from the rstat tree in a bottom-up fashion, so calls will always be made for cgroups that have updates before their parents. The program aggregates percpu readings to a total per-cgroup reading, and also propagates them to the parent cgroup. After rstat flushing is over, all cgroups will have correct updated hierarchical readings (including all cpus and all their descendants).

- Finally, the test creates a cgroup hierarchy and induces memcg reclaim in parts of it, and makes sure that the stats collection, aggregation, and reading workflow works as expected.

---
 .../prog_tests/cgroup_hierarchical_stats.c    | 362 ++++++++++++++++++
 .../bpf/progs/cgroup_hierarchical_stats.c     | 235 ++++++++++++
 2 files changed, 597 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c
 create mode 100644 tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +362 -0
new file mode 100644
index 0000000000000..5d0a8bb110a44
@@ -0,0 +1,362 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Functions to manage eBPF programs attached to cgroup subsystems
+ *
+ * Copyright 2022 Google LLC.
+ */
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <test_progs.h>
+#include <bpf/libbpf.h>
+#include <bpf/bpf.h>
+
+#include "cgroup_helpers.h"
+#include "cgroup_hierarchical_stats.skel.h"
+
+#define PAGE_SIZE 4096
+#define MB(x) (x << 20)
+
+#define BPFFS_ROOT "/sys/fs/bpf/"
+#define BPFFS_VMSCAN BPFFS_ROOT"vmscan/"
+
+#define CG_ROOT_NAME "root"
+#define CG_ROOT_ID 1
+
+#define CGROUP_PATH(p, n) {.path = #p"/"#n, .name = #n}
+
+static struct {
+	const char *path, *name;
+	unsigned long long id;
+	int fd;
+} cgroups[] = {
+	CGROUP_PATH(/, test),
+	CGROUP_PATH(/test, child1),
+	CGROUP_PATH(/test, child2),
+	CGROUP_PATH(/test/child1, child1_1),
+	CGROUP_PATH(/test/child1, child1_2),
+	CGROUP_PATH(/test/child2, child2_1),
+	CGROUP_PATH(/test/child2, child2_2),
+};
+
+#define N_CGROUPS ARRAY_SIZE(cgroups)
+#define N_NON_LEAF_CGROUPS 3
+
+int root_cgroup_fd;
+bool mounted_bpffs;
+
+static int read_from_file(const char *path, char *buf, size_t size)
+{
+	int fd, len;
+
+	fd = open(path, O_RDONLY);
+	if (fd < 0) {
+		log_err("Open %s", path);
+		return 1;
+	}
+	len = read(fd, buf, size);
+	if (len < 0)
+		log_err("Read %s", path);
+	else
+		buf[len] = 0;
+	close(fd);
+	return len < 0;
+}
+
+static int setup_bpffs(void)
+{
+	int err;
+
+	/* Mount bpffs */
+	err = mount("bpf", BPFFS_ROOT, "bpf", 0, NULL);
+	mounted_bpffs = !err;
+	if (!ASSERT_OK(err && errno != EBUSY, "mount bpffs"))
+		return err;
+
+	/* Create a directory to contain stat files in bpffs */
+	err = mkdir(BPFFS_VMSCAN, 0755);
+	ASSERT_OK(err, "mkdir bpffs");
+	return err;
+}
+
+static void cleanup_bpffs(void)
+{
+	/* Remove created directory in bpffs */
+	ASSERT_OK(rmdir(BPFFS_VMSCAN), "rmdir "BPFFS_VMSCAN);
+
+	/* Unmount bpffs, if it wasn't already mounted when we started */
+	if (mounted_bpffs)
+		return;
+	ASSERT_OK(umount(BPFFS_ROOT), "unmount bpffs");
+}
+
+static int setup_cgroups(void)
+{
+	int i, fd, err;
+
+	err = setup_cgroup_environment();
+	if (!ASSERT_OK(err, "setup_cgroup_environment"))
+		return err;
+
+	root_cgroup_fd = get_root_cgroup();
+	if (!ASSERT_GE(root_cgroup_fd, 0, "get_root_cgroup"))
+		return root_cgroup_fd;
+
+	for (i = 0; i < N_CGROUPS; i++) {
+		fd = create_and_get_cgroup(cgroups[i].path);
+		if (!ASSERT_GE(fd, 0, "create_and_get_cgroup"))
+			return fd;
+
+		cgroups[i].fd = fd;
+		cgroups[i].id = get_cgroup_id(cgroups[i].path);
+
+		/*
+		 * Enable memcg controller for the entire hierarchy.
+		 * Note that stats are collected for all cgroups in a hierarchy
+		 * with memcg enabled anyway, but are only exposed for cgroups
+		 * that have memcg enabled.
+		 */
+		if (i < N_NON_LEAF_CGROUPS) {
+			err = enable_controllers(cgroups[i].path, "memory");
+			if (!ASSERT_OK(err, "enable_controllers"))
+				return err;
+		}
+	}
+	return 0;
+}
+
+static void cleanup_cgroups(void)
+{
+	close(root_cgroup_fd);
+	for (int i = 0; i < N_CGROUPS; i++)
+		close(cgroups[i].fd);
+	cleanup_cgroup_environment();
+}
+
+
+static int setup_hierarchy(void)
+{
+	return setup_bpffs() || setup_cgroups();
+}
+
+static void destroy_hierarchy(void)
+{
+	cleanup_cgroups();
+	cleanup_bpffs();
+}
+
+static void reclaimer(const char *cgroup_path, size_t size)
+{
+	char *buf, *ptr;
+	char size_buf[128];
+	int err;
+
+	/* Join cgroup in the parent process workdir */
+	join_parent_cgroup(cgroup_path);
+
+	/* Allocate memory */
+	buf = malloc(size);
+	for (ptr = buf; ptr < buf + size; ptr += PAGE_SIZE)
+		*ptr = 1;
+
+	/*
+	 * Try to reclaim memory.
+	 * memory.reclaim can return EAGAIN if the amount is not
+	 * fully reclaimed.
+	 */
+	snprintf(size_buf, 128, "%lu", size);
+	err = write_cgroup_file_parent(cgroup_path, "memory.reclaim", size_buf);
+
+	free(buf);
+	exit(err && errno != EAGAIN);
+}
+
+static int induce_vmscan(void)
+{
+	int i, status, err = 0;
+
+	/*
+	 * In every leaf cgroup, run a child process that allocates some memory
+	 * and attempts to reclaim some of it.
+	 */
+	for (i = N_NON_LEAF_CGROUPS; i < N_CGROUPS; i++) {
+		pid_t pid;
+
+		/* Create reclaimer child */
+		pid = fork();
+		if (pid == 0)
+			reclaimer(cgroups[i].path, MB(5));
+		if (!ASSERT_GT(pid, 0, "fork reclaimer child"))
+			return pid;
+
+		/* Cleanup reclaimer child */
+		waitpid(pid, &status, 0);
+		err = !WIFEXITED(status) || WEXITSTATUS(status);
+		ASSERT_OK(err, "reclaimer child exit status");
+	}
+	return 0;
+}
+
+static unsigned long long get_cgroup_vmscan_delay(unsigned long long cgroup_id,
+						  const char *file_name)
+{
+	char buf[128], path[128];
+	unsigned long long vmscan = 0, id = 0;
+	int err;
+
+	/* For every cgroup, read the file generated by cgroup_iter */
+	snprintf(path, 128, "%s%s", BPFFS_VMSCAN, file_name);
+	err = read_from_file(path, buf, 128);
+	if (!ASSERT_OK(err, "read cgroup_iter"))
+		return 0;
+
+	/* Check the output file formatting */
+	ASSERT_EQ(sscanf(buf, "cg_id: %llu, total_vmscan_delay: %llu\n",
+			 &id, &vmscan), 2, "output format");
+
+	/* Check that the cgroup_id is displayed correctly */
+	ASSERT_EQ(id, cgroup_id, "cgroup_id");
+	/* Check that the vmscan reading is non-zero */
+	ASSERT_GT(vmscan, 0, "vmscan_reading");
+	return vmscan;
+}
+
+static void check_vmscan_stats(void)
+{
+	int i;
+	unsigned long long vmscan_readings[N_CGROUPS], vmscan_root;
+
+	for (i = 0; i < N_CGROUPS; i++)
+		vmscan_readings[i] = get_cgroup_vmscan_delay(cgroups[i].id,
+							     cgroups[i].name);
+
+	/* Read stats for root too */
+	vmscan_root = get_cgroup_vmscan_delay(CG_ROOT_ID, CG_ROOT_NAME);
+
+	/* Check that child1 == child1_1 + child1_2 */
+	ASSERT_EQ(vmscan_readings[1], vmscan_readings[3] + vmscan_readings[4],
+		  "child1_vmscan");
+	/* Check that child2 == child2_1 + child2_2 */
+	ASSERT_EQ(vmscan_readings[2], vmscan_readings[5] + vmscan_readings[6],
+		  "child2_vmscan");
+	/* Check that test == child1 + child2 */
+	ASSERT_EQ(vmscan_readings[0], vmscan_readings[1] + vmscan_readings[2],
+		  "test_vmscan");
+	/* Check that root >= test */
+	ASSERT_GE(vmscan_root, vmscan_readings[1], "root_vmscan");
+}
+
+static int setup_cgroup_iter(struct cgroup_hierarchical_stats *obj, int cgroup_fd,
+			     const char *file_name)
+{
+	DECLARE_LIBBPF_OPTS(bpf_iter_attach_opts, opts);
+	union bpf_iter_link_info linfo = {};
+	struct bpf_link *link;
+	char path[128];
+	int err;
+
+	/*
+	 * Create an iter link, parameterized by cgroup_fd.
+	 * We only want to traverse one cgroup, so set the traversal order to
+	 * "pre", and return 1 from dump_vmscan to stop iteration after the
+	 * first cgroup.
+	 */
+	linfo.cgroup.cgroup_fd = cgroup_fd;
+	linfo.cgroup.traversal_order = BPF_ITER_CGROUP_PRE;
+	opts.link_info = &linfo;
+	opts.link_info_len = sizeof(linfo);
+	link = bpf_program__attach_iter(obj->progs.dump_vmscan, &opts);
+	if (!ASSERT_OK_PTR(link, "attach iter"))
+		return libbpf_get_error(link);
+
+	/* Pin the link to a bpffs file */
+	snprintf(path, 128, "%s%s", BPFFS_VMSCAN, file_name);
+	err = bpf_link__pin(link, path);
+	if (!ASSERT_OK(err, "pin cgroup_iter"))
+		return err;
+
+	/* Remove the link, leaving only the ref held by the pinned file */
+	err = bpf_link__destroy(link);
+	ASSERT_OK(err, "destroy cgroup_iter link");
+	return err;
+}
+
+static int setup_progs(struct cgroup_hierarchical_stats **skel)
+{
+	int i, err;
+	struct bpf_link *link;
+	struct cgroup_hierarchical_stats *obj;
+
+	obj = cgroup_hierarchical_stats__open_and_load();
+	if (!ASSERT_OK_PTR(obj, "open_and_load"))
+		return libbpf_get_error(obj);
+
+	/* Attach cgroup_iter program that will dump the stats to cgroups */
+	for (i = 0; i < N_CGROUPS; i++) {
+		err = setup_cgroup_iter(obj, cgroups[i].fd, cgroups[i].name);
+		if (!ASSERT_OK(err, "setup_cgroup_iter"))
+			return err;
+	}
+	/* Also dump stats for root */
+	err = setup_cgroup_iter(obj, root_cgroup_fd, CG_ROOT_NAME);
+	if (!ASSERT_OK(err, "setup_cgroup_iter"))
+		return err;
+
+	/* Attach rstat flusher */
+	link = bpf_program__attach(obj->progs.vmscan_flush);
+	if (!ASSERT_OK_PTR(link, "attach rstat"))
+		return libbpf_get_error(link);
+	obj->links.vmscan_flush = link;
+
+	/* Attach tracing programs that will calculate vmscan delays */
+	link = bpf_program__attach(obj->progs.vmscan_start);
+	if (!ASSERT_OK_PTR(obj, "attach raw_tracepoint"))
+		return libbpf_get_error(link);
+	obj->links.vmscan_start = link;
+
+	link = bpf_program__attach(obj->progs.vmscan_end);
+	if (!ASSERT_OK_PTR(obj, "attach raw_tracepoint"))
+		return libbpf_get_error(link);
+	obj->links.vmscan_end = link;
+
+	*skel = obj;
+	return 0;
+}
+
+void destroy_progs(struct cgroup_hierarchical_stats *skel)
+{
+	char path[128];
+	int i;
+
+	for (i = 0; i < N_CGROUPS; i++) {
+		/* Delete files in bpffs that cgroup_iters are pinned in */
+		snprintf(path, 128, "%s%s", BPFFS_VMSCAN,
+			 cgroups[i].name);
+		ASSERT_OK(remove(path), "remove cgroup_iter pin");
+	}
+
+	/* Delete root file in bpffs */
+	snprintf(path, 128, "%s%s", BPFFS_VMSCAN, CG_ROOT_NAME);
+	ASSERT_OK(remove(path), "remove cgroup_iter root pin");
+	cgroup_hierarchical_stats__destroy(skel);
+}
+
+void test_cgroup_hierarchical_stats(void)
+{
+	struct cgroup_hierarchical_stats *skel = NULL;
+
+	if (setup_hierarchy())
+		goto hierarchy_cleanup;
+	if (setup_progs(&skel))
+		goto cleanup;
+	if (induce_vmscan())
+		goto cleanup;
+	check_vmscan_stats();
+cleanup:
+	destroy_progs(skel);
+hierarchy_cleanup:
+	destroy_hierarchy();
+}
tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c new file +235 -0

235 lines not on this page · raw message

Signature · 1 line
2.37.0.rc0.161.g10f37bed90-goog
#18 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

Quoted 54 lines · Yosry Ahmed

Add a selftest that tests the whole workflow for collecting, aggregating (flushing), and displaying cgroup hierarchical stats.

TL;DR:
- Userspace program creates a cgroup hierarchy and induces memcg reclaim in parts of it.
- Whenever reclaim happens, vmscan_start and vmscan_end update per-cgroup percpu readings, and tell rstat which (cgroup, cpu) pairs have updates.
- When userspace tries to read the stats, vmscan_dump calls rstat to flush the stats, and outputs the stats in text format to userspace (similar to cgroupfs stats).
- rstat calls vmscan_flush once for every (cgroup, cpu) pair that has updates, vmscan_flush aggregates cpu readings and propagates updates to parents.
- Userspace program makes sure the stats are aggregated and read correctly.

Detailed explanation:
- The test loads tracing bpf programs, vmscan_start and vmscan_end, to measure the latency of cgroup reclaim. Per-cgroup readings are stored in percpu maps for efficiency. When a cgroup reading is updated on a cpu, cgroup_rstat_updated(cgroup, cpu) is called to add the cgroup to the rstat updated tree on that cpu.

- A cgroup_iter program, vmscan_dump, is loaded and pinned to a file, for each cgroup. Reading this file invokes the program, which calls cgroup_rstat_flush(cgroup) to ask rstat to propagate the updates for all cpus and cgroups that have updates in this cgroup's subtree. Afterwards, the stats are exposed to the user. vmscan_dump returns 1 to terminate iteration early, so that we only expose stats for one cgroup per read.

- An ftrace program, vmscan_flush, is also loaded and attached to bpf_rstat_flush. When rstat flushing is ongoing, vmscan_flush is invoked once for each (cgroup, cpu) pair that has updates. cgroups are popped from the rstat tree in a bottom-up fashion, so calls will always be made for cgroups that have updates before their parents. The program aggregates percpu readings to a total per-cgroup reading, and also propagates them to the parent cgroup. After rstat flushing is over, all cgroups will have correct updated hierarchical readings (including all cpus and all their descendants).

- Finally, the test creates a cgroup hierarchy and induces memcg reclaim in parts of it, and makes sure that the stats collection, aggregation, and reading workflow works as expected.

---
  .../prog_tests/cgroup_hierarchical_stats.c    | 362 ++++++++++++++++++
  .../bpf/progs/cgroup_hierarchical_stats.c     | 235 ++++++++++++
  2 files changed, 597 insertions(+)

create mode 100644 tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c create mode 100644 tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c

[...]

Quoted 38 lines
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +38 -0
+
+static unsigned long long get_cgroup_vmscan_delay(unsigned long long cgroup_id,
+						  const char *file_name)
+{
+	char buf[128], path[128];
+	unsigned long long vmscan = 0, id = 0;
+	int err;
+
+	/* For every cgroup, read the file generated by cgroup_iter */
+	snprintf(path, 128, "%s%s", BPFFS_VMSCAN, file_name);
+	err = read_from_file(path, buf, 128);
+	if (!ASSERT_OK(err, "read cgroup_iter"))
+		return 0;
+
+	/* Check the output file formatting */
+	ASSERT_EQ(sscanf(buf, "cg_id: %llu, total_vmscan_delay: %llu\n",
+			 &id, &vmscan), 2, "output format");
+
+	/* Check that the cgroup_id is displayed correctly */
+	ASSERT_EQ(id, cgroup_id, "cgroup_id");
+	/* Check that the vmscan reading is non-zero */
+	ASSERT_GT(vmscan, 0, "vmscan_reading");
+	return vmscan;
+}
+
+static void check_vmscan_stats(void)
+{
+	int i;
+	unsigned long long vmscan_readings[N_CGROUPS], vmscan_root;
+
+	for (i = 0; i < N_CGROUPS; i++)
+		vmscan_readings[i] = get_cgroup_vmscan_delay(cgroups[i].id,
+							     cgroups[i].name);
+
+	/* Read stats for root too */
+	vmscan_root = get_cgroup_vmscan_delay(CG_ROOT_ID, CG_ROOT_NAME);
+
+	/* Check that child1 == child1_1 + child1_2 */

tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c line 249

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +10 -0
+	ASSERT_EQ(vmscan_readings[1], vmscan_readings[3] + vmscan_readings[4],
+		  "child1_vmscan");
+	/* Check that child2 == child2_1 + child2_2 */
+	ASSERT_EQ(vmscan_readings[2], vmscan_readings[5] + vmscan_readings[6],
+		  "child2_vmscan");
+	/* Check that test == child1 + child2 */
+	ASSERT_EQ(vmscan_readings[0], vmscan_readings[1] + vmscan_readings[2],
+		  "test_vmscan");
+	/* Check that root >= test */
+	ASSERT_GE(vmscan_root, vmscan_readings[1], "root_vmscan");

I still get a test failure with

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:FAIL:vmscan_reading unexpected vmscan_reading: actual 0 <= expected 0 check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan: actual 0 != expected -2 check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan: actual 0 != expected -2 check_vmscan_stats:PASS:test_vmscan 0 nsec
check_vmscan_stats:PASS:root_vmscan 0 nsec

I added 'dump_stack()' in function try_to_free_mem_cgroup_pages() and run this test (#33) and didn't get any stacktrace. But I do get stacktraces due to other operations like

        try_to_free_mem_cgroup_pages+0x1fd [kernel]
        try_to_free_mem_cgroup_pages+0x1fd [kernel]
        memory_reclaim_write+0x88 [kernel]
        cgroup_file_write+0x88 [kernel]
        kernfs_fop_write_iter+0xd0 [kernel]
        vfs_write+0x2c4 [kernel]
        __x64_sys_write+0x60 [kernel]
        do_syscall_64+0x2d [kernel]
        entry_SYSCALL_64_after_hwframe+0x44 [kernel]

If you can show me the stacktrace about how try_to_free_mem_cgroup_pages() is triggered in your setup, I can help debug this problem in my environment.

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +3 -0
+}
+
+static int setup_cgroup_iter(struct cgroup_hierarchical_stats *obj, int cgroup_fd,

[...]

#19 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

Quoted 134 lines · Yonghong Song
Quoted 55 lines · Yosry Ahmed

Add a selftest that tests the whole workflow for collecting, aggregating (flushing), and displaying cgroup hierarchical stats.

TL;DR:
- Userspace program creates a cgroup hierarchy and induces memcg reclaim in parts of it.
- Whenever reclaim happens, vmscan_start and vmscan_end update per-cgroup percpu readings, and tell rstat which (cgroup, cpu) pairs have updates.
- When userspace tries to read the stats, vmscan_dump calls rstat to flush
   the stats, and outputs the stats in text format to userspace (similar to cgroupfs stats).
- rstat calls vmscan_flush once for every (cgroup, cpu) pair that has updates, vmscan_flush aggregates cpu readings and propagates updates to parents.
- Userspace program makes sure the stats are aggregated and read correctly.

Detailed explanation:
- The test loads tracing bpf programs, vmscan_start and vmscan_end, to measure the latency of cgroup reclaim. Per-cgroup readings are stored in percpu maps for efficiency. When a cgroup reading is updated on a cpu, cgroup_rstat_updated(cgroup, cpu) is called to add the cgroup to the rstat updated tree on that cpu.

- A cgroup_iter program, vmscan_dump, is loaded and pinned to a file, for each cgroup. Reading this file invokes the program, which calls cgroup_rstat_flush(cgroup) to ask rstat to propagate the updates for all cpus and cgroups that have updates in this cgroup's subtree. Afterwards, the stats are exposed to the user. vmscan_dump returns 1 to terminate iteration early, so that we only expose stats for one cgroup per read.

- An ftrace program, vmscan_flush, is also loaded and attached to bpf_rstat_flush. When rstat flushing is ongoing, vmscan_flush is invoked once for each (cgroup, cpu) pair that has updates. cgroups are popped from the rstat tree in a bottom-up fashion, so calls will always be made for cgroups that have updates before their parents. The program aggregates percpu readings to a total per-cgroup reading, and also propagates them to the parent cgroup. After rstat flushing is over, all cgroups will have correct updated hierarchical readings (including all cpus and all their descendants).

- Finally, the test creates a cgroup hierarchy and induces memcg reclaim in parts of it, and makes sure that the stats collection, aggregation, and reading workflow works as expected.

---
  .../prog_tests/cgroup_hierarchical_stats.c    | 362 ++++++++++++++++++ .../bpf/progs/cgroup_hierarchical_stats.c     | 235 ++++++++++++

  2 files changed, 597 insertions(+)

  create mode 100644 tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c create mode 100644 tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c

[...]

Quoted 44 lines
(quoted diff) +2 -0
+
+static unsigned long long get_cgroup_vmscan_delay(unsigned long long 

cgroup_id,
+                          const char *file_name)

tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +36 -0
+{
+    char buf[128], path[128];
+    unsigned long long vmscan = 0, id = 0;
+    int err;
+
+    /* For every cgroup, read the file generated by cgroup_iter */
+    snprintf(path, 128, "%s%s", BPFFS_VMSCAN, file_name);
+    err = read_from_file(path, buf, 128);
+    if (!ASSERT_OK(err, "read cgroup_iter"))
+        return 0;
+
+    /* Check the output file formatting */
+    ASSERT_EQ(sscanf(buf, "cg_id: %llu, total_vmscan_delay: %llu\n",
+             &id, &vmscan), 2, "output format");
+
+    /* Check that the cgroup_id is displayed correctly */
+    ASSERT_EQ(id, cgroup_id, "cgroup_id");
+    /* Check that the vmscan reading is non-zero */
+    ASSERT_GT(vmscan, 0, "vmscan_reading");
+    return vmscan;
+}
+
+static void check_vmscan_stats(void)
+{
+    int i;
+    unsigned long long vmscan_readings[N_CGROUPS], vmscan_root;
+
+    for (i = 0; i < N_CGROUPS; i++)
+        vmscan_readings[i] = get_cgroup_vmscan_delay(cgroups[i].id,
+                                 cgroups[i].name);
+
+    /* Read stats for root too */
+    vmscan_root = get_cgroup_vmscan_delay(CG_ROOT_ID, CG_ROOT_NAME);
+
+    /* Check that child1 == child1_1 + child1_2 */
+    ASSERT_EQ(vmscan_readings[1], vmscan_readings[3] + 

vmscan_readings[4],
+          "child1_vmscan");
+    /* Check that child2 == child2_1 + child2_2 */ +    ASSERT_EQ(vmscan_readings[2], vmscan_readings[5] +

Quoted 8 lines

vmscan_readings[6],
+          "child2_vmscan");
+    /* Check that test == child1 + child2 */
+    ASSERT_EQ(vmscan_readings[0], vmscan_readings[1] + vmscan_readings[2],
+          "test_vmscan");
+    /* Check that root >= test */
+    ASSERT_GE(vmscan_root, vmscan_readings[1], "root_vmscan");

I still get a test failure with

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:FAIL:vmscan_reading unexpected vmscan_reading: actual 0 <= expected 0 check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan: actual 0 != expected -2 check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan: actual 0 != expected -2 check_vmscan_stats:PASS:test_vmscan 0 nsec
check_vmscan_stats:PASS:root_vmscan 0 nsec

I added 'dump_stack()' in function try_to_free_mem_cgroup_pages() and run this test (#33) and didn't get any stacktrace. But I do get stacktraces due to other operations like
        try_to_free_mem_cgroup_pages+0x1fd [kernel] try_to_free_mem_cgroup_pages+0x1fd [kernel] memory_reclaim_write+0x88 [kernel] cgroup_file_write+0x88 [kernel] kernfs_fop_write_iter+0xd0 [kernel] vfs_write+0x2c4 [kernel]
        __x64_sys_write+0x60 [kernel] do_syscall_64+0x2d [kernel] entry_SYSCALL_64_after_hwframe+0x44 [kernel]

Quoted 2 lines

If you can show me the stacktrace about how try_to_free_mem_cgroup_pages() is triggered in your setup, I can help debug this problem in my environment.

BTW, CI also reported the test failure.
https://github.com/kernel-patches/bpf/pull/3284

For example, with gcc built kernel,
https://github.com/kernel-patches/bpf/runs/7272407890?check_suite_focus=true

The error:

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:PASS:vmscan_reading 0 nsec check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan:
actual 28390910 != expected 28390909
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan:
actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

Quoted 6 lines
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +3 -0
+}
+
+static int setup_cgroup_iter(struct cgroup_hierarchical_stats *obj, 

int cgroup_fd,

[...]

#20 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

Quoted 4 lines · Yonghong Song

On 7/10/22 5:26 PM, Yonghong Song wrote:

[...]

Quoted 9 lines

BTW, CI also reported the test failure.
https://github.com/kernel-patches/bpf/pull/3284

For example, with gcc built kernel,
https://github.com/kernel-patches/bpf/runs/7272407890?check_suite_focus=true

The error:

Quoted 9 lines

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:PASS:vmscan_reading 0 nsec check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan:
actual 28390910 != expected 28390909
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan:
actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

Yonghong,

I noticed that the test only failed on test_progs-no_alu32, not test_progs. test_progs passed. I believe Yosry and I have only tested on test_progs. I tried building and running the no_alu32 version, but so far, not able to run test_progs-no_alu32. Whenever I ran test_progs-no_alu32, it exits without any message. Do you have any clue what could be wrong?

Quoted 1 line
Quoted 1 line

[...]

#21 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

Quoted 25 lines · Hao Luo
Quoted 4 lines · Yonghong Song

On 7/10/22 5:26 PM, Yonghong Song wrote:

[...]

Quoted 9 lines

BTW, CI also reported the test failure.
https://github.com/kernel-patches/bpf/pull/3284

For example, with gcc built kernel,
https://github.com/kernel-patches/bpf/runs/7272407890?check_suite_focus=true

The error:

Quoted 9 lines

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:PASS:vmscan_reading 0 nsec check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan:
actual 28390910 != expected 28390909
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan:
actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

Quoted 4 lines

Yonghong,

I noticed that the test only failed on test_progs-no_alu32, not test_progs. test_progs passed. I believe Yosry and I have only tested

In my case, both test_progs and test_progs-no_alu32 failed the test. I think the reason for the failure is the same.

Quoted 4 lines

on test_progs. I tried building and running the no_alu32 version, but so far, not able to run test_progs-no_alu32. Whenever I ran test_progs-no_alu32, it exits without any message. Do you have any clue what could be wrong?

It works fine in my environment. test_progs should be very similar to test_progs-no_alu32. The only difference is bpf programs with different insn set. Some tests may not run with test_progs-no_alu32, e.g., newer atomic insn tests.

I have no idea why test_progs-no_alu32 won't work for you, I guess you may need to debug it a little bit.

Quoted 3 lines
Quoted 2 lines
Quoted 2 lines

[...]

#22 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

Quoted 42 lines · Yonghong Song
Quoted 25 lines · Hao Luo
Quoted 4 lines · Yonghong Song

On 7/10/22 5:26 PM, Yonghong Song wrote:

[...]

Quoted 9 lines

BTW, CI also reported the test failure.
https://github.com/kernel-patches/bpf/pull/3284

For example, with gcc built kernel,
https://github.com/kernel-patches/bpf/runs/7272407890?check_suite_focus=true

The error:

Quoted 9 lines

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:PASS:vmscan_reading 0 nsec check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan:
actual 28390910 != expected 28390909
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan:
actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

Quoted 4 lines

Yonghong,

I noticed that the test only failed on test_progs-no_alu32, not test_progs. test_progs passed. I believe Yosry and I have only tested

In my case, both test_progs and test_progs-no_alu32 failed the test. I think the reason for the failure is the same.

Quoted 4 lines

on test_progs. I tried building and running the no_alu32 version, but so far, not able to run test_progs-no_alu32. Whenever I ran test_progs-no_alu32, it exits without any message. Do you have any clue what could be wrong?

Quoted 8 lines

It works fine in my environment. test_progs should be very similar to test_progs-no_alu32. The only difference is bpf programs with different insn set. Some tests may not run with test_progs-no_alu32, e.g., newer atomic insn tests.

I have no idea why test_progs-no_alu32 won't work for you, I guess you may need to debug it a little bit.

Yonghong, I reproduced the failure using vmtest.sh now. Yosry and I are debugging it. Once we have any result, we will report back. Thanks for taking a look.

Quoted 3 lines
Quoted 3 lines
Quoted 2 lines
Quoted 2 lines

[...]

#23 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

In reply to Yonghong Song
Quoted 160 lines · Yonghong Song
Quoted 144 lines · Yonghong Song
Quoted 62 lines · Yosry Ahmed

Add a selftest that tests the whole workflow for collecting, aggregating (flushing), and displaying cgroup hierarchical stats.

TL;DR:
- Userspace program creates a cgroup hierarchy and induces memcg reclaim in parts of it.
- Whenever reclaim happens, vmscan_start and vmscan_end update per-cgroup percpu readings, and tell rstat which (cgroup, cpu) pairs have updates.
- When userspace tries to read the stats, vmscan_dump calls rstat to flush
the stats, and outputs the stats in text format to userspace (similar to cgroupfs stats).
- rstat calls vmscan_flush once for every (cgroup, cpu) pair that has updates, vmscan_flush aggregates cpu readings and propagates updates to parents.
- Userspace program makes sure the stats are aggregated and read correctly.

Detailed explanation:
- The test loads tracing bpf programs, vmscan_start and vmscan_end, to measure the latency of cgroup reclaim. Per-cgroup readings are
stored in
percpu maps for efficiency. When a cgroup reading is updated on a cpu, cgroup_rstat_updated(cgroup, cpu) is called to add the cgroup to the rstat updated tree on that cpu.

- A cgroup_iter program, vmscan_dump, is loaded and pinned to a file, for each cgroup. Reading this file invokes the program, which calls cgroup_rstat_flush(cgroup) to ask rstat to propagate the updates
for all
cpus and cgroups that have updates in this cgroup's subtree.
Afterwards,
the stats are exposed to the user. vmscan_dump returns 1 to terminate iteration early, so that we only expose stats for one cgroup per read.

- An ftrace program, vmscan_flush, is also loaded and attached to bpf_rstat_flush. When rstat flushing is ongoing, vmscan_flush is
invoked
once for each (cgroup, cpu) pair that has updates. cgroups are popped from the rstat tree in a bottom-up fashion, so calls will always be made for cgroups that have updates before their parents. The program aggregates percpu readings to a total per-cgroup reading, and also propagates them to the parent cgroup. After rstat flushing is over,
all
cgroups will have correct updated hierarchical readings (including all cpus and all their descendants).

- Finally, the test creates a cgroup hierarchy and induces memcg reclaim in parts of it, and makes sure that the stats collection, aggregation, and reading workflow works as expected.

---
  .../prog_tests/cgroup_hierarchical_stats.c    | 362 ++++++++++++++++++
  .../bpf/progs/cgroup_hierarchical_stats.c     | 235 ++++++++++++
  2 files changed, 597 insertions(+)

create mode 100644
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c
create mode 100644
tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c

[...]

Quoted 49 lines
(quoted diff) +2 -0
+
+static unsigned long long get_cgroup_vmscan_delay(unsigned long long

cgroup_id,

tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +37 -0
+                          const char *file_name)
+{
+    char buf[128], path[128];
+    unsigned long long vmscan = 0, id = 0;
+    int err;
+
+    /* For every cgroup, read the file generated by cgroup_iter */
+    snprintf(path, 128, "%s%s", BPFFS_VMSCAN, file_name);
+    err = read_from_file(path, buf, 128);
+    if (!ASSERT_OK(err, "read cgroup_iter"))
+        return 0;
+
+    /* Check the output file formatting */
+    ASSERT_EQ(sscanf(buf, "cg_id: %llu, total_vmscan_delay: %llu\n",
+             &id, &vmscan), 2, "output format");
+
+    /* Check that the cgroup_id is displayed correctly */
+    ASSERT_EQ(id, cgroup_id, "cgroup_id");
+    /* Check that the vmscan reading is non-zero */
+    ASSERT_GT(vmscan, 0, "vmscan_reading");
+    return vmscan;
+}
+
+static void check_vmscan_stats(void)
+{
+    int i;
+    unsigned long long vmscan_readings[N_CGROUPS], vmscan_root;
+
+    for (i = 0; i < N_CGROUPS; i++)
+        vmscan_readings[i] = get_cgroup_vmscan_delay(cgroups[i].id,
+                                 cgroups[i].name);
+
+    /* Read stats for root too */
+    vmscan_root = get_cgroup_vmscan_delay(CG_ROOT_ID, CG_ROOT_NAME);
+
+    /* Check that child1 == child1_1 + child1_2 */
+    ASSERT_EQ(vmscan_readings[1], vmscan_readings[3] +

vmscan_readings[4],

tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +3 -0
+          "child1_vmscan");
+    /* Check that child2 == child2_1 + child2_2 */
+    ASSERT_EQ(vmscan_readings[2], vmscan_readings[5] +

vmscan_readings[6],

tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +3 -0
+          "child2_vmscan");
+    /* Check that test == child1 + child2 */
+    ASSERT_EQ(vmscan_readings[0], vmscan_readings[1] +

vmscan_readings[2],

tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c line 249

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +3 -0
+          "test_vmscan");
+    /* Check that root >= test */
+    ASSERT_GE(vmscan_root, vmscan_readings[1], "root_vmscan");

I still get a test failure with

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:FAIL:vmscan_reading unexpected vmscan_reading:
actual 0 <= expected 0
check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan: actual 0 != expected -2
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan: actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

I added 'dump_stack()' in function try_to_free_mem_cgroup_pages() and run this test (#33) and didn't get any stacktrace. But I do get stacktraces due to other operations like

         try_to_free_mem_cgroup_pages+0x1fd [kernel]
         try_to_free_mem_cgroup_pages+0x1fd [kernel]
         memory_reclaim_write+0x88 [kernel]
         cgroup_file_write+0x88 [kernel]
         kernfs_fop_write_iter+0xd0 [kernel]
         vfs_write+0x2c4 [kernel]
         __x64_sys_write+0x60 [kernel]
         do_syscall_64+0x2d [kernel]
         entry_SYSCALL_64_after_hwframe+0x44 [kernel]
Quoted 3 lines

If you can show me the stacktrace about how try_to_free_mem_cgroup_pages() is triggered in your setup, I can help debug this problem in my environment.

BTW, CI also reported the test failure.
https://github.com/kernel-patches/bpf/pull/3284

For example, with gcc built kernel,
https://github.com/kernel-patches/bpf/runs/7272407890?check_suite_focus=true

The error:

Quoted 9 lines

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:PASS:vmscan_reading 0 nsec check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan:
actual 28390910 != expected 28390909
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan:
actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

Hey Yonghong,

Thanks for helping us debug this failure. I can reproduce the CI failure in my enviornment, but this failure is actually different from the failure in your environment. In your environment it looks like no stats are gathered for all cgroups (either no reclaim happening or bpf progs not being run). In the CI and in my environment, only one cgroup observes this behavior.

The thing is, I was able to reproduce the problem only when I ran all test_progs. When I run the selftest alone (test_progs -t cgroup_hierarchical_stats), it consistently passes, which is interesting.

Anyway, one failure at a time :) I am working on debugging the CI failure (that occurs only when all tests are run), then we'll see if fixing that fixes the problem in our environment as well.

If you have any pointers about why a test would consistently pass alone and consistently fail with others that would be good. Otherwise, I will keep you updated with any findings I reach.

Thanks again!

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c new file +3 -0
+}
+
+static int setup_cgroup_iter(struct cgroup_hierarchical_stats *obj,

int cgroup_fd,

[...]

#24 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

Quoted 181 lines · Yosry Ahmed
Quoted 160 lines · Yonghong Song
Quoted 144 lines · Yonghong Song
Quoted 62 lines · Yosry Ahmed

Add a selftest that tests the whole workflow for collecting, aggregating (flushing), and displaying cgroup hierarchical stats.

TL;DR:
- Userspace program creates a cgroup hierarchy and induces memcg reclaim in parts of it.
- Whenever reclaim happens, vmscan_start and vmscan_end update per-cgroup percpu readings, and tell rstat which (cgroup, cpu) pairs have updates.
- When userspace tries to read the stats, vmscan_dump calls rstat to flush
the stats, and outputs the stats in text format to userspace (similar to cgroupfs stats).
- rstat calls vmscan_flush once for every (cgroup, cpu) pair that has updates, vmscan_flush aggregates cpu readings and propagates updates to parents.
- Userspace program makes sure the stats are aggregated and read correctly.

Detailed explanation:
- The test loads tracing bpf programs, vmscan_start and vmscan_end, to measure the latency of cgroup reclaim. Per-cgroup readings are
stored in
percpu maps for efficiency. When a cgroup reading is updated on a cpu, cgroup_rstat_updated(cgroup, cpu) is called to add the cgroup to the rstat updated tree on that cpu.

- A cgroup_iter program, vmscan_dump, is loaded and pinned to a file, for each cgroup. Reading this file invokes the program, which calls cgroup_rstat_flush(cgroup) to ask rstat to propagate the updates
for all
cpus and cgroups that have updates in this cgroup's subtree.
Afterwards,
the stats are exposed to the user. vmscan_dump returns 1 to terminate iteration early, so that we only expose stats for one cgroup per read.

- An ftrace program, vmscan_flush, is also loaded and attached to bpf_rstat_flush. When rstat flushing is ongoing, vmscan_flush is
invoked
once for each (cgroup, cpu) pair that has updates. cgroups are popped from the rstat tree in a bottom-up fashion, so calls will always be made for cgroups that have updates before their parents. The program aggregates percpu readings to a total per-cgroup reading, and also propagates them to the parent cgroup. After rstat flushing is over,
all
cgroups will have correct updated hierarchical readings (including all cpus and all their descendants).

- Finally, the test creates a cgroup hierarchy and induces memcg reclaim in parts of it, and makes sure that the stats collection, aggregation, and reading workflow works as expected.

---
  .../prog_tests/cgroup_hierarchical_stats.c    | 362 ++++++++++++++++++
  .../bpf/progs/cgroup_hierarchical_stats.c     | 235 ++++++++++++
  2 files changed, 597 insertions(+)

create mode 100644
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c
create mode 100644
tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c

[...]

Quoted 49 lines
(quoted diff) +2 -0
+
+static unsigned long long get_cgroup_vmscan_delay(unsigned long long

cgroup_id,

(quoted diff) +37 -0
+                          const char *file_name)
+{
+    char buf[128], path[128];
+    unsigned long long vmscan = 0, id = 0;
+    int err;
+
+    /* For every cgroup, read the file generated by cgroup_iter */
+    snprintf(path, 128, "%s%s", BPFFS_VMSCAN, file_name);
+    err = read_from_file(path, buf, 128);
+    if (!ASSERT_OK(err, "read cgroup_iter"))
+        return 0;
+
+    /* Check the output file formatting */
+    ASSERT_EQ(sscanf(buf, "cg_id: %llu, total_vmscan_delay: %llu\n",
+             &id, &vmscan), 2, "output format");
+
+    /* Check that the cgroup_id is displayed correctly */
+    ASSERT_EQ(id, cgroup_id, "cgroup_id");
+    /* Check that the vmscan reading is non-zero */
+    ASSERT_GT(vmscan, 0, "vmscan_reading");
+    return vmscan;
+}
+
+static void check_vmscan_stats(void)
+{
+    int i;
+    unsigned long long vmscan_readings[N_CGROUPS], vmscan_root;
+
+    for (i = 0; i < N_CGROUPS; i++)
+        vmscan_readings[i] = get_cgroup_vmscan_delay(cgroups[i].id,
+                                 cgroups[i].name);
+
+    /* Read stats for root too */
+    vmscan_root = get_cgroup_vmscan_delay(CG_ROOT_ID, CG_ROOT_NAME);
+
+    /* Check that child1 == child1_1 + child1_2 */
+    ASSERT_EQ(vmscan_readings[1], vmscan_readings[3] +

vmscan_readings[4],

(quoted diff) +3 -0
+          "child1_vmscan");
+    /* Check that child2 == child2_1 + child2_2 */
+    ASSERT_EQ(vmscan_readings[2], vmscan_readings[5] +

vmscan_readings[6],

(quoted diff) +3 -0
+          "child2_vmscan");
+    /* Check that test == child1 + child2 */
+    ASSERT_EQ(vmscan_readings[0], vmscan_readings[1] +

vmscan_readings[2],

Review

Quoted 3 lines
(quoted diff) +3 -0
+          "test_vmscan");
+    /* Check that root >= test */
+    ASSERT_GE(vmscan_root, vmscan_readings[1], "root_vmscan");

I still get a test failure with

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:FAIL:vmscan_reading unexpected vmscan_reading:
actual 0 <= expected 0
check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan: actual 0 != expected -2
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan: actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

I added 'dump_stack()' in function try_to_free_mem_cgroup_pages() and run this test (#33) and didn't get any stacktrace. But I do get stacktraces due to other operations like

         try_to_free_mem_cgroup_pages+0x1fd [kernel]
         try_to_free_mem_cgroup_pages+0x1fd [kernel]
         memory_reclaim_write+0x88 [kernel]
         cgroup_file_write+0x88 [kernel]
         kernfs_fop_write_iter+0xd0 [kernel]
         vfs_write+0x2c4 [kernel]
         __x64_sys_write+0x60 [kernel]
         do_syscall_64+0x2d [kernel]
         entry_SYSCALL_64_after_hwframe+0x44 [kernel]
Quoted 3 lines

If you can show me the stacktrace about how try_to_free_mem_cgroup_pages() is triggered in your setup, I can help debug this problem in my environment.

BTW, CI also reported the test failure.
https://github.com/kernel-patches/bpf/pull/3284

For example, with gcc built kernel,
https://github.com/kernel-patches/bpf/runs/7272407890?check_suite_focus=true

The error:

Quoted 9 lines

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:PASS:vmscan_reading 0 nsec check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan:
actual 28390910 != expected 28390909
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan:
actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

Hey Yonghong,

Thanks for helping us debug this failure. I can reproduce the CI failure in my enviornment, but this failure is actually different from the failure in your environment. In your environment it looks like no stats are gathered for all cgroups (either no reclaim happening or bpf progs not being run). In the CI and in my environment, only one cgroup observes this behavior.

Quoted 4 lines

The thing is, I was able to reproduce the problem only when I ran all test_progs. When I run the selftest alone (test_progs -t cgroup_hierarchical_stats), it consistently passes, which is interesting.

I think I figured this one out (the CI failure). I set max_entries for the maps in the test to 10, because I have 1 entry per-cgroup, and I have less than 10 cgroups. When I run the test with other tests I *think* there are other cgroups that are being created, so the number exceeds 10, and some of the entries for the test cgroups cannot be created. I saw a lot of "failed to create entry for cgroup.." message in the bpf trace produced by my test, and the error turned out to be -E2BIG. I increased max_entries to 100 and it seems to be consistently passing when run with all the other tests, using both test_progs and test_progs-no_alu32.

Please find a diff attached fixing this problem and a few other nits:
- Return meaningful exit codes from the reclaimer() child process and check them in induce_vmscan().
- Make buf and path variables static in get_cgroup_vmscan_delay()
- Print error code in bpf trace when we fail to create a bpf map entry.
- Print 0 instead of -1 when we can't find a map entry, to avoid underflowing the unsigned counters in the test.

Let me know if this diff works or not, and if I need to send a new version with the diff or not. Also let me know if this fixes the failures that you have been seeing locally (which looked different from the CI failures).

Thanks!

Quoted 5 lines

Anyway, one failure at a time :) I am working on debugging the CI failure (that occurs only when all tests are run), then we'll see if fixing that fixes the problem in our environment as well.

Quoted 12 lines

If you have any pointers about why a test would consistently pass alone and consistently fail with others that would be good. Otherwise, I will keep you updated with any findings I reach.

Thanks again!

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
(quoted diff) +3 -0
+}
+
+static int setup_cgroup_iter(struct cgroup_hierarchical_stats *obj,

int cgroup_fd,

[...]

tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c +14 -12
index 5d0a8bb110a4..e01fac401ec5 100644
@@ -155,28 +155,30 @@ static void reclaimer(const char *cgroup_path, size_t size)
 	int err;
 
 	/* Join cgroup in the parent process workdir */
-	join_parent_cgroup(cgroup_path);
+	if (join_parent_cgroup(cgroup_path))
+		exit(EACCES);
 
 	/* Allocate memory */
 	buf = malloc(size);
+	if(!buf)
+		exit(ENOMEM);
+
+	/* Write to memory to make sure it's actually allocated */
 	for (ptr = buf; ptr < buf + size; ptr += PAGE_SIZE)
 		*ptr = 1;
 
-	/*
-	 * Try to reclaim memory.
-	 * memory.reclaim can return EAGAIN if the amount is not
-	 * fully reclaimed.
-	 */
+	/* Try to reclaim memory */
 	snprintf(size_buf, 128, "%lu", size);
 	err = write_cgroup_file_parent(cgroup_path, "memory.reclaim", size_buf);
 
 	free(buf);
-	exit(err && errno != EAGAIN);
+	/* memory.reclaim returns EAGAIN if the amount is not fully reclaimed */
+	exit(err && errno != EAGAIN ? errno : 0);
 }
 
 static int induce_vmscan(void)
 {
-	int i, status, err = 0;
+	int i, status;
 
 	/*
 	 * In every leaf cgroup, run a child process that allocates some memory
@@ -189,13 +191,13 @@ static int induce_vmscan(void)
 		pid = fork();
 		if (pid == 0)
 			reclaimer(cgroups[i].path, MB(5));
-		if (!ASSERT_GT(pid, 0, "fork reclaimer child"))
+		if (!ASSERT_GT(pid, 0, "fork reclaimer"))
 			return pid;
 
 		/* Cleanup reclaimer child */
 		waitpid(pid, &status, 0);
-		err = !WIFEXITED(status) || WEXITSTATUS(status);
-		ASSERT_OK(err, "reclaimer child exit status");
+		ASSERT_TRUE(WIFEXITED(status), "reclaimer exited");
+		ASSERT_EQ(WEXITSTATUS(status), 0, "reclaim exit code");
 	}
 	return 0;
 }
@@ -203,7 +205,7 @@ static int induce_vmscan(void)
 static unsigned long long get_cgroup_vmscan_delay(unsigned long long cgroup_id,
 						  const char *file_name)
 {
-	char buf[128], path[128];
+	static char buf[128], path[128];
 	unsigned long long vmscan = 0, id = 0;
 	int err;
 
tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c +15 -11
index 0a1a3bebdf4c..85a65a72482e 100644
@@ -37,14 +37,14 @@ struct vmscan {
 
 struct {
 	__uint(type, BPF_MAP_TYPE_PERCPU_HASH);
-	__uint(max_entries, 10);
+	__uint(max_entries, 100);
 	__type(key, __u64);
 	__type(value, struct vmscan_percpu);
 } pcpu_cgroup_vmscan_elapsed SEC(".maps");
 
 struct {
 	__uint(type, BPF_MAP_TYPE_HASH);
-	__uint(max_entries, 10);
+	__uint(max_entries, 100);
 	__type(key, __u64);
 	__type(value, struct vmscan);
 } cgroup_vmscan_elapsed SEC(".maps");
@@ -65,11 +65,13 @@ static inline uint64_t cgroup_id(struct cgroup *cgrp)
 static inline int create_vmscan_percpu_elem(__u64 cg_id, __u64 state)
 {
 	struct vmscan_percpu pcpu_init = {.state = state, .prev = 0};
+	int err;
 
-	if (bpf_map_update_elem(&pcpu_cgroup_vmscan_elapsed, &cg_id,
-				&pcpu_init, BPF_NOEXIST)) {
-		bpf_printk("failed to create pcpu entry for cgroup %llu\n"
-			   , cg_id);
+	err = bpf_map_update_elem(&pcpu_cgroup_vmscan_elapsed, &cg_id,
+				  &pcpu_init, BPF_NOEXIST);
+	if (err) {
+		bpf_printk("failed to create pcpu entry for cgroup %llu: %d\n"
+			   , cg_id, err);
 		return 1;
 	}
 	return 0;
@@ -78,11 +80,13 @@ static inline int create_vmscan_percpu_elem(__u64 cg_id, __u64 state)
 static inline int create_vmscan_elem(__u64 cg_id, __u64 state, __u64 pending)
 {
 	struct vmscan init = {.state = state, .pending = pending};
+	int err;
 
-	if (bpf_map_update_elem(&cgroup_vmscan_elapsed, &cg_id,
-				&init, BPF_NOEXIST)) {
-		bpf_printk("failed to create entry for cgroup %llu\n"
-			   , cg_id);
+	err = bpf_map_update_elem(&cgroup_vmscan_elapsed, &cg_id,
+				  &init, BPF_NOEXIST);
+	if (err) {
+		bpf_printk("failed to create entry for cgroup %llu: %d\n"
+			   , cg_id, err);
 		return 1;
 	}
 	return 0;
@@ -220,7 +224,7 @@ int BPF_PROG(dump_vmscan, struct bpf_iter_meta *meta, struct cgroup *cgrp)
 	total_stat = bpf_map_lookup_elem(&cgroup_vmscan_elapsed, &cg_id);
 	if (!total_stat) {
 		bpf_printk("error finding stats for cgroup %llu\n", cg_id);
-		BPF_SEQ_PRINTF(seq, "cg_id: %llu, total_vmscan_delay: -1\n",
+		BPF_SEQ_PRINTF(seq, "cg_id: %llu, total_vmscan_delay: 0\n",
 			       cg_id);
 		return 1;
 	}
#25 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

Quoted 1 line · Yosry Ahmed

[...]

Quoted 7 lines

I think I figured this one out (the CI failure). I set max_entries for the maps in the test to 10, because I have 1 entry per-cgroup, and I have less than 10 cgroups. When I run the test with other tests I *think* there are other cgroups that are being created, so the number exceeds 10, and some of the entries for the test cgroups cannot be created.

Using hashmap to store per-cgroup data is only a short-term solution. We should work on extending cgroup-local storage to tracing programs. Maybe as a follow-up change once cgroup_iter is merged.

Quoted 13 lines

in the bpf trace produced by my test, and the error turned out to be -E2BIG. I increased max_entries to 100 and it seems to be consistently passing when run with all the other tests, using both test_progs and test_progs-no_alu32.

Please find a diff attached fixing this problem and a few other nits:
- Return meaningful exit codes from the reclaimer() child process and check them in induce_vmscan().
- Make buf and path variables static in get_cgroup_vmscan_delay()
- Print error code in bpf trace when we fail to create a bpf map entry.
- Print 0 instead of -1 when we can't find a map entry, to avoid underflowing the unsigned counters in the test.

Quoted 5 lines

Let me know if this diff works or not, and if I need to send a new version with the diff or not. Also let me know if this fixes the failures that you have been seeing locally (which looked different from the CI failures).

Yosry, I also need to address Yonghong's comments in the cgroup_iter patch, so we need to send v4 anyway.

Hao

Quoted 2 lines

Thanks!

[...]

#26 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

In reply to Yosry Ahmed
Quoted 206 lines · Yosry Ahmed
Quoted 181 lines · Yosry Ahmed
Quoted 160 lines · Yonghong Song
Quoted 144 lines · Yonghong Song
Quoted 62 lines · Yosry Ahmed

Add a selftest that tests the whole workflow for collecting, aggregating (flushing), and displaying cgroup hierarchical stats.

TL;DR:
- Userspace program creates a cgroup hierarchy and induces memcg reclaim in parts of it.
- Whenever reclaim happens, vmscan_start and vmscan_end update per-cgroup percpu readings, and tell rstat which (cgroup, cpu) pairs have updates.
- When userspace tries to read the stats, vmscan_dump calls rstat to flush
the stats, and outputs the stats in text format to userspace (similar to cgroupfs stats).
- rstat calls vmscan_flush once for every (cgroup, cpu) pair that has updates, vmscan_flush aggregates cpu readings and propagates updates to parents.
- Userspace program makes sure the stats are aggregated and read correctly.

Detailed explanation:
- The test loads tracing bpf programs, vmscan_start and vmscan_end, to measure the latency of cgroup reclaim. Per-cgroup readings are
stored in
percpu maps for efficiency. When a cgroup reading is updated on a cpu, cgroup_rstat_updated(cgroup, cpu) is called to add the cgroup to the rstat updated tree on that cpu.

- A cgroup_iter program, vmscan_dump, is loaded and pinned to a file, for each cgroup. Reading this file invokes the program, which calls cgroup_rstat_flush(cgroup) to ask rstat to propagate the updates
for all
cpus and cgroups that have updates in this cgroup's subtree.
Afterwards,
the stats are exposed to the user. vmscan_dump returns 1 to terminate iteration early, so that we only expose stats for one cgroup per read.

- An ftrace program, vmscan_flush, is also loaded and attached to bpf_rstat_flush. When rstat flushing is ongoing, vmscan_flush is
invoked
once for each (cgroup, cpu) pair that has updates. cgroups are popped from the rstat tree in a bottom-up fashion, so calls will always be made for cgroups that have updates before their parents. The program aggregates percpu readings to a total per-cgroup reading, and also propagates them to the parent cgroup. After rstat flushing is over,
all
cgroups will have correct updated hierarchical readings (including all cpus and all their descendants).

- Finally, the test creates a cgroup hierarchy and induces memcg reclaim in parts of it, and makes sure that the stats collection, aggregation, and reading workflow works as expected.

---
   .../prog_tests/cgroup_hierarchical_stats.c    | 362 ++++++++++++++++++
   .../bpf/progs/cgroup_hierarchical_stats.c     | 235 ++++++++++++
   2 files changed, 597 insertions(+)

create mode 100644
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c
create mode 100644
tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c

[...]

Quoted 49 lines
(quoted diff) +2 -0
+
+static unsigned long long get_cgroup_vmscan_delay(unsigned long long

cgroup_id,

(quoted diff) +37 -0
+                          const char *file_name)
+{
+    char buf[128], path[128];
+    unsigned long long vmscan = 0, id = 0;
+    int err;
+
+    /* For every cgroup, read the file generated by cgroup_iter */
+    snprintf(path, 128, "%s%s", BPFFS_VMSCAN, file_name);
+    err = read_from_file(path, buf, 128);
+    if (!ASSERT_OK(err, "read cgroup_iter"))
+        return 0;
+
+    /* Check the output file formatting */
+    ASSERT_EQ(sscanf(buf, "cg_id: %llu, total_vmscan_delay: %llu\n",
+             &id, &vmscan), 2, "output format");
+
+    /* Check that the cgroup_id is displayed correctly */
+    ASSERT_EQ(id, cgroup_id, "cgroup_id");
+    /* Check that the vmscan reading is non-zero */
+    ASSERT_GT(vmscan, 0, "vmscan_reading");
+    return vmscan;
+}
+
+static void check_vmscan_stats(void)
+{
+    int i;
+    unsigned long long vmscan_readings[N_CGROUPS], vmscan_root;
+
+    for (i = 0; i < N_CGROUPS; i++)
+        vmscan_readings[i] = get_cgroup_vmscan_delay(cgroups[i].id,
+                                 cgroups[i].name);
+
+    /* Read stats for root too */
+    vmscan_root = get_cgroup_vmscan_delay(CG_ROOT_ID, CG_ROOT_NAME);
+
+    /* Check that child1 == child1_1 + child1_2 */
+    ASSERT_EQ(vmscan_readings[1], vmscan_readings[3] +

vmscan_readings[4],

(quoted diff) +3 -0
+          "child1_vmscan");
+    /* Check that child2 == child2_1 + child2_2 */
+    ASSERT_EQ(vmscan_readings[2], vmscan_readings[5] +

vmscan_readings[6],

(quoted diff) +3 -0
+          "child2_vmscan");
+    /* Check that test == child1 + child2 */
+    ASSERT_EQ(vmscan_readings[0], vmscan_readings[1] +

vmscan_readings[2],

Review

Quoted 3 lines
(quoted diff) +3 -0
+          "test_vmscan");
+    /* Check that root >= test */
+    ASSERT_GE(vmscan_root, vmscan_readings[1], "root_vmscan");

I still get a test failure with

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:FAIL:vmscan_reading unexpected vmscan_reading:
actual 0 <= expected 0
check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan: actual 0 != expected -2
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan: actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

I added 'dump_stack()' in function try_to_free_mem_cgroup_pages() and run this test (#33) and didn't get any stacktrace. But I do get stacktraces due to other operations like

          try_to_free_mem_cgroup_pages+0x1fd [kernel]
          try_to_free_mem_cgroup_pages+0x1fd [kernel]
          memory_reclaim_write+0x88 [kernel]
          cgroup_file_write+0x88 [kernel]
          kernfs_fop_write_iter+0xd0 [kernel]
          vfs_write+0x2c4 [kernel]
          __x64_sys_write+0x60 [kernel]
          do_syscall_64+0x2d [kernel]
          entry_SYSCALL_64_after_hwframe+0x44 [kernel]
Quoted 3 lines

If you can show me the stacktrace about how try_to_free_mem_cgroup_pages() is triggered in your setup, I can help debug this problem in my environment.

BTW, CI also reported the test failure.
https://github.com/kernel-patches/bpf/pull/3284

For example, with gcc built kernel,
https://github.com/kernel-patches/bpf/runs/7272407890?check_suite_focus=true

The error:

Quoted 9 lines

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:PASS:vmscan_reading 0 nsec check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan:
actual 28390910 != expected 28390909
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan:
actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

Hey Yonghong,

Thanks for helping us debug this failure. I can reproduce the CI failure in my enviornment, but this failure is actually different from the failure in your environment. In your environment it looks like no stats are gathered for all cgroups (either no reclaim happening or bpf progs not being run). In the CI and in my environment, only one cgroup observes this behavior.

Quoted 4 lines

The thing is, I was able to reproduce the problem only when I ran all test_progs. When I run the selftest alone (test_progs -t cgroup_hierarchical_stats), it consistently passes, which is interesting.

I think I figured this one out (the CI failure). I set max_entries for the maps in the test to 10, because I have 1 entry per-cgroup, and I have less than 10 cgroups. When I run the test with other tests I *think* there are other cgroups that are being created, so the number exceeds 10, and some of the entries for the test cgroups cannot be created. I saw a lot of "failed to create entry for cgroup.." message in the bpf trace produced by my test, and the error turned out to be -E2BIG. I increased max_entries to 100 and it seems to be consistently passing when run with all the other tests, using both test_progs and test_progs-no_alu32.

Please find a diff attached fixing this problem and a few other nits:
- Return meaningful exit codes from the reclaimer() child process and check them in induce_vmscan().
- Make buf and path variables static in get_cgroup_vmscan_delay()
- Print error code in bpf trace when we fail to create a bpf map entry.
- Print 0 instead of -1 when we can't find a map entry, to avoid underflowing the unsigned counters in the test.

Quoted 4 lines

Let me know if this diff works or not, and if I need to send a new version with the diff or not. Also let me know if this fixes the failures that you have been seeing locally (which looked different from the CI failures).

I tried this patch and the test passed in my local environment so the diff sounds good to me.

Quoted 20 lines

Thanks!

Quoted 17 lines

Anyway, one failure at a time :) I am working on debugging the CI failure (that occurs only when all tests are run), then we'll see if fixing that fixes the problem in our environment as well.

If you have any pointers about why a test would consistently pass alone and consistently fail with others that would be good. Otherwise, I will keep you updated with any findings I reach.

Thanks again!

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
(quoted diff) +3 -0
+}
+
+static int setup_cgroup_iter(struct cgroup_hierarchical_stats *obj,

int cgroup_fd,

[...]

#27 lore raw

Re: [PATCH bpf-next v3 8/8] bpf: add a selftest for cgroup hierarchical stats collection

Quoted 210 lines · Yonghong Song
Quoted 206 lines · Yosry Ahmed
Quoted 181 lines · Yosry Ahmed
Quoted 160 lines · Yonghong Song
Quoted 144 lines · Yonghong Song
Quoted 62 lines · Yosry Ahmed

Add a selftest that tests the whole workflow for collecting, aggregating (flushing), and displaying cgroup hierarchical stats.

TL;DR:
- Userspace program creates a cgroup hierarchy and induces memcg reclaim in parts of it.
- Whenever reclaim happens, vmscan_start and vmscan_end update per-cgroup percpu readings, and tell rstat which (cgroup, cpu) pairs have updates.
- When userspace tries to read the stats, vmscan_dump calls rstat to flush
the stats, and outputs the stats in text format to userspace (similar to cgroupfs stats).
- rstat calls vmscan_flush once for every (cgroup, cpu) pair that has updates, vmscan_flush aggregates cpu readings and propagates updates to parents.
- Userspace program makes sure the stats are aggregated and read correctly.

Detailed explanation:
- The test loads tracing bpf programs, vmscan_start and vmscan_end, to measure the latency of cgroup reclaim. Per-cgroup readings are
stored in
percpu maps for efficiency. When a cgroup reading is updated on a cpu, cgroup_rstat_updated(cgroup, cpu) is called to add the cgroup to the rstat updated tree on that cpu.

- A cgroup_iter program, vmscan_dump, is loaded and pinned to a file, for each cgroup. Reading this file invokes the program, which calls cgroup_rstat_flush(cgroup) to ask rstat to propagate the updates
for all
cpus and cgroups that have updates in this cgroup's subtree.
Afterwards,
the stats are exposed to the user. vmscan_dump returns 1 to terminate iteration early, so that we only expose stats for one cgroup per read.

- An ftrace program, vmscan_flush, is also loaded and attached to bpf_rstat_flush. When rstat flushing is ongoing, vmscan_flush is
invoked
once for each (cgroup, cpu) pair that has updates. cgroups are popped from the rstat tree in a bottom-up fashion, so calls will always be made for cgroups that have updates before their parents. The program aggregates percpu readings to a total per-cgroup reading, and also propagates them to the parent cgroup. After rstat flushing is over,
all
cgroups will have correct updated hierarchical readings (including all cpus and all their descendants).

- Finally, the test creates a cgroup hierarchy and induces memcg reclaim in parts of it, and makes sure that the stats collection, aggregation, and reading workflow works as expected.

---
   .../prog_tests/cgroup_hierarchical_stats.c    | 362 ++++++++++++++++++
   .../bpf/progs/cgroup_hierarchical_stats.c     | 235 ++++++++++++
   2 files changed, 597 insertions(+)

create mode 100644
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c
create mode 100644
tools/testing/selftests/bpf/progs/cgroup_hierarchical_stats.c

[...]

Quoted 49 lines
(quoted diff) +2 -0
+
+static unsigned long long get_cgroup_vmscan_delay(unsigned long long

cgroup_id,

(quoted diff) +37 -0
+                          const char *file_name)
+{
+    char buf[128], path[128];
+    unsigned long long vmscan = 0, id = 0;
+    int err;
+
+    /* For every cgroup, read the file generated by cgroup_iter */
+    snprintf(path, 128, "%s%s", BPFFS_VMSCAN, file_name);
+    err = read_from_file(path, buf, 128);
+    if (!ASSERT_OK(err, "read cgroup_iter"))
+        return 0;
+
+    /* Check the output file formatting */
+    ASSERT_EQ(sscanf(buf, "cg_id: %llu, total_vmscan_delay: %llu\n",
+             &id, &vmscan), 2, "output format");
+
+    /* Check that the cgroup_id is displayed correctly */
+    ASSERT_EQ(id, cgroup_id, "cgroup_id");
+    /* Check that the vmscan reading is non-zero */
+    ASSERT_GT(vmscan, 0, "vmscan_reading");
+    return vmscan;
+}
+
+static void check_vmscan_stats(void)
+{
+    int i;
+    unsigned long long vmscan_readings[N_CGROUPS], vmscan_root;
+
+    for (i = 0; i < N_CGROUPS; i++)
+        vmscan_readings[i] = get_cgroup_vmscan_delay(cgroups[i].id,
+                                 cgroups[i].name);
+
+    /* Read stats for root too */
+    vmscan_root = get_cgroup_vmscan_delay(CG_ROOT_ID, CG_ROOT_NAME);
+
+    /* Check that child1 == child1_1 + child1_2 */
+    ASSERT_EQ(vmscan_readings[1], vmscan_readings[3] +

vmscan_readings[4],

(quoted diff) +3 -0
+          "child1_vmscan");
+    /* Check that child2 == child2_1 + child2_2 */
+    ASSERT_EQ(vmscan_readings[2], vmscan_readings[5] +

vmscan_readings[6],

(quoted diff) +3 -0
+          "child2_vmscan");
+    /* Check that test == child1 + child2 */
+    ASSERT_EQ(vmscan_readings[0], vmscan_readings[1] +

vmscan_readings[2],

Review

Quoted 3 lines
(quoted diff) +3 -0
+          "test_vmscan");
+    /* Check that root >= test */
+    ASSERT_GE(vmscan_root, vmscan_readings[1], "root_vmscan");

I still get a test failure with

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:FAIL:vmscan_reading unexpected vmscan_reading:
actual 0 <= expected 0
check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan: actual 0 != expected -2
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan: actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

I added 'dump_stack()' in function try_to_free_mem_cgroup_pages() and run this test (#33) and didn't get any stacktrace. But I do get stacktraces due to other operations like

          try_to_free_mem_cgroup_pages+0x1fd [kernel]
          try_to_free_mem_cgroup_pages+0x1fd [kernel]
          memory_reclaim_write+0x88 [kernel]
          cgroup_file_write+0x88 [kernel]
          kernfs_fop_write_iter+0xd0 [kernel]
          vfs_write+0x2c4 [kernel]
          __x64_sys_write+0x60 [kernel]
          do_syscall_64+0x2d [kernel]
          entry_SYSCALL_64_after_hwframe+0x44 [kernel]
Quoted 3 lines

If you can show me the stacktrace about how try_to_free_mem_cgroup_pages() is triggered in your setup, I can help debug this problem in my environment.

BTW, CI also reported the test failure.
https://github.com/kernel-patches/bpf/pull/3284

For example, with gcc built kernel,
https://github.com/kernel-patches/bpf/runs/7272407890?check_suite_focus=true

The error:

Quoted 9 lines

get_cgroup_vmscan_delay:PASS:cgroup_id 0 nsec get_cgroup_vmscan_delay:PASS:vmscan_reading 0 nsec check_vmscan_stats:FAIL:child1_vmscan unexpected child1_vmscan:
actual 28390910 != expected 28390909
check_vmscan_stats:FAIL:child2_vmscan unexpected child2_vmscan:
actual 0 != expected -2
check_vmscan_stats:PASS:test_vmscan 0 nsec check_vmscan_stats:PASS:root_vmscan 0 nsec

Hey Yonghong,

Thanks for helping us debug this failure. I can reproduce the CI failure in my enviornment, but this failure is actually different from the failure in your environment. In your environment it looks like no stats are gathered for all cgroups (either no reclaim happening or bpf progs not being run). In the CI and in my environment, only one cgroup observes this behavior.

Quoted 4 lines

The thing is, I was able to reproduce the problem only when I ran all test_progs. When I run the selftest alone (test_progs -t cgroup_hierarchical_stats), it consistently passes, which is interesting.

I think I figured this one out (the CI failure). I set max_entries for the maps in the test to 10, because I have 1 entry per-cgroup, and I have less than 10 cgroups. When I run the test with other tests I *think* there are other cgroups that are being created, so the number exceeds 10, and some of the entries for the test cgroups cannot be created. I saw a lot of "failed to create entry for cgroup.." message in the bpf trace produced by my test, and the error turned out to be -E2BIG. I increased max_entries to 100 and it seems to be consistently passing when run with all the other tests, using both test_progs and test_progs-no_alu32.

Please find a diff attached fixing this problem and a few other nits:
- Return meaningful exit codes from the reclaimer() child process and check them in induce_vmscan().
- Make buf and path variables static in get_cgroup_vmscan_delay()
- Print error code in bpf trace when we fail to create a bpf map entry.
- Print 0 instead of -1 when we can't find a map entry, to avoid underflowing the unsigned counters in the test.

Quoted 8 lines
Quoted 4 lines

Let me know if this diff works or not, and if I need to send a new version with the diff or not. Also let me know if this fixes the failures that you have been seeing locally (which looked different from the CI failures).

I tried this patch and the test passed in my local environment so the diff sounds good to me.

Awesome! Thanks so much for helping debugging this!

I will bundle this diff with Hao's cgroup_iter changes and send a v4 soon.

Quoted 20 lines
Quoted 20 lines

Thanks!

Quoted 17 lines

Anyway, one failure at a time :) I am working on debugging the CI failure (that occurs only when all tests are run), then we'll see if fixing that fixes the problem in our environment as well.

If you have any pointers about why a test would consistently pass alone and consistently fail with others that would be good. Otherwise, I will keep you updated with any findings I reach.

Thanks again!

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines
(quoted diff) +3 -0
+}
+
+static int setup_cgroup_iter(struct cgroup_hierarchical_stats *obj,

int cgroup_fd,

[...]