Skip to contentSkip to conversation

cgroup: dmem: add selftest helper, coverage, and VM runner

PATCH Superseded Albert Esteve 3 participants 14 messages Jul 6 – Aug 31

Subsystems (2)

v5 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v5 cover cgroup: dmem: add selftest helper, coverage, and VM runner

Hi all,

This small series adds practical test coverage for the dmem cgroup controller.

The motivation came from following the recent dmem API discussion in thread [1]. That discussion considered changing the dmem API and adding a new knob. Currently there are no dedicated tests covering dmem behaviour, which makes such changes riskier.

Adding selftests has an additional challenge: dmem charging paths are driver-driven today, so regression testing is harder unless a suitable driver is present in the test environment.

This series addresses that by adding:
- a kernel-side selftest helper module to trigger charge/uncharge from userspace in a controlled way,
- cgroup selftests covering dmem accounting and protection semantics (including dmem.max enforcement and byte-granularity checks),
- a virtme-based VM runner for repeatable execution of the dmem tests.

The goal is to make dmem behavior easier to validate when evolving the API and implementation, while keeping tests deterministic and driver-independent.

Thanks.

[1] - https://lore.kernel.org/all/aZoHfloupKvF2oSu@fedora/

---
Changes in v5:
- Change parse_first_region() by find_selftest_region to scan
dmem.capacity lines
- Use exact equality for limit readback, not values_close()
- Write VM tempfile to $SCRIPT_DIR
- Fix KTAP by dropping outer framing in test_dmem
- Use array for optional vng args to handle paths with spaces
- Respect O=/KBUILD_OUTPUT= when building, per bpf/vmtest.sh convention
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- Fix charged_pool leak in dmem_selftest_init()
- Replace ssh-based VM approach in vmtest-dmem.sh with vng --exec
- Add main() wrapper to vmtest-dmem.sh
- Other small fixes suggested by Sashiko
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Set charged flag on unexpected over-limit charge success.
- Add CONFIG_DMEM_SELFTEST=m to selftest config.
- Simplify -v to a boolean; single -v was a no-op.
- Unquote kernel_opt to avoid empty-string arg to vng.
- Document -b in usage() output.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Fix debugfs_create_dir() error check
- Fix module teardown race: call dmem_selftest_remove() before
uncharging so debugfs files are torn down
- Use IS_ERR_OR_NULL() in selftest() sanity check
- Add CONFIG_CGROUP_DMEM=y to the cgroup selftest config
- Replace config-file parsing in check_guest_requirements() with
a direct check of /sys/fs/cgroup/cgroup.controllers
- Add new patch 4 (from Eric Chanudet): vmtest-dmem.sh -b flag
to configure and build a local kernel tree
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Albert Esteve (4):
cgroup: Add dmem_selftest module
selftests: cgroup: Add dmem selftest coverage
selftests: cgroup: Add vmtest-dmem runner script
selftests: cgroup: handle vmtest-dmem -b to test locally built kernel

 init/Kconfig                                  |  12 +
 kernel/cgroup/Makefile                        |   1 +
 kernel/cgroup/dmem_selftest.c                 | 198 +++++++++++
 tools/testing/selftests/cgroup/.gitignore     |   1 +
 tools/testing/selftests/cgroup/Makefile       |   4 +-
 tools/testing/selftests/cgroup/config         |   2 +
 tools/testing/selftests/cgroup/test_dmem.c    | 486 ++++++++++++++++++++++++++
 tools/testing/selftests/cgroup/vmtest-dmem.sh | 188 ++++++++++
 8 files changed, 891 insertions(+), 1 deletion(-)

---
base-commit: 8cdeaa50eae8dad34885515f62559ee83e7e8dda
change-id: 20260318-kunit_cgroups-7fb0b9e64017

Best regards,

Signature · 1 line
Albert Esteve <[email protected]>
#1 lore raw

PATCH v5 1/4 cgroup: Add dmem_selftest module

Currently, dmem charging is driver-driven through direct calls to dmem_cgroup_try_charge(), so cgroup selftests do not have a generic way to trigger charge and uncharge paths from userspace.

This limits any selftest coverage to configuration/readout checks unless a specific driver exposing charge hooks is present in the test environment.

Add kernel/cgroup/dmem_selftest.c as a helper module (CONFIG_DMEM_SELFTEST) that registers a synthetic dmem region (dmem_selftest) and exposes debugfs control files:
/sys/kernel/debug/dmem_selftest/charge /sys/kernel/debug/dmem_selftest/uncharge

Writing a size to charge triggers dmem_cgroup_try_charge() for the calling task's cgroup (the module calls kstrtou64()). Writing to uncharge releases the outstanding charge via dmem_cgroup_uncharge(). Only a single outstanding charge is supported.

This provides a deterministic, driver-independent mechanism for exercising dmem accounting paths in selftests.

---
 init/Kconfig                  |  12 +++
 kernel/cgroup/Makefile        |   1 +
 kernel/cgroup/dmem_selftest.c | 198 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 211 insertions(+)
init/Kconfig +12 -0
index 5230d4879b1c8..6fab65d6b44ea 100644
@@ -1267,6 +1267,18 @@ config CGROUP_DMEM
 	  As an example, it allows you to restrict VRAM usage for applications
 	  in the DRM subsystem.
 
+config DMEM_SELFTEST
+	tristate "dmem cgroup selftest helper module"
+	depends on CGROUP_DMEM && DEBUG_FS
+	default n
+	help
+	  Builds a small loadable module that registers a dmem region named
+	  "dmem_selftest" and exposes debugfs files under
+	  /sys/kernel/debug/dmem_selftest/ so kselftests can trigger
+	  dmem charge/uncharge operations from userspace.
+
+	  Say N unless you run dmem selftests or develop the dmem controller.
+
 config CGROUP_FREEZER
 	bool "Freezer controller"
 	help
kernel/cgroup/Makefile +1 -0
index ede31601a363a..febc36e60f9f9 100644
@@ -8,4 +8,5 @@ obj-$(CONFIG_CPUSETS) += cpuset.o
 obj-$(CONFIG_CPUSETS_V1) += cpuset-v1.o
 obj-$(CONFIG_CGROUP_MISC) += misc.o
 obj-$(CONFIG_CGROUP_DMEM) += dmem.o
+obj-$(CONFIG_DMEM_SELFTEST) += dmem_selftest.o
 obj-$(CONFIG_CGROUP_DEBUG) += debug.o
kernel/cgroup/dmem_selftest.c new file +198 -0

198 lines not on this page · raw message

Signature · 1 line
2.54.0
Reviewed-by on v5 1/4
#2 lore raw

Re: [PATCH v5 1/4] cgroup: Add dmem_selftest module

Quoted 21 lines · Albert Esteve

Currently, dmem charging is driver-driven through direct calls to dmem_cgroup_try_charge(), so cgroup selftests do not have a generic way to trigger charge and uncharge paths from userspace.

This limits any selftest coverage to configuration/readout checks unless a specific driver exposing charge hooks is present in the test environment.

Add kernel/cgroup/dmem_selftest.c as a helper module (CONFIG_DMEM_SELFTEST) that registers a synthetic dmem region (dmem_selftest) and exposes debugfs control files:
/sys/kernel/debug/dmem_selftest/charge /sys/kernel/debug/dmem_selftest/uncharge

Writing a size to charge triggers dmem_cgroup_try_charge() for the calling task's cgroup (the module calls kstrtou64()). Writing to uncharge releases the outstanding charge via dmem_cgroup_uncharge(). Only a single outstanding charge is supported.

Quoted 4 lines

This provides a deterministic, driver-independent mechanism for exercising dmem accounting paths in selftests.

Signature · 1 line
Eric Chanudet
maintainer
#3 lore raw

Re: [PATCH v5 1/4] cgroup: Add dmem_selftest module

In reply to Albert Esteve
Quoted 8 lines · Albert Esteve

Currently, dmem charging is driver-driven through direct calls to dmem_cgroup_try_charge(), so cgroup selftests do not have a generic way to trigger charge and uncharge paths from userspace.

This limits any selftest coverage to configuration/readout checks unless a specific driver exposing charge hooks is present in the test environment.

