hc
2024-05-13 9d77db3c730780c8ef5ccd4b66403ff5675cfe4e
kernel/samples/bpf/cpustat_user.c
....@@ -9,7 +9,6 @@
99 #include <string.h>
1010 #include <unistd.h>
1111 #include <fcntl.h>
12
-#include <linux/bpf.h>
1312 #include <locale.h>
1413 #include <sys/types.h>
1514 #include <sys/stat.h>
....@@ -18,7 +17,9 @@
1817 #include <sys/wait.h>
1918
2019 #include <bpf/bpf.h>
21
-#include "bpf_load.h"
20
+#include <bpf/libbpf.h>
21
+
22
+static int cstate_map_fd, pstate_map_fd;
2223
2324 #define MAX_CPU 8
2425 #define MAX_PSTATE_ENTRIES 5
....@@ -181,21 +182,50 @@
181182 {
182183 cpu_stat_inject_cpu_idle_event();
183184 cpu_stat_inject_cpu_frequency_event();
184
- cpu_stat_update(map_fd[1], map_fd[2]);
185
+ cpu_stat_update(cstate_map_fd, pstate_map_fd);
185186 cpu_stat_print();
186187 exit(0);
187188 }
188189
189190 int main(int argc, char **argv)
190191 {
192
+ struct bpf_link *link = NULL;
193
+ struct bpf_program *prog;
194
+ struct bpf_object *obj;
191195 char filename[256];
192196 int ret;
193197
194198 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
199
+ obj = bpf_object__open_file(filename, NULL);
200
+ if (libbpf_get_error(obj)) {
201
+ fprintf(stderr, "ERROR: opening BPF object file failed\n");
202
+ return 0;
203
+ }
195204
196
- if (load_bpf_file(filename)) {
197
- printf("%s", bpf_log_buf);
198
- return 1;
205
+ prog = bpf_object__find_program_by_name(obj, "bpf_prog1");
206
+ if (!prog) {
207
+ printf("finding a prog in obj file failed\n");
208
+ goto cleanup;
209
+ }
210
+
211
+ /* load BPF program */
212
+ if (bpf_object__load(obj)) {
213
+ fprintf(stderr, "ERROR: loading BPF object file failed\n");
214
+ goto cleanup;
215
+ }
216
+
217
+ cstate_map_fd = bpf_object__find_map_fd_by_name(obj, "cstate_duration");
218
+ pstate_map_fd = bpf_object__find_map_fd_by_name(obj, "pstate_duration");
219
+ if (cstate_map_fd < 0 || pstate_map_fd < 0) {
220
+ fprintf(stderr, "ERROR: finding a map in obj file failed\n");
221
+ goto cleanup;
222
+ }
223
+
224
+ link = bpf_program__attach(prog);
225
+ if (libbpf_get_error(link)) {
226
+ fprintf(stderr, "ERROR: bpf_program__attach failed\n");
227
+ link = NULL;
228
+ goto cleanup;
199229 }
200230
201231 ret = cpu_stat_inject_cpu_idle_event();
....@@ -210,10 +240,13 @@
210240 signal(SIGTERM, int_exit);
211241
212242 while (1) {
213
- cpu_stat_update(map_fd[1], map_fd[2]);
243
+ cpu_stat_update(cstate_map_fd, pstate_map_fd);
214244 cpu_stat_print();
215245 sleep(5);
216246 }
217247
248
+cleanup:
249
+ bpf_link__destroy(link);
250
+ bpf_object__close(obj);
218251 return 0;
219252 }