Merge tag 'rproc-v4.16' of git://github.com/andersson/remoteproc
[linux-2.6-block.git] / samples / bpf / test_current_task_under_cgroup_user.c
CommitLineData
9e6e60ec
SD
1/* Copyright (c) 2016 Sargun Dhillon <sargun@sargun.me>
2 *
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of version 2 of the GNU General Public
5 * License as published by the Free Software Foundation.
6 */
7
8#define _GNU_SOURCE
9#include <stdio.h>
10#include <linux/bpf.h>
11#include <unistd.h>
12#include "libbpf.h"
13#include "bpf_load.h"
9e6e60ec 14#include <linux/bpf.h>
1a922fee 15#include "cgroup_helpers.h"
9e6e60ec 16
1a922fee 17#define CGROUP_PATH "/my-cgroup"
9e6e60ec
SD
18
19int main(int argc, char **argv)
20{
9e6e60ec 21 pid_t remote_pid, local_pid = getpid();
1a922fee
SD
22 int cg2, idx = 0, rc = 0;
23 char filename[256];
9e6e60ec
SD
24
25 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
26 if (load_bpf_file(filename)) {
27 printf("%s", bpf_log_buf);
28 return 1;
29 }
30
1a922fee
SD
31 if (setup_cgroup_environment())
32 goto err;
9e6e60ec 33
1a922fee 34 cg2 = create_and_get_cgroup(CGROUP_PATH);
9e6e60ec 35
1a922fee
SD
36 if (!cg2)
37 goto err;
9e6e60ec 38
d40fc181 39 if (bpf_map_update_elem(map_fd[0], &idx, &cg2, BPF_ANY)) {
9e6e60ec 40 log_err("Adding target cgroup to map");
1a922fee 41 goto err;
9e6e60ec
SD
42 }
43
1a922fee
SD
44 if (join_cgroup(CGROUP_PATH))
45 goto err;
46
9e6e60ec
SD
47 /*
48 * The installed helper program catched the sync call, and should
49 * write it to the map.
50 */
51
52 sync();
d40fc181 53 bpf_map_lookup_elem(map_fd[1], &idx, &remote_pid);
9e6e60ec
SD
54
55 if (local_pid != remote_pid) {
56 fprintf(stderr,
57 "BPF Helper didn't write correct PID to map, but: %d\n",
58 remote_pid);
1a922fee 59 goto err;
9e6e60ec
SD
60 }
61
62 /* Verify the negative scenario; leave the cgroup */
1a922fee
SD
63 if (join_cgroup("/"))
64 goto err;
9e6e60ec
SD
65
66 remote_pid = 0;
d40fc181 67 bpf_map_update_elem(map_fd[1], &idx, &remote_pid, BPF_ANY);
9e6e60ec
SD
68
69 sync();
d40fc181 70 bpf_map_lookup_elem(map_fd[1], &idx, &remote_pid);
9e6e60ec
SD
71
72 if (local_pid == remote_pid) {
73 fprintf(stderr, "BPF cgroup negative test did not work\n");
1a922fee 74 goto err;
9e6e60ec
SD
75 }
76
1a922fee
SD
77 goto out;
78err:
79 rc = 1;
9e6e60ec 80
1a922fee
SD
81out:
82 close(cg2);
83 cleanup_cgroup_environment();
84 return rc;
9e6e60ec 85}