What about that
drivers/gpu/drm/ttm/tests/ttm_resource_test.c
?

Quoted 6 lines

Add kernel/cgroup/dmem_selftest.c as a helper module (CONFIG_DMEM_SELFTEST) that registers a synthetic dmem region (dmem_selftest) and exposes debugfs control files:
/sys/kernel/debug/dmem_selftest/charge /sys/kernel/debug/dmem_selftest/uncharge

Nit: I'd think about alloc and free (to denote meaning not how it's implemented).

Quoted 26 lines

Writing a size to charge triggers dmem_cgroup_try_charge() for the calling task's cgroup (the module calls kstrtou64()). Writing to uncharge releases the outstanding charge via dmem_cgroup_uncharge(). Only a single outstanding charge is supported.

This provides a deterministic, driver-independent mechanism for exercising dmem accounting paths in selftests.

---
 init/Kconfig                  |  12 +++
 kernel/cgroup/Makefile        |   1 +
 kernel/cgroup/dmem_selftest.c | 198 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 211 insertions(+)
init/Kconfig +1 -0
index 5230d4879b1c8..6fab65d6b44ea 100644
@@ -1267,6 +1267,18 @@ config CGROUP_DMEM
 	  As an example, it allows you to restrict VRAM usage for applications
 	  in the DRM subsystem.
 
+config DMEM_SELFTEST

init/Kconfig config CGROUP_DMEM · line 1280

Quoted 10 lines
init/Kconfig +10 -0
+	tristate "dmem cgroup selftest helper module"
+	depends on CGROUP_DMEM && DEBUG_FS
+	default n
+	help
+	  Builds a small loadable module that registers a dmem region named
+	  "dmem_selftest" and exposes debugfs files under
+	  /sys/kernel/debug/dmem_selftest/ so kselftests can trigger
+	  dmem charge/uncharge operations from userspace.
+
+	  Say N unless you run dmem selftests or develop the dmem controller.

Could this be made w/out introduciton of a new Kconfig option? (E.g. what tools/testing/selftests/livepatch/test_modules/Makefile does)

(Maybe reword to insmod if you choose building the test module as OOT.)

init/Kconfig config CGROUP_DMEM · line 1281

Quoted 1 line
init/Kconfig +1 -0
+static int __init dmem_selftest_register(void)

Just an idea to reduce the amount debugfs of boilerplage -- the testing args could be handled by module_param_cb().

Quoted 1 line
init/Kconfig +1 -0
+static int __init dmem_selftest_init(void)

...

init/Kconfig

Quoted 1 line
init/Kconfig +1 -0
+	add_taint(TAINT_TEST, LOCKDEP_STILL_OK);

Great!

#4 lore raw

Re: [PATCH v5 1/4] cgroup: Add dmem_selftest module

Quoted 7 lines · Michal Koutný
Quoted 5 lines · Albert Esteve

Currently, dmem charging is driver-driven through direct calls to dmem_cgroup_try_charge(), so cgroup selftests do not have a generic way to trigger charge and uncharge paths from userspace.

Quoted 7 lines
Quoted 3 lines

This limits any selftest coverage to configuration/readout checks unless a specific driver exposing charge hooks is present in the test environment.

What about that
drivers/gpu/drm/ttm/tests/ttm_resource_test.c
?

But that test does not set up a dmem region (man->cg == NULL), so ttm_resource_try_charge is a no-op. Even if we add a region there, it would not exercise nested dmem.{max,min,low} from userspace as intended here. But I can reword the message to avoid sounding like there is no in-kernel coverage whatsoever.

Quoted 10 lines
Quoted 7 lines

Add kernel/cgroup/dmem_selftest.c as a helper module (CONFIG_DMEM_SELFTEST) that registers a synthetic dmem region (dmem_selftest) and exposes debugfs control files:
/sys/kernel/debug/dmem_selftest/charge /sys/kernel/debug/dmem_selftest/uncharge

Nit: I'd think about alloc and free (to denote meaning not how it's implemented).

Works for me. I'll change the naming for the next version.

Quoted 41 lines
Quoted 27 lines

Writing a size to charge triggers dmem_cgroup_try_charge() for the calling task's cgroup (the module calls kstrtou64()). Writing to uncharge releases the outstanding charge via dmem_cgroup_uncharge(). Only a single outstanding charge is supported.

This provides a deterministic, driver-independent mechanism for exercising dmem accounting paths in selftests.

---
 init/Kconfig                  |  12 +++
 kernel/cgroup/Makefile        |   1 +
 kernel/cgroup/dmem_selftest.c | 198 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 211 insertions(+)
init/Kconfig +1 -0
index 5230d4879b1c8..6fab65d6b44ea 100644
@@ -1267,6 +1267,18 @@ config CGROUP_DMEM
        As an example, it allows you to restrict VRAM usage for applications
        in the DRM subsystem.
 
+config DMEM_SELFTEST

init/Kconfig config CGROUP_DMEM · line 1280

Quoted 10 lines
init/Kconfig +10 -0
+     tristate "dmem cgroup selftest helper module"
+     depends on CGROUP_DMEM && DEBUG_FS
+     default n
+     help
+       Builds a small loadable module that registers a dmem region named
+       "dmem_selftest" and exposes debugfs files under
+       /sys/kernel/debug/dmem_selftest/ so kselftests can trigger
+       dmem charge/uncharge operations from userspace.
+
+       Say N unless you run dmem selftests or develop the dmem controller.

Could this be made w/out introduciton of a new Kconfig option? (E.g. what tools/testing/selftests/livepatch/test_modules/Makefile does)

Quoted 1 line

(Maybe reword to insmod if you choose building the test module as OOT.)

Ah, nice example. I'll drop the CONFIG_DMEM_SELFTEST and have the helper module as OOT.

Quoted 5 lines

init/Kconfig config CGROUP_DMEM · line 1281

Quoted 2 lines
init/Kconfig +1 -0
+static int __init dmem_selftest_register(void)

Just an idea to reduce the amount debugfs of boilerplage -- the testing args could be handled by module_param_cb().

Ok, I'll switch to module parameters and drop the debugfs boilerplate and DEBUG_FS dependency.

BR,
Albert

Quoted 7 lines
Quoted 2 lines
init/Kconfig +1 -0
+static int __init dmem_selftest_init(void)

...

Quoted 1 line

+ add_taint(TAINT_TEST, LOCKDEP_STILL_OK);

Great!

#5 lore raw

PATCH v5 2/4 selftests: cgroup: Add dmem selftest coverage

In reply to Albert Esteve

Currently, tools/testing/selftests/cgroup/ does not include a dmem-specific test binary. This leaves dmem charge and limit behavior largely unvalidated in kselftest coverage.

Add test_dmem and wire it into the cgroup selftests Makefile. The new test exercises dmem controller behavior through the dmem_selftest debugfs interface for the dmem_selftest region.

The test adds three complementary checks:
- test_dmem_max creates a nested hierarchy with per-leaf dmem.max values and verifies that over-limit charges fail while in-limit charges succeed in dmem.current.
- test_dmem_min and test_dmem_low verify that charging from a cgroup with the corresponding protection knob set updates dmem.current as expected.
- test_dmem_charge_byte_granularity validates accounting bounds for non-page-aligned charge sizes and uncharge-to-zero behavior.

This provides deterministic userspace coverage for dmem accounting and hard-limit enforcement using a test helper module, without requiring subsystem-specific production drivers.

---
 tools/testing/selftests/cgroup/.gitignore  |   1 +
 tools/testing/selftests/cgroup/Makefile    |   2 +
 tools/testing/selftests/cgroup/config      |   2 +
 tools/testing/selftests/cgroup/test_dmem.c | 486 +++++++++++++++++++++++++++++
 4 files changed, 491 insertions(+)
tools/testing/selftests/cgroup/.gitignore +1 -0
index 952e4448bf070..ea2322598217d 100644
@@ -2,6 +2,7 @@
 test_core
 test_cpu
 test_cpuset
+test_dmem
 test_freezer
 test_hugetlb_memcg
 test_kill
