1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 // Copyright (c) 2020 Wenbo Zhang
3 //
4 // Based on cpufreq(8) from BPF-Perf-Tools-Book by Brendan Gregg.
5 // 10-OCT-2020 Wenbo Zhang Created this.
6 #include <argp.h>
7 #include <signal.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <linux/perf_event.h>
13 #include <asm/unistd.h>
14 #include <bpf/libbpf.h>
15 #include <bpf/bpf.h>
16 #include "cpufreq.h"
17 #include "cpufreq.skel.h"
18 #include "trace_helpers.h"
19
20 static struct env {
21 int duration;
22 int freq;
23 bool verbose;
24 } env = {
25 .duration = -1,
26 .freq = 99,
27 };
28
29 const char *argp_program_version = "cpufreq 0.1";
30 const char *argp_program_bug_address =
31 "https://github.com/iovisor/bcc/tree/master/libbpf-tools";
32 const char argp_program_doc[] =
33 "Sampling CPU freq system-wide & by process. Ctrl-C to end.\n"
34 "\n"
35 "USAGE: cpufreq [--help] [-d DURATION] [-f FREQUENCY]\n"
36 "\n"
37 "EXAMPLES:\n"
38 " cpufreq # sample CPU freq at 99HZ (default)\n"
39 " cpufreq -d 5 # sample for 5 seconds only\n"
40 " cpufreq -f 199 # sample CPU freq at 199HZ\n";
41
42 static const struct argp_option opts[] = {
43 { "duration", 'd', "DURATION", 0, "Duration to sample in seconds" },
44 { "frequency", 'f', "FREQUENCY", 0, "Sample with a certain frequency" },
45 { "verbose", 'v', NULL, 0, "Verbose debug output" },
46 { NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
47 {},
48 };
49
parse_arg(int key,char * arg,struct argp_state * state)50 static error_t parse_arg(int key, char *arg, struct argp_state *state)
51 {
52 switch (key) {
53 case 'h':
54 argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
55 break;
56 case 'v':
57 env.verbose = true;
58 break;
59 case 'd':
60 errno = 0;
61 env.duration = strtol(arg, NULL, 10);
62 if (errno || env.duration <= 0) {
63 fprintf(stderr, "Invalid duration: %s\n", arg);
64 argp_usage(state);
65 }
66 break;
67 case 'f':
68 errno = 0;
69 env.freq = strtol(arg, NULL, 10);
70 if (errno || env.freq <= 0) {
71 fprintf(stderr, "Invalid freq (in HZ): %s\n", arg);
72 argp_usage(state);
73 }
74 break;
75 default:
76 return ARGP_ERR_UNKNOWN;
77 }
78 return 0;
79 }
80
81 static int nr_cpus;
82
open_and_attach_perf_event(int freq,struct bpf_program * prog,struct bpf_link * links[])83 static int open_and_attach_perf_event(int freq, struct bpf_program *prog,
84 struct bpf_link *links[])
85 {
86 struct perf_event_attr attr = {
87 .type = PERF_TYPE_SOFTWARE,
88 .freq = 1,
89 .sample_period = freq,
90 .config = PERF_COUNT_SW_CPU_CLOCK,
91 };
92 int i, fd;
93
94 for (i = 0; i < nr_cpus; i++) {
95 fd = syscall(__NR_perf_event_open, &attr, -1, i, -1, 0);
96 if (fd < 0) {
97 /* Ignore CPU that is offline */
98 if (errno == ENODEV)
99 continue;
100 fprintf(stderr, "failed to init perf sampling: %s\n",
101 strerror(errno));
102 return -1;
103 }
104 links[i] = bpf_program__attach_perf_event(prog, fd);
105 if (!links[i]) {
106 fprintf(stderr, "failed to attach perf event on cpu: %d\n", i);
107 close(fd);
108 return -1;
109 }
110 }
111
112 return 0;
113 }
114
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)115 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
116 {
117 if (level == LIBBPF_DEBUG && !env.verbose)
118 return 0;
119 return vfprintf(stderr, format, args);
120 }
121
sig_handler(int sig)122 static void sig_handler(int sig)
123 {
124 }
125
init_freqs_hmz(__u32 * freqs_mhz,int nr_cpus)126 static int init_freqs_hmz(__u32 *freqs_mhz, int nr_cpus)
127 {
128 char path[64];
129 FILE *f;
130 int i;
131
132 for (i = 0; i < nr_cpus; i++) {
133 snprintf(path, sizeof(path),
134 "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq",
135 i);
136
137 f = fopen(path, "r");
138 if (!f) {
139 fprintf(stderr, "failed to open '%s': %s\n", path,
140 strerror(errno));
141 return -1;
142 }
143 if (fscanf(f, "%u\n", &freqs_mhz[i]) != 1) {
144 fprintf(stderr, "failed to parse '%s': %s\n", path,
145 strerror(errno));
146 fclose(f);
147 return -1;
148 }
149 fclose(f);
150 }
151
152 return 0;
153 }
154
print_linear_hists(struct bpf_map * hists,struct cpufreq_bpf__bss * bss)155 static void print_linear_hists(struct bpf_map *hists,
156 struct cpufreq_bpf__bss *bss)
157 {
158 struct hkey lookup_key = {}, next_key;
159 int err, fd = bpf_map__fd(hists);
160 struct hist hist;
161
162 while (!bpf_map_get_next_key(fd, &lookup_key, &next_key)) {
163 err = bpf_map_lookup_elem(fd, &next_key, &hist);
164 if (err < 0) {
165 fprintf(stderr, "failed to lookup hist: %d\n", err);
166 return;
167 }
168 print_linear_hist(hist.slots, MAX_SLOTS, 0, HIST_STEP_SIZE,
169 next_key.comm);
170 printf("\n");
171 lookup_key = next_key;
172 }
173
174 printf("\n");
175 print_linear_hist(bss->syswide.slots, MAX_SLOTS, 0, HIST_STEP_SIZE,
176 "syswide");
177 }
178
main(int argc,char ** argv)179 int main(int argc, char **argv)
180 {
181 static const struct argp argp = {
182 .options = opts,
183 .parser = parse_arg,
184 .doc = argp_program_doc,
185 };
186 struct bpf_link *links[MAX_CPU_NR] = {};
187 struct cpufreq_bpf *obj;
188 int err, i;
189
190 err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
191 if (err)
192 return err;
193
194 libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
195 libbpf_set_print(libbpf_print_fn);
196
197 nr_cpus = libbpf_num_possible_cpus();
198 if (nr_cpus < 0) {
199 fprintf(stderr, "failed to get # of possible cpus: '%s'!\n",
200 strerror(-nr_cpus));
201 return 1;
202 }
203 if (nr_cpus > MAX_CPU_NR) {
204 fprintf(stderr, "the number of cpu cores is too big, please "
205 "increase MAX_CPU_NR's value and recompile");
206 return 1;
207 }
208
209 obj = cpufreq_bpf__open_and_load();
210 if (!obj) {
211 fprintf(stderr, "failed to open and/or load BPF object\n");
212 return 1;
213 }
214
215 if (!obj->bss) {
216 fprintf(stderr, "Memory-mapping BPF maps is supported starting from Linux 5.7, please upgrade.\n");
217 goto cleanup;
218 }
219
220 err = init_freqs_hmz(obj->bss->freqs_mhz, nr_cpus);
221 if (err) {
222 fprintf(stderr, "failed to init freqs\n");
223 goto cleanup;
224 }
225
226 err = open_and_attach_perf_event(env.freq, obj->progs.do_sample, links);
227 if (err)
228 goto cleanup;
229
230 err = cpufreq_bpf__attach(obj);
231 if (err) {
232 fprintf(stderr, "failed to attach BPF programs\n");
233 goto cleanup;
234 }
235
236 printf("Sampling CPU freq system-wide & by process. Ctrl-C to end.\n");
237
238 signal(SIGINT, sig_handler);
239
240 /*
241 * We'll get sleep interrupted when someone presses Ctrl-C (which will
242 * be "handled" with noop by sig_handler).
243 */
244 sleep(env.duration);
245 printf("\n");
246
247 print_linear_hists(obj->maps.hists, obj->bss);
248
249 cleanup:
250 for (i = 0; i < nr_cpus; i++)
251 bpf_link__destroy(links[i]);
252 cpufreq_bpf__destroy(obj);
253
254 return err != 0;
255 }
256