Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

selftests/bpf: Add a new cgroup helper get_cgroup_hierarchy_id()

A new cgroup helper function, get_cgroup1_hierarchy_id(), has been
introduced to obtain the ID of a cgroup1 hierarchy based on the provided
cgroup name. This cgroup name can be obtained from the /proc/self/cgroup
file.

Signed-off-by: Yafang Shao <laoar.shao@gmail.com>
Link: https://lore.kernel.org/r/20231111090034.4248-6-laoar.shao@gmail.com
Signed-off-by: Alexei Starovoitov <ast@kernel.org>

authored by

Yafang Shao and committed by
Alexei Starovoitov
bf47300b c1dcc050

+53
+52
tools/testing/selftests/bpf/cgroup_helpers.c
··· 637 637 format_classid_path(cgroup_workdir); 638 638 return get_cgroup_id_from_path(cgroup_workdir); 639 639 } 640 + 641 + /** 642 + * get_cgroup1_hierarchy_id - Retrieves the ID of a cgroup1 hierarchy from the cgroup1 subsys name. 643 + * @subsys_name: The cgroup1 subsys name, which can be retrieved from /proc/self/cgroup. It can be 644 + * a named cgroup like "name=systemd", a controller name like "net_cls", or multi-contollers like 645 + * "net_cls,net_prio". 646 + */ 647 + int get_cgroup1_hierarchy_id(const char *subsys_name) 648 + { 649 + char *c, *c2, *c3, *c4; 650 + bool found = false; 651 + char line[1024]; 652 + FILE *file; 653 + int i, id; 654 + 655 + if (!subsys_name) 656 + return -1; 657 + 658 + file = fopen("/proc/self/cgroup", "r"); 659 + if (!file) { 660 + log_err("fopen /proc/self/cgroup"); 661 + return -1; 662 + } 663 + 664 + while (fgets(line, 1024, file)) { 665 + i = 0; 666 + for (c = strtok_r(line, ":", &c2); c && i < 2; c = strtok_r(NULL, ":", &c2)) { 667 + if (i == 0) { 668 + id = strtol(c, NULL, 10); 669 + } else if (i == 1) { 670 + if (!strcmp(c, subsys_name)) { 671 + found = true; 672 + break; 673 + } 674 + 675 + /* Multiple subsystems may share one single mount point */ 676 + for (c3 = strtok_r(c, ",", &c4); c3; 677 + c3 = strtok_r(NULL, ",", &c4)) { 678 + if (!strcmp(c, subsys_name)) { 679 + found = true; 680 + break; 681 + } 682 + } 683 + } 684 + i++; 685 + } 686 + if (found) 687 + break; 688 + } 689 + fclose(file); 690 + return found ? id : -1; 691 + }
+1
tools/testing/selftests/bpf/cgroup_helpers.h
··· 20 20 int create_and_get_cgroup(const char *relative_path); 21 21 void remove_cgroup(const char *relative_path); 22 22 unsigned long long get_cgroup_id(const char *relative_path); 23 + int get_cgroup1_hierarchy_id(const char *subsys_name); 23 24 24 25 int join_cgroup(const char *relative_path); 25 26 int join_root_cgroup(void);