tools/testing/selftests/cgroup/Makefile +2 -0
index e01584c2189ac..e1a5e9316620e 100644
@@ -10,6 +10,7 @@ TEST_GEN_FILES := wait_inotify
 TEST_GEN_PROGS  = test_core
 TEST_GEN_PROGS += test_cpu
 TEST_GEN_PROGS += test_cpuset
+TEST_GEN_PROGS += test_dmem
 TEST_GEN_PROGS += test_freezer
 TEST_GEN_PROGS += test_hugetlb_memcg
 TEST_GEN_PROGS += test_kill
@@ -26,6 +27,7 @@ include lib/libcgroup.mk
 $(OUTPUT)/test_core: $(LIBCGROUP_O)
 $(OUTPUT)/test_cpu: $(LIBCGROUP_O)
 $(OUTPUT)/test_cpuset: $(LIBCGROUP_O)
+$(OUTPUT)/test_dmem: $(LIBCGROUP_O)
 $(OUTPUT)/test_freezer: $(LIBCGROUP_O)
 $(OUTPUT)/test_hugetlb_memcg: $(LIBCGROUP_O)
 $(OUTPUT)/test_kill: $(LIBCGROUP_O)
tools/testing/selftests/cgroup/config +2 -0
index 39f979690dd3b..5728278310a31 100644
@@ -1,6 +1,8 @@
 CONFIG_CGROUPS=y
 CONFIG_CGROUP_CPUACCT=y
+CONFIG_CGROUP_DMEM=y
 CONFIG_CGROUP_FREEZER=y
 CONFIG_CGROUP_SCHED=y
+CONFIG_DMEM_SELFTEST=m
 CONFIG_MEMCG=y
 CONFIG_PAGE_COUNTER=y
tools/testing/selftests/cgroup/test_dmem.c new file +486 -0

486 lines not on this page · raw message

Signature · 1 line
2.54.0
Reviewed-by on v5 2/4
#6 lore raw

Re: [PATCH v5 2/4] selftests: cgroup: Add dmem selftest coverage

Quoted 19 lines · Albert Esteve

Currently, tools/testing/selftests/cgroup/ does not include a dmem-specific test binary. This leaves dmem charge and limit behavior largely unvalidated in kselftest coverage.

Add test_dmem and wire it into the cgroup selftests Makefile. The new test exercises dmem controller behavior through the dmem_selftest debugfs interface for the dmem_selftest region.

The test adds three complementary checks:
- test_dmem_max creates a nested hierarchy with per-leaf dmem.max values and verifies that over-limit charges fail while in-limit charges succeed in dmem.current.
- test_dmem_min and test_dmem_low verify that charging from a cgroup with the corresponding protection knob set updates dmem.current as expected.
- test_dmem_charge_byte_granularity validates accounting bounds for non-page-aligned charge sizes and uncharge-to-zero behavior.

Quoted 6 lines

This provides deterministic userspace coverage for dmem accounting and hard-limit enforcement using a test helper module, without requiring subsystem-specific production drivers.

Signature · 1 line
Eric Chanudet
maintainer
#7 lore raw

Re: [PATCH v5 2/4] selftests: cgroup: Add dmem selftest coverage

In reply to Albert Esteve

tools/testing/selftests/cgroup/test_dmem.c line 63

Quoted 2 lines · Albert Esteve
tools/testing/selftests/cgroup/test_dmem.c new file +2 -0
+static long long dmem_read_limit_for_region(const char *cgroup, const char *ctrl,
+					    const char *region_name)

This should be replaceable with lib/cgroup_util.c:cg_read_key_long()

