1 // SPDX-License-Identifier: GPL-2.0
4 #include <subcmd/parse-options.h>
8 #include <linux/stringify.h>
13 cgroupfs_find_mountpoint(char *buf, size_t maxlen)
16 char mountpoint[PATH_MAX + 1], tokens[PATH_MAX + 1], type[PATH_MAX + 1];
17 char path_v1[PATH_MAX + 1], path_v2[PATH_MAX + 2], *path;
18 char *token, *saved_ptr = NULL;
20 fp = fopen("/proc/mounts", "r");
25 * in order to handle split hierarchy, we need to scan /proc/mounts
26 * and inspect every cgroupfs mount point to find one that has
27 * perf_event subsystem
32 while (fscanf(fp, "%*s %"__stringify(PATH_MAX)"s %"__stringify(PATH_MAX)"s %"
33 __stringify(PATH_MAX)"s %*d %*d\n",
34 mountpoint, type, tokens) == 3) {
36 if (!path_v1[0] && !strcmp(type, "cgroup")) {
38 token = strtok_r(tokens, ",", &saved_ptr);
40 while (token != NULL) {
41 if (!strcmp(token, "perf_event")) {
42 strcpy(path_v1, mountpoint);
45 token = strtok_r(NULL, ",", &saved_ptr);
49 if (!path_v2[0] && !strcmp(type, "cgroup2"))
50 strcpy(path_v2, mountpoint);
52 if (path_v1[0] && path_v2[0])
64 if (strlen(path) < maxlen) {
71 static int open_cgroup(char *name)
73 char path[PATH_MAX + 1];
74 char mnt[PATH_MAX + 1];
78 if (cgroupfs_find_mountpoint(mnt, PATH_MAX + 1))
81 scnprintf(path, PATH_MAX, "%s/%s", mnt, name);
83 fd = open(path, O_RDONLY);
85 fprintf(stderr, "no access to cgroup %s\n", path);
90 static int add_cgroup(struct perf_evlist *evlist, char *str)
92 struct perf_evsel *counter;
93 struct cgroup_sel *cgrp = NULL;
96 * check if cgrp is already defined, if so we reuse it
98 evlist__for_each_entry(evlist, counter) {
102 if (!strcmp(cgrp->name, str)) {
103 refcount_inc(&cgrp->refcnt);
111 cgrp = zalloc(sizeof(*cgrp));
116 refcount_set(&cgrp->refcnt, 1);
118 cgrp->fd = open_cgroup(str);
119 if (cgrp->fd == -1) {
126 * find corresponding event
127 * if add cgroup N, then need to find event N
130 evlist__for_each_entry(evlist, counter) {
135 if (refcount_dec_and_test(&cgrp->refcnt))
140 counter->cgrp = cgrp;
144 void close_cgroup(struct cgroup_sel *cgrp)
146 if (cgrp && refcount_dec_and_test(&cgrp->refcnt)) {
153 int parse_cgroups(const struct option *opt __maybe_unused, const char *str,
154 int unset __maybe_unused)
156 struct perf_evlist *evlist = *(struct perf_evlist **)opt->value;
157 const char *p, *e, *eos = str + strlen(str);
161 if (list_empty(&evlist->entries)) {
162 fprintf(stderr, "must define events before cgroups\n");
167 p = strchr(str, ',');
170 /* allow empty cgroups, i.e., skip */
172 /* termination added */
173 s = strndup(str, e - str);
176 ret = add_cgroup(evlist, s);
182 /* nr_cgroups is increased een for empty cgroups */