tools/testing/selftests/bpf/prog_tests/cgroup_iter_memcg.c

Source file repositories/reference/linux-study-clean/tools/testing/selftests/bpf/prog_tests/cgroup_iter_memcg.c

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/bpf/prog_tests/cgroup_iter_memcg.c
Extension
.c
Size
4772 bytes
Lines
195
Domain
Support Tooling And Documentation
Bucket
tools
Inferred role
Support Tooling And Documentation: implementation source
Status
source implementation candidate

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

// SPDX-License-Identifier: GPL-2.0
/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
#include <test_progs.h>
#include <bpf/libbpf.h>
#include <bpf/btf.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include "cgroup_helpers.h"
#include "cgroup_iter_memcg.h"
#include "cgroup_iter_memcg.skel.h"

static int read_stats(struct bpf_link *link)
{
	int fd, ret = 0;
	ssize_t bytes;

	fd = bpf_iter_create(bpf_link__fd(link));
	if (!ASSERT_OK_FD(fd, "bpf_iter_create"))
		return 1;

	/*
	 * Invoke iter program by reading from its fd. We're not expecting any
	 * data to be written by the bpf program so the result should be zero.
	 * Results will be read directly through the custom data section
	 * accessible through skel->data_query.memcg_query.
	 */
	bytes = read(fd, NULL, 0);
	if (!ASSERT_EQ(bytes, 0, "read fd"))
		ret = 1;

	close(fd);
	return ret;
}

static void test_anon(struct bpf_link *link, struct memcg_query *memcg_query)
{
	void *map;
	size_t len;

	len = sysconf(_SC_PAGESIZE) * 1024;

	/*
	 * Increase memcg anon usage by mapping and writing
	 * to a new anon region.
	 */
	map = mmap(NULL, len, PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
	if (!ASSERT_NEQ(map, MAP_FAILED, "mmap anon"))
		return;

	memset(map, 1, len);

	if (!ASSERT_OK(read_stats(link), "read stats"))
		goto cleanup;

	ASSERT_GT(memcg_query->nr_anon_mapped, 0, "final anon mapped val");

cleanup:
	munmap(map, len);
}

static void test_file(struct bpf_link *link, struct memcg_query *memcg_query)
{
	void *map;
	size_t len;
	char *path;
	int fd;

	len = sysconf(_SC_PAGESIZE) * 1024;
	path = "/tmp/test_cgroup_iter_memcg";

	/*
	 * Increase memcg file usage by creating and writing
	 * to a mapped file.
	 */
	fd = open(path, O_CREAT | O_RDWR, 0644);
	if (!ASSERT_OK_FD(fd, "open fd"))
		return;
	if (!ASSERT_OK(ftruncate(fd, len), "ftruncate"))
		goto cleanup_fd;

	map = mmap(NULL, len, PROT_WRITE, MAP_SHARED, fd, 0);
	if (!ASSERT_NEQ(map, MAP_FAILED, "mmap file"))
		goto cleanup_fd;

	memset(map, 1, len);

	if (!ASSERT_OK(read_stats(link), "read stats"))
		goto cleanup_map;

Annotation

Implementation Notes