Quoted 72 lines
tools/testing/selftests/cgroup/test_dmem.c new file +72 -0
+{
+	char buf[4096];
+	char *line, *saveptr = NULL;
+	char fname[256];
+	char fval[64];
+
+	if (cg_read(cgroup, ctrl, buf, sizeof(buf)) < 0)
+		return -2;
+
+	for (line = strtok_r(buf, "\n", &saveptr); line;
+	     line = strtok_r(NULL, "\n", &saveptr)) {
+		if (!line[0])
+			continue;
+		if (sscanf(line, "%255s %63s", fname, fval) != 2)
+			continue;
+		if (strcmp(fname, region_name))
+			continue;
+		if (!strcmp(fval, "max"))
+			return -1;
+		return strtoll(fval, NULL, 0);
+	}
+	return -2;
+}
+
+static long long dmem_read_limit(const char *cgroup, const char *ctrl)
+{
+	return dmem_read_limit_for_region(cgroup, ctrl, DM_SELFTEST_REGION);
+}
+
+static int dmem_write_limit(const char *cgroup, const char *ctrl,
+			    const char *val)
+{
+	char wr[512];
+
+	snprintf(wr, sizeof(wr), "%s %s", DM_SELFTEST_REGION, val);
+	return cg_write(cgroup, ctrl, wr);
+}
+
+static int dmem_selftest_charge_bytes(unsigned long long bytes)
+{
+	char wr[32];
+
+	snprintf(wr, sizeof(wr), "%llu", bytes);
+	return write_text(DM_SELFTEST_CHARGE, wr, strlen(wr));
+}
+
+static int dmem_selftest_uncharge(void)
+{
+	return write_text(DM_SELFTEST_UNCHARGE, "\n", 1);
+}
+
+/*
+ * First, this test creates the following hierarchy:
+ * A
+ * A/B     dmem.max=1M
+ * A/B/C   dmem.max=75K
+ * A/B/D   dmem.max=25K
+ * A/B/E   dmem.max=8K
+ * A/B/F   dmem.max=0
+ *
+ * Then for each leaf cgroup it tries to charge above dmem.max
+ * and expects the charge request to fail and dmem.current to
+ * remain unchanged.
+ *
+ * For leaves with non-zero dmem.max, it additionally charges a
+ * smaller amount and verifies accounting grows within one PAGE_SIZE
+ * rounding bound, then uncharges and verifies dmem.current returns
+ * to the previous value.
+ *
+ */
+static int test_dmem_max(const char *root)
+{

tools/testing/selftests/cgroup/test_dmem.c line 145

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+	static const char * const leaf_max[] = { "75K", "25K", "8K", "0" };
+	static const unsigned long long fail_sz[] = {
+		(75ULL * 1024ULL) + 1ULL,
+		(25ULL * 1024ULL) + 1ULL,
+		(8ULL * 1024ULL) + 1ULL,
+		1ULL
+	};
+	static const unsigned long long pass_sz[] = {
+		4096ULL, 4096ULL, 4096ULL, 0ULL
+	};

Possibly those could be signed (to save the casts down below).

tools/testing/selftests/cgroup/test_dmem.c line 150

Quoted 5 lines
tools/testing/selftests/cgroup/test_dmem.c new file +5 -0
+	char *parent[2] = {NULL};
+	char *children[4] = {NULL};
+	unsigned long long cap;
+	long long page_size;
+	long long cur_before, cur_after;

Just long should be fine (with gcc).

Quoted 27 lines
tools/testing/selftests/cgroup/test_dmem.c new file +27 -0
+	int ret = KSFT_FAIL;
+	int charged = 0;
+	int in_child = 0;
+	long long v;
+	int i;
+
+	if (access(DM_SELFTEST_CHARGE, W_OK) != 0)
+		return KSFT_SKIP;
+
+	if (find_selftest_region(root, &cap) != 1)
+		return KSFT_SKIP;
+
+	page_size = sysconf(_SC_PAGESIZE);
+	if (page_size <= 0)
+		goto cleanup;
+
+	parent[0] = cg_name(root, "dmem_prot_0");
+	if (!parent[0])
+		goto cleanup;
+
+	parent[1] = cg_name(parent[0], "dmem_prot_1");
+	if (!parent[1])
+		goto cleanup;
+
+	if (cg_create(parent[0]))
+		goto cleanup;
+

tools/testing/selftests/cgroup/test_dmem.c line 187

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+	if (cg_write(parent[0], "cgroup.subtree_control", "+dmem"))
+		goto cleanup;
+
+	if (cg_create(parent[1]))
+		goto cleanup;
+
+	if (cg_write(parent[1], "cgroup.subtree_control", "+dmem"))
+		goto cleanup;
+
+	for (i = 0; i < 4; i++) {
	for (i = 0; i < ARRAY_SIZE(children); i++) {

tools/testing/selftests/cgroup/test_dmem.c line 197

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+		children[i] = cg_name_indexed(parent[1], "dmem_child", i);
+		if (!children[i])
+			goto cleanup;
+		if (cg_create(children[i]))
+			goto cleanup;
+	}
+
+	if (dmem_write_limit(parent[1], "dmem.max", "1M"))
+		goto cleanup;
+	for (i = 0; i < 4; i++)
	for (i = 0; i < ARRAY_SIZE(children); i++) {

tools/testing/selftests/cgroup/test_dmem.c line 202

Quoted 5 lines
tools/testing/selftests/cgroup/test_dmem.c new file +5 -0
+		if (dmem_write_limit(children[i], "dmem.max", leaf_max[i]))
+			goto cleanup;
+
+	v = dmem_read_limit(parent[1], "dmem.max");
+	if (v != 1024LL * 1024LL)

This...

tools/testing/selftests/cgroup/test_dmem.c line 205

Quoted 3 lines
tools/testing/selftests/cgroup/test_dmem.c new file +3 -0
+		goto cleanup;
+	v = dmem_read_limit(children[0], "dmem.max");
+	if (v != 75LL * 1024LL)

...and these literals would be nicer with MB() macro and possibly added similar KB() macro.

tools/testing/selftests/cgroup/test_dmem.c line 217

Quoted 12 lines
tools/testing/selftests/cgroup/test_dmem.c new file +12 -0
+		goto cleanup;
+	v = dmem_read_limit(children[1], "dmem.max");
+	if (v != 25LL * 1024LL)
+		goto cleanup;
+	v = dmem_read_limit(children[2], "dmem.max");
+	if (v != 8LL * 1024LL)
+		goto cleanup;
+	v = dmem_read_limit(children[3], "dmem.max");
+	if (v != 0)
+		goto cleanup;
+
+	for (i = 0; i < 4; i++) {
	for (i = 0; i < ARRAY_SIZE(children); i++) {

(to avoid unnamed non-trivial constant)

Quoted 40 lines
tools/testing/selftests/cgroup/test_dmem.c new file +40 -0
+		if (cg_enter_current(children[i]))
+			goto cleanup;
+		in_child = 1;
+
+		cur_before = dmem_read_limit(children[i], "dmem.current");
+		if (cur_before < 0)
+			goto cleanup;
+
+		if (dmem_selftest_charge_bytes(fail_sz[i]) >= 0) {
+			charged = 1;
+			goto cleanup;
+		}
+
+		cur_after = dmem_read_limit(children[i], "dmem.current");
+		if (cur_after != cur_before)
+			goto cleanup;
+
+		if (pass_sz[i] > 0) {
+			if (dmem_selftest_charge_bytes(pass_sz[i]) < 0)
+				goto cleanup;
+			charged = 1;
+
+			cur_after = dmem_read_limit(children[i], "dmem.current");
+			if (cur_after < cur_before + (long long)pass_sz[i])
+				goto cleanup;
+			if (cur_after > cur_before + (long long)pass_sz[i] + page_size)
+				goto cleanup;
+
+			if (dmem_selftest_uncharge() < 0)
+				goto cleanup;
+			charged = 0;
+
+			cur_after = dmem_read_limit(children[i], "dmem.current");
+			if (cur_after != cur_before)
+				goto cleanup;
+		}
+
+		if (cg_enter_current(root))
+			goto cleanup;
+		in_child = 0;

tools/testing/selftests/cgroup/test_dmem.c line 267

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+	}
+
+	ret = KSFT_PASS;
+
+cleanup:
+	if (charged)
+		dmem_selftest_uncharge();
+	if (in_child)
+		cg_enter_current(root);
+	for (i = 3; i >= 0; i--) {

ditto with ARRAY_SIZE

tools/testing/selftests/cgroup/test_dmem.c line 273

Quoted 6 lines
tools/testing/selftests/cgroup/test_dmem.c new file +6 -0
+		if (!children[i])
+			continue;
+		cg_destroy(children[i]);
+		free(children[i]);
+	}
+	for (i = 1; i >= 0; i--) {

ditto with ARRAY_SIZE

tools/testing/selftests/cgroup/test_dmem.c line 285

Quoted 12 lines
tools/testing/selftests/cgroup/test_dmem.c new file +12 -0
+		if (!parent[i])
+			continue;
+		cg_destroy(parent[i]);
+		free(parent[i]);
+	}
+	return ret;
+}
+
+/*
+ * This test sets dmem.min and dmem.low on a child cgroup, then charge
+ * from that context and verify dmem.current tracks the charged bytes
+ * (within one page rounding).

I don't know, this doesn't test much of the .min nor .low protection, and the .current tracking is already tested by the above. I'd drop it for now.

Quoted 72 lines

+ */

tools/testing/selftests/cgroup/test_dmem.c new file +71 -0
+static int test_dmem_charge_with_attr(const char *root, bool min)
+{
+	unsigned long long cap;
+	const unsigned long long charge_sz = 12345ULL;
+	const char *attribute = min ? "dmem.min" : "dmem.low";
+	int ret = KSFT_FAIL;
+	char *cg = NULL;
+	long long cur;
+	long long page_size;
+	int charged = 0;
+	int in_child = 0;
+
+	if (access(DM_SELFTEST_CHARGE, W_OK) != 0)
+		return KSFT_SKIP;
+
+	if (find_selftest_region(root, &cap) != 1)
+		return KSFT_SKIP;
+
+	page_size = sysconf(_SC_PAGESIZE);
+	if (page_size <= 0)
+		goto cleanup;
+
+	cg = cg_name(root, "test_dmem_attr");
+	if (!cg)
+		goto cleanup;
+
+	if (cg_create(cg))
+		goto cleanup;
+
+	if (cg_enter_current(cg))
+		goto cleanup;
+	in_child = 1;
+
+	if (dmem_write_limit(cg, attribute, "16K"))
+		goto cleanup;
+
+	if (dmem_selftest_charge_bytes(charge_sz) < 0)
+		goto cleanup;
+	charged = 1;
+
+	cur = dmem_read_limit(cg, "dmem.current");
+	if (cur < (long long)charge_sz)
+		goto cleanup;
+	if (cur > (long long)charge_sz + page_size)
+		goto cleanup;
+
+	if (dmem_selftest_uncharge() < 0)
+		goto cleanup;
+	charged = 0;
+
+	cur = dmem_read_limit(cg, "dmem.current");
+	if (cur != 0)
+		goto cleanup;
+
+	ret = KSFT_PASS;
+
+cleanup:
+	if (charged)
+		dmem_selftest_uncharge();
+	if (in_child)
+		cg_enter_current(root);
+	cg_destroy(cg);
+	free(cg);
+	return ret;
+}
+
+static int test_dmem_min(const char *root)
+{
+	return test_dmem_charge_with_attr(root, true);
+}
+

tools/testing/selftests/cgroup/test_dmem.c line 367

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+static int test_dmem_low(const char *root)
+{
+	return test_dmem_charge_with_attr(root, false);
+}
+
+/*
+ * This test charges non-page-aligned byte sizes and verify dmem.current
+ * stays consistent: it must account at least the requested bytes and
+ * never exceed one kernel page of rounding overhead. Then uncharge must
+ * return usage to 0.

The lower bound makes sense. Could you explain more about the upper bound and granularity? That applies only for the test module or is that intended constraint for any dmem-charging driver?

Quoted 100 lines

+ */

tools/testing/selftests/cgroup/test_dmem.c new file +99 -0
+static int test_dmem_charge_byte_granularity(const char *root)
+{
+	static const unsigned long long sizes[] = { 1ULL, 4095ULL, 4097ULL, 12345ULL };
+	char *cg = NULL;
+	unsigned long long cap;
+	long long cur;
+	long long page_size;
+	int ret = KSFT_FAIL;
+	int charged = 0;
+	int in_child = 0;
+	size_t i;
+
+	if (access(DM_SELFTEST_CHARGE, W_OK) != 0)
+		return KSFT_SKIP;
+
+	if (find_selftest_region(root, &cap) != 1)
+		return KSFT_SKIP;
+
+	page_size = sysconf(_SC_PAGESIZE);
+	if (page_size <= 0)
+		goto cleanup;
+
+	cg = cg_name(root, "dmem_dbg_byte_gran");
+	if (!cg)
+		goto cleanup;
+
+	if (cg_create(cg))
+		goto cleanup;
+
+	if (dmem_write_limit(cg, "dmem.max", "8M"))
+		goto cleanup;
+
+	if (cg_enter_current(cg))
+		goto cleanup;
+	in_child = 1;
+
+	for (i = 0; i < ARRAY_SIZE(sizes); i++) {
+		if (dmem_selftest_charge_bytes(sizes[i]) < 0)
+			goto cleanup;
+		charged = 1;
+
+		cur = dmem_read_limit(cg, "dmem.current");
+		if (cur < (long long)sizes[i])
+			goto cleanup;
+		if (cur > (long long)sizes[i] + page_size)
+			goto cleanup;
+
+		if (dmem_selftest_uncharge() < 0)
+			goto cleanup;
+		charged = 0;
+
+		cur = dmem_read_limit(cg, "dmem.current");
+		if (cur != 0)
+			goto cleanup;
+	}
+
+	ret = KSFT_PASS;
+
+cleanup:
+	if (charged)
+		dmem_selftest_uncharge();
+	if (in_child)
+		cg_enter_current(root);
+	if (cg) {
+		cg_destroy(cg);
+		free(cg);
+	}
+	return ret;
+}
+
+#define T(x) { x, #x }
+struct dmem_test {
+	int (*fn)(const char *root);
+	const char *name;
+} tests[] = {
+	T(test_dmem_max),
+	T(test_dmem_min),
+	T(test_dmem_low),
+	T(test_dmem_charge_byte_granularity),
+};
+#undef T
+
+int main(int argc, char **argv)
+{
+	char root[PATH_MAX];
+	int i;
+
+	ksft_print_header();
+	ksft_set_plan(ARRAY_SIZE(tests));
+
+	if (cg_find_unified_root(root, sizeof(root), NULL))
+		ksft_exit_skip("cgroup v2 isn't mounted\n");
+
+	if (cg_read_strstr(root, "cgroup.controllers", "dmem"))
+		ksft_exit_skip("dmem controller isn't available (CONFIG_CGROUP_DMEM?)\n");
+
+	if (cg_read_strstr(root, "cgroup.subtree_control", "dmem"))
+		if (cg_write(root, "cgroup.subtree_control", "+dmem"))
+			ksft_exit_skip("Failed to enable dmem controller\n");

tools/testing/selftests/cgroup/test_dmem.c line 477

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+
+	for (i = 0; i < ARRAY_SIZE(tests); i++) {
+		switch (tests[i].fn(root)) {
+		case KSFT_PASS:
+			ksft_test_result_pass("%s\n", tests[i].name);
+			break;
+		case KSFT_SKIP:
+			ksft_test_result_skip(
+				"%s (need CONFIG_DMEM_SELFTEST, modprobe dmem_selftest)\n",
+				tests[i].name);

I'm worried that the KSFT_SKIP from a subtest might be too broad for the modprobe prompt.
Perhaps you can check it by stat'ing DM_SELFTEST_CHARGE before any subtests start?

Quoted 13 lines
tools/testing/selftests/cgroup/test_dmem.c new file +9 -0
+			break;
+		default:
+			ksft_test_result_fail("%s\n", tests[i].name);
+			break;
+		}
+	}
+
+	ksft_finished();
+}
Signature · 2 lines
-- 
2.54.0
#8 lore raw

Re: [PATCH v5 2/4] selftests: cgroup: Add dmem selftest coverage

Quoted 6 lines · Michal Koutný

tools/testing/selftests/cgroup/test_dmem.c line 63

Quoted 2 lines · Albert Esteve
tools/testing/selftests/cgroup/test_dmem.c new file +2 -0
+static long long dmem_read_limit_for_region(const char *cgroup, const char *ctrl,
+                                         const char *region_name)

This should be replaceable with lib/cgroup_util.c:cg_read_key_long()

True. I'll take care of it.

Quoted 232 lines
Quoted 73 lines
tools/testing/selftests/cgroup/test_dmem.c new file +72 -0
+{
+     char buf[4096];
+     char *line, *saveptr = NULL;
+     char fname[256];
+     char fval[64];
+
+     if (cg_read(cgroup, ctrl, buf, sizeof(buf)) < 0)
+             return -2;
+
+     for (line = strtok_r(buf, "\n", &saveptr); line;
+          line = strtok_r(NULL, "\n", &saveptr)) {
+             if (!line[0])
+                     continue;
+             if (sscanf(line, "%255s %63s", fname, fval) != 2)
+                     continue;
+             if (strcmp(fname, region_name))
+                     continue;
+             if (!strcmp(fval, "max"))
+                     return -1;
+             return strtoll(fval, NULL, 0);
+     }
+     return -2;
+}
+
+static long long dmem_read_limit(const char *cgroup, const char *ctrl)
+{
+     return dmem_read_limit_for_region(cgroup, ctrl, DM_SELFTEST_REGION);
+}
+
+static int dmem_write_limit(const char *cgroup, const char *ctrl,
+                         const char *val)
+{
+     char wr[512];
+
+     snprintf(wr, sizeof(wr), "%s %s", DM_SELFTEST_REGION, val);
+     return cg_write(cgroup, ctrl, wr);
+}
+
+static int dmem_selftest_charge_bytes(unsigned long long bytes)
+{
+     char wr[32];
+
+     snprintf(wr, sizeof(wr), "%llu", bytes);
+     return write_text(DM_SELFTEST_CHARGE, wr, strlen(wr));
+}
+
+static int dmem_selftest_uncharge(void)
+{
+     return write_text(DM_SELFTEST_UNCHARGE, "\n", 1);
+}
+
+/*
+ * First, this test creates the following hierarchy:
+ * A
+ * A/B     dmem.max=1M
+ * A/B/C   dmem.max=75K
+ * A/B/D   dmem.max=25K
+ * A/B/E   dmem.max=8K
+ * A/B/F   dmem.max=0
+ *
+ * Then for each leaf cgroup it tries to charge above dmem.max
+ * and expects the charge request to fail and dmem.current to
+ * remain unchanged.
+ *
+ * For leaves with non-zero dmem.max, it additionally charges a
+ * smaller amount and verifies accounting grows within one PAGE_SIZE
+ * rounding bound, then uncharges and verifies dmem.current returns
+ * to the previous value.
+ *
+ */
+static int test_dmem_max(const char *root)
+{

tools/testing/selftests/cgroup/test_dmem.c line 145

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+     static const char * const leaf_max[] = { "75K", "25K", "8K", "0" };
+     static const unsigned long long fail_sz[] = {
+             (75ULL * 1024ULL) + 1ULL,
+             (25ULL * 1024ULL) + 1ULL,
+             (8ULL * 1024ULL) + 1ULL,
+             1ULL
+     };
+     static const unsigned long long pass_sz[] = {
+             4096ULL, 4096ULL, 4096ULL, 0ULL
+     };

Possibly those could be signed (to save the casts down below).

tools/testing/selftests/cgroup/test_dmem.c line 150

Quoted 5 lines
tools/testing/selftests/cgroup/test_dmem.c new file +5 -0
+     char *parent[2] = {NULL};
+     char *children[4] = {NULL};
+     unsigned long long cap;
+     long long page_size;
+     long long cur_before, cur_after;

Just long should be fine (with gcc).

Quoted 27 lines
tools/testing/selftests/cgroup/test_dmem.c new file +27 -0
+     int ret = KSFT_FAIL;
+     int charged = 0;
+     int in_child = 0;
+     long long v;
+     int i;
+
+     if (access(DM_SELFTEST_CHARGE, W_OK) != 0)
+             return KSFT_SKIP;
+
+     if (find_selftest_region(root, &cap) != 1)
+             return KSFT_SKIP;
+
+     page_size = sysconf(_SC_PAGESIZE);
+     if (page_size <= 0)
+             goto cleanup;
+
+     parent[0] = cg_name(root, "dmem_prot_0");
+     if (!parent[0])
+             goto cleanup;
+
+     parent[1] = cg_name(parent[0], "dmem_prot_1");
+     if (!parent[1])
+             goto cleanup;
+
+     if (cg_create(parent[0]))
+             goto cleanup;
+

tools/testing/selftests/cgroup/test_dmem.c line 187

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+     if (cg_write(parent[0], "cgroup.subtree_control", "+dmem"))
+             goto cleanup;
+
+     if (cg_create(parent[1]))
+             goto cleanup;
+
+     if (cg_write(parent[1], "cgroup.subtree_control", "+dmem"))
+             goto cleanup;
+
+     for (i = 0; i < 4; i++) {
        for (i = 0; i < ARRAY_SIZE(children); i++) {

tools/testing/selftests/cgroup/test_dmem.c line 197

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+             children[i] = cg_name_indexed(parent[1], "dmem_child", i);
+             if (!children[i])
+                     goto cleanup;
+             if (cg_create(children[i]))
+                     goto cleanup;
+     }
+
+     if (dmem_write_limit(parent[1], "dmem.max", "1M"))
+             goto cleanup;
+     for (i = 0; i < 4; i++)
        for (i = 0; i < ARRAY_SIZE(children); i++) {

tools/testing/selftests/cgroup/test_dmem.c line 202

Quoted 5 lines
tools/testing/selftests/cgroup/test_dmem.c new file +5 -0
+             if (dmem_write_limit(children[i], "dmem.max", leaf_max[i]))
+                     goto cleanup;
+
+     v = dmem_read_limit(parent[1], "dmem.max");
+     if (v != 1024LL * 1024LL)

This...

tools/testing/selftests/cgroup/test_dmem.c line 205

Quoted 3 lines
tools/testing/selftests/cgroup/test_dmem.c new file +3 -0
+             goto cleanup;
+     v = dmem_read_limit(children[0], "dmem.max");
+     if (v != 75LL * 1024LL)

...and these literals would be nicer with MB() macro and possibly added similar KB() macro.

tools/testing/selftests/cgroup/test_dmem.c line 217

Quoted 12 lines
tools/testing/selftests/cgroup/test_dmem.c new file +12 -0
+             goto cleanup;
+     v = dmem_read_limit(children[1], "dmem.max");
+     if (v != 25LL * 1024LL)
+             goto cleanup;
+     v = dmem_read_limit(children[2], "dmem.max");
+     if (v != 8LL * 1024LL)
+             goto cleanup;
+     v = dmem_read_limit(children[3], "dmem.max");
+     if (v != 0)
+             goto cleanup;
+
+     for (i = 0; i < 4; i++) {
        for (i = 0; i < ARRAY_SIZE(children); i++) {

(to avoid unnamed non-trivial constant)

Quoted 40 lines
tools/testing/selftests/cgroup/test_dmem.c new file +40 -0
+             if (cg_enter_current(children[i]))
+                     goto cleanup;
+             in_child = 1;
+
+             cur_before = dmem_read_limit(children[i], "dmem.current");
+             if (cur_before < 0)
+                     goto cleanup;
+
+             if (dmem_selftest_charge_bytes(fail_sz[i]) >= 0) {
+                     charged = 1;
+                     goto cleanup;
+             }
+
+             cur_after = dmem_read_limit(children[i], "dmem.current");
+             if (cur_after != cur_before)
+                     goto cleanup;
+
+             if (pass_sz[i] > 0) {
+                     if (dmem_selftest_charge_bytes(pass_sz[i]) < 0)
+                             goto cleanup;
+                     charged = 1;
+
+                     cur_after = dmem_read_limit(children[i], "dmem.current");
+                     if (cur_after < cur_before + (long long)pass_sz[i])
+                             goto cleanup;
+                     if (cur_after > cur_before + (long long)pass_sz[i] + page_size)
+                             goto cleanup;
+
+                     if (dmem_selftest_uncharge() < 0)
+                             goto cleanup;
+                     charged = 0;
+
+                     cur_after = dmem_read_limit(children[i], "dmem.current");
+                     if (cur_after != cur_before)
+                             goto cleanup;
+             }
+
+             if (cg_enter_current(root))
+                     goto cleanup;
+             in_child = 0;

tools/testing/selftests/cgroup/test_dmem.c line 267

Quoted 10 lines
tools/testing/selftests/cgroup/test_dmem.c new file +10 -0
+     }
+
+     ret = KSFT_PASS;
+
+cleanup:
+     if (charged)
+             dmem_selftest_uncharge();
+     if (in_child)
+             cg_enter_current(root);
+     for (i = 3; i >= 0; i--) {

ditto with ARRAY_SIZE

Quoted 8 lines

tools/testing/selftests/cgroup/test_dmem.c line 273

Quoted 6 lines
tools/testing/selftests/cgroup/test_dmem.c new file +6 -0
+             if (!children[i])
+                     continue;
+             cg_destroy(children[i]);
+             free(children[i]);
+     }
+     for (i = 1; i >= 0; i--) {

ditto with ARRAY_SIZE

I'll address all the points raised (here and all the above).

Quoted 17 lines

tools/testing/selftests/cgroup/test_dmem.c line 285

Quoted 13 lines
tools/testing/selftests/cgroup/test_dmem.c new file +12 -0
+             if (!parent[i])
+                     continue;
+             cg_destroy(parent[i]);
+             free(parent[i]);
+     }
+     return ret;
+}
+
+/*
+ * This test sets dmem.min and dmem.low on a child cgroup, then charge
+ * from that context and verify dmem.current tracks the charged bytes
+ * (within one page rounding).

I don't know, this doesn't test much of the .min nor .low protection, and the .current tracking is already tested by the above. I'd drop it for now.

Makes sense. I'll do that for the next version.

Quoted 79 lines
Quoted 79 lines

+ */

tools/testing/selftests/cgroup/test_dmem.c new file +77 -0
+static int test_dmem_charge_with_attr(const char *root, bool min)
+{
+     unsigned long long cap;
+     const unsigned long long charge_sz = 12345ULL;
+     const char *attribute = min ? "dmem.min" : "dmem.low";
+     int ret = KSFT_FAIL;
+     char *cg = NULL;
+     long long cur;
+     long long page_size;
+     int charged = 0;
+     int in_child = 0;
+
+     if (access(DM_SELFTEST_CHARGE, W_OK) != 0)
+             return KSFT_SKIP;
+
+     if (find_selftest_region(root, &cap) != 1)
+             return KSFT_SKIP;
+
+     page_size = sysconf(_SC_PAGESIZE);
+     if (page_size <= 0)
+             goto cleanup;
+
+     cg = cg_name(root, "test_dmem_attr");
+     if (!cg)
+             goto cleanup;
+
+     if (cg_create(cg))
+             goto cleanup;
+
+     if (cg_enter_current(cg))
+             goto cleanup;
+     in_child = 1;
+
+     if (dmem_write_limit(cg, attribute, "16K"))
+             goto cleanup;
+
+     if (dmem_selftest_charge_bytes(charge_sz) < 0)
+             goto cleanup;
+     charged = 1;
+
+     cur = dmem_read_limit(cg, "dmem.current");
+     if (cur < (long long)charge_sz)
+             goto cleanup;
+     if (cur > (long long)charge_sz + page_size)
+             goto cleanup;
+
+     if (dmem_selftest_uncharge() < 0)
+             goto cleanup;
+     charged = 0;
+
+     cur = dmem_read_limit(cg, "dmem.current");
+     if (cur != 0)
+             goto cleanup;
+
+     ret = KSFT_PASS;
+
+cleanup:
+     if (charged)
+             dmem_selftest_uncharge();
+     if (in_child)
+             cg_enter_current(root);
+     cg_destroy(cg);
+     free(cg);
+     return ret;
+}
+
+static int test_dmem_min(const char *root)
+{
+     return test_dmem_charge_with_attr(root, true);
+}
+
+static int test_dmem_low(const char *root)
+{
+     return test_dmem_charge_with_attr(root, false);
+}
+
+/*
Quoted 8 lines
Quoted 4 lines

+ * This test charges non-page-aligned byte sizes and verify dmem.current
+ * stays consistent: it must account at least the requested bytes and
+ * never exceed one kernel page of rounding overhead. Then uncharge must
+ * return usage to 0.

The lower bound makes sense. Could you explain more about the upper bound and granularity? That applies only for the test module or is that intended constraint for any dmem-charging driver?

Uhm, the upper bound was modeled on test_memcontrol.c. Those tests cannot match memory.current exactly, so use lower bound plus values_close().

But for dmem, it isn't necessary; it accounts for the requested size with no page rounding or extra charge. I'll fix that and check for equality.

Thanks for raising this.

Quoted 108 lines
Quoted 108 lines

+ */

tools/testing/selftests/cgroup/test_dmem.c new file +106 -0
+static int test_dmem_charge_byte_granularity(const char *root)
+{
+     static const unsigned long long sizes[] = { 1ULL, 4095ULL, 4097ULL, 12345ULL };
+     char *cg = NULL;
+     unsigned long long cap;
+     long long cur;
+     long long page_size;
+     int ret = KSFT_FAIL;
+     int charged = 0;
+     int in_child = 0;
+     size_t i;
+
+     if (access(DM_SELFTEST_CHARGE, W_OK) != 0)
+             return KSFT_SKIP;
+
+     if (find_selftest_region(root, &cap) != 1)
+             return KSFT_SKIP;
+
+     page_size = sysconf(_SC_PAGESIZE);
+     if (page_size <= 0)
+             goto cleanup;
+
+     cg = cg_name(root, "dmem_dbg_byte_gran");
+     if (!cg)
+             goto cleanup;
+
+     if (cg_create(cg))
+             goto cleanup;
+
+     if (dmem_write_limit(cg, "dmem.max", "8M"))
+             goto cleanup;
+
+     if (cg_enter_current(cg))
+             goto cleanup;
+     in_child = 1;
+
+     for (i = 0; i < ARRAY_SIZE(sizes); i++) {
+             if (dmem_selftest_charge_bytes(sizes[i]) < 0)
+                     goto cleanup;
+             charged = 1;
+
+             cur = dmem_read_limit(cg, "dmem.current");
+             if (cur < (long long)sizes[i])
+                     goto cleanup;
+             if (cur > (long long)sizes[i] + page_size)
+                     goto cleanup;
+
+             if (dmem_selftest_uncharge() < 0)
+                     goto cleanup;
+             charged = 0;
+
+             cur = dmem_read_limit(cg, "dmem.current");
+             if (cur != 0)
+                     goto cleanup;
+     }
+
+     ret = KSFT_PASS;
+
+cleanup:
+     if (charged)
+             dmem_selftest_uncharge();
+     if (in_child)
+             cg_enter_current(root);
+     if (cg) {
+             cg_destroy(cg);
+             free(cg);
+     }
+     return ret;
+}
+
+#define T(x) { x, #x }
+struct dmem_test {
+     int (*fn)(const char *root);
+     const char *name;
+} tests[] = {
+     T(test_dmem_max),
+     T(test_dmem_min),
+     T(test_dmem_low),
+     T(test_dmem_charge_byte_granularity),
+};
+#undef T
+
+int main(int argc, char **argv)
+{
+     char root[PATH_MAX];
+     int i;
+
+     ksft_print_header();
+     ksft_set_plan(ARRAY_SIZE(tests));
+
+     if (cg_find_unified_root(root, sizeof(root), NULL))
+             ksft_exit_skip("cgroup v2 isn't mounted\n");
+
+     if (cg_read_strstr(root, "cgroup.controllers", "dmem"))
+             ksft_exit_skip("dmem controller isn't available (CONFIG_CGROUP_DMEM?)\n");
+
+     if (cg_read_strstr(root, "cgroup.subtree_control", "dmem"))
+             if (cg_write(root, "cgroup.subtree_control", "+dmem"))
+                     ksft_exit_skip("Failed to enable dmem controller\n");
+
+     for (i = 0; i < ARRAY_SIZE(tests); i++) {
+             switch (tests[i].fn(root)) {
+             case KSFT_PASS:
+                     ksft_test_result_pass("%s\n", tests[i].name);
+                     break;
+             case KSFT_SKIP:
Quoted 8 lines

tools/testing/selftests/cgroup/test_dmem.c line 477

Quoted 3 lines
tools/testing/selftests/cgroup/test_dmem.c new file +3 -0
+                     ksft_test_result_skip(
+                             "%s (need CONFIG_DMEM_SELFTEST, modprobe dmem_selftest)\n",
+                             tests[i].name);

I'm worried that the KSFT_SKIP from a subtest might be too broad for the modprobe prompt.
Perhaps you can check it by stat'ing DM_SELFTEST_CHARGE before any subtests start?

Agreed. I'll stat the helper in main().

BR,
Albert.

Quoted 15 lines
Quoted 15 lines
tools/testing/selftests/cgroup/test_dmem.c new file +9 -1
+                     break;
+             default:
+                     ksft_test_result_fail("%s\n", tests[i].name);
+                     break;
+             }
+     }
+
+     ksft_finished();
+}
 
--

2.54.0

#9 lore raw

PATCH v5 3/4 selftests: cgroup: Add vmtest-dmem runner script

In reply to Albert Esteve

Currently, test_dmem relies on the dmem_selftest helper module and a VM setup that may not have the helper preinstalled. This makes automated coverage of dmem charge paths harder in virtme-based runs.

Add tools/testing/selftests/cgroup/vmtest-dmem.sh to provide a repeatable VM workflow for dmem tests. The script uses vng --exec to run the test directly inside a virtme-ng guest with minimal setup.

The script boots a virtme-ng guest, validates dmem controller availability, ensures the dmem helper path is present, and runs tools/testing/selftests/cgroup/test_dmem. If the helper is not available as a loaded module, it attempts module build/load for the running guest kernel before executing the test binary.

The runner also supports interactive shell mode (-s) and reuses the verbosity and KTAP exit-code conventions used by other vmtest scripts, so it integrates with existing kselftest workflows.

vmtest-dmem.sh is placed in TEST_FILES rather than TEST_PROGS so it is installed alongside the test suite but not invoked automatically by run_kselftest.sh. It requires a VM-capable host and is intended to be run manually.

---
 tools/testing/selftests/cgroup/Makefile       |   2 +-
 tools/testing/selftests/cgroup/vmtest-dmem.sh | 149 ++++++++++++++++++++++++++
 2 files changed, 150 insertions(+), 1 deletion(-)
tools/testing/selftests/cgroup/Makefile +1 -1
index e1a5e9316620e..2c407710c6e3b 100644
@@ -3,7 +3,7 @@ CFLAGS += -Wall -pthread
 
 all: ${HELPER_PROGS}
 
-TEST_FILES     := with_stress.sh
+TEST_FILES     := with_stress.sh vmtest-dmem.sh
 TEST_PROGS     := test_stress.sh test_cpuset_prs.sh test_cpuset_v1_hp.sh
 TEST_GEN_FILES := wait_inotify
 # Keep the lists lexicographically sorted
tools/testing/selftests/cgroup/vmtest-dmem.sh new file +149 -0

149 lines not on this page · raw message

Signature · 1 line
2.54.0
Reviewed-by on v5 3/4
#10 lore raw

Re: [PATCH v5 3/4] selftests: cgroup: Add vmtest-dmem runner script

Quoted 20 lines · Albert Esteve

Currently, test_dmem relies on the dmem_selftest helper module and a VM setup that may not have the helper preinstalled. This makes automated coverage of dmem charge paths harder in virtme-based runs.

Add tools/testing/selftests/cgroup/vmtest-dmem.sh to provide a repeatable VM workflow for dmem tests. The script uses vng --exec to run the test directly inside a virtme-ng guest with minimal setup.

The script boots a virtme-ng guest, validates dmem controller availability, ensures the dmem helper path is present, and runs tools/testing/selftests/cgroup/test_dmem. If the helper is not available as a loaded module, it attempts module build/load for the running guest kernel before executing the test binary.

The runner also supports interactive shell mode (-s) and reuses the verbosity and KTAP exit-code conventions used by other vmtest scripts, so it integrates with existing kselftest workflows.

Quoted 6 lines

vmtest-dmem.sh is placed in TEST_FILES rather than TEST_PROGS so it is installed alongside the test suite but not invoked automatically by run_kselftest.sh. It requires a VM-capable host and is intended to be run manually.

Signature · 1 line
Eric Chanudet
#11 lore raw

PATCH v5 4/4 selftests: cgroup: handle vmtest-dmem -b to test locally built kernel

In reply to Albert Esteve

Currently vmtest-dmem.sh relies on the host's running kernel or a pre-built one when booting the virtme-ng VM, with no option to configure and build a local kernel tree directly.

This adds friction to the development cycle: the user must manually run vng --kconfig with the correct config fragment, build the kernel, and pass the result to the script.

Add a -b flag that automates this workflow. When set, handle_build() configures the kernel using vng --kconfig with the selftest config fragment, builds it with make -j$(nproc), and run_vm() passes the local tree to vng --run so the VM boots the freshly built kernel.

---
 tools/testing/selftests/cgroup/vmtest-dmem.sh | 47 ++++++++++++++++++++++++---
 1 file changed, 43 insertions(+), 4 deletions(-)
tools/testing/selftests/cgroup/vmtest-dmem.sh +43 -4
index 0bb6529112b54..4d0e2c0511e5b 100755
@@ -15,6 +15,7 @@ readonly KERNEL_CHECKOUT="$(realpath "${SCRIPT_DIR}"/../../../../)"
 
 source "${SCRIPT_DIR}"/../kselftest/ktap_helpers.sh
 
+BUILD=0
 QEMU="qemu-system-$(uname -m)"
 VERBOSE=0
 SHELL_MODE=0
@@ -26,10 +27,22 @@ function usage() {
 	cat <<EOF
 $0 [OPTIONS]
 Options:
+	-b	Build kernel from source tree before booting
 	-q	QEMU binary/path (default: ${QEMU})
 	-s	Start interactive shell in VM instead of running tests
 	-v	Verbose output (vng boot logs on stdout)
 	-h	Display this help
+
+If you build your kernel using KBUILD_OUTPUT= or O= options, these
+can be passed as environment variables to the script:
+
+  O=<build_path> $0 -b
+
+or
+
+  KBUILD_OUTPUT=<build_path> $0 -b
+
+O= takes precedence over KBUILD_OUTPUT= if both are set.
 EOF
 }
 
@@ -60,17 +73,41 @@ function check_deps() {
 	done
 }
 
+function handle_build() {
+	[[ "${BUILD}" -eq 1 ]] || return 0
+
+	[[ -f "${KERNEL_CHECKOUT}/kernel/cgroup/dmem_selftest.c" ]] || \
+		fail "-b requires vmtest-dmem.sh called from the kernel source tree"
+
+	# Figure out where the kernel is being built.
+	# O takes precedence over KBUILD_OUTPUT.
+	local out_args=()
+	if [[ -n "${O:-}" ]]; then
+		out_args=(O="${O}")
+	elif [[ -n "${KBUILD_OUTPUT:-}" ]]; then
+		out_args=(KBUILD_OUTPUT="${KBUILD_OUTPUT}")
+	fi
+
+	pushd "${KERNEL_CHECKOUT}" &>/dev/null
+	vng --kconfig --config "${SCRIPT_DIR}"/config "${out_args[@]}" || \
+		fail "failed to generate .config for kernel source tree (${KERNEL_CHECKOUT})"
+	make "${out_args[@]}" -j"$(nproc 2>/dev/null || echo 1)" || \
+		fail "failed to build kernel from source tree (${KERNEL_CHECKOUT})"
+	popd &>/dev/null
+}
+
 # Run vng with common flags. Extra arguments are appended by the caller:
 #   --exec <script>  for automated test runs
 #   (nothing)        for interactive shell mode
 function run_vm() {
-	local verbose_opt=""
+	local vng_args=()
 
-	[[ "${VERBOSE}" -eq 1 ]] && verbose_opt="--verbose"
+	[[ "${BUILD}" -eq 1 ]] && vng_args+=("${KERNEL_CHECKOUT}")
+	[[ "${VERBOSE}" -eq 1 ]] && vng_args+=("--verbose")
 
 	vng \
 		--run \
-		${verbose_opt:+"${verbose_opt}"} \
+		"${vng_args[@]}" \
 		--qemu="$(command -v "${QEMU}")" \
 		--user root \
 		--rw \
@@ -78,10 +115,11 @@ function run_vm() {
 }
 
 function main() {
-	while getopts ':hvq:s' opt; do
+	while getopts ':hvq:sb' opt; do
 		case "${opt}" in
 		v) VERBOSE=1 ;;
 		q) QEMU="${OPTARG}" ;;
+		b) BUILD=1 ;;
 		s) SHELL_MODE=1 ;;
 		h) usage; exit 0 ;;
 		*) usage; exit 1 ;;
@@ -89,6 +127,7 @@ function main() {
 	done
 
 	check_deps
+	handle_build
 
 	if [[ "${SHELL_MODE}" -eq 1 ]]; then
 		echo "Starting interactive shell in VM. Exit to stop VM."
Signature · 1 line
2.54.0
maintainer
#12 lore raw
In reply to Albert Esteve

Hello Albert.

Quoted 21 lines · Albert Esteve

Hi all,

This small series adds practical test coverage for the dmem cgroup controller.

The motivation came from following the recent dmem API discussion in thread [1]. That discussion considered changing the dmem API and adding a new knob. Currently there are no dedicated tests covering dmem behaviour, which makes such changes riskier.

Adding selftests has an additional challenge: dmem charging paths are driver-driven today, so regression testing is harder unless a suitable driver is present in the test environment.

This series addresses that by adding:
- a kernel-side selftest helper module to trigger charge/uncharge from userspace in a controlled way,
- cgroup selftests covering dmem accounting and protection semantics (including dmem.max enforcement and byte-granularity checks),
- a virtme-based VM runner for repeatable execution of the dmem tests.

Quoted 2 lines

The goal is to make dmem behavior easier to validate when evolving the API and implementation, while keeping tests deterministic and driver-independent.

Thanks for the dmem selftesting. I'll respond to first two patches individually. I find the wrapper scripts in the last two a bit of an overkill for the selftest (as it adds dependency on particular VM environment, I'd keep the simplicity of selftests such that wherever they are executed (w/out wrappers), there they run (be it a physical machine or a VM). At most, I'd consider a simple wrapper that'd load ensure the test module is loaded.

Thanks,
Michal

#13 lore raw
Quoted 28 lines · Michal Koutný

Hello Albert.

Quoted 21 lines · Albert Esteve

Hi all,

This small series adds practical test coverage for the dmem cgroup controller.

The motivation came from following the recent dmem API discussion in thread [1]. That discussion considered changing the dmem API and adding a new knob. Currently there are no dedicated tests covering dmem behaviour, which makes such changes riskier.

Adding selftests has an additional challenge: dmem charging paths are driver-driven today, so regression testing is harder unless a suitable driver is present in the test environment.

This series addresses that by adding:
- a kernel-side selftest helper module to trigger charge/uncharge from userspace in a controlled way,
- cgroup selftests covering dmem accounting and protection semantics (including dmem.max enforcement and byte-granularity checks),
- a virtme-based VM runner for repeatable execution of the dmem tests.

Quoted 2 lines

The goal is to make dmem behavior easier to validate when evolving the API and implementation, while keeping tests deterministic and driver-independent.

Quoted 7 lines

Thanks for the dmem selftesting. I'll respond to first two patches individually. I find the wrapper scripts in the last two a bit of an overkill for the selftest (as it adds dependency on particular VM environment, I'd keep the simplicity of selftests such that wherever they are executed (w/out wrappers), there they run (be it a physical machine or a VM). At most, I'd consider a simple wrapper that'd load ensure the test module is loaded.

Thanks for the review!

The last two patches were meant to follow the existing virtme-ng vmtest.sh pattern used by other selftests, mainly as a convenient developer loop. Anyway, I can see how it might be overkill, especially in this initial version. I'll drop them for now and keep the first two patches.

If a tiny wrapper that only ensures dmem_selftest is loaded turns out to be useful, that can be added later.

BR,
Albert.

Quoted 3 lines

Thanks,
Michal