0001
0002 #include <stdio.h>
0003 #include <fcntl.h>
0004 #include <poll.h>
0005 #include <time.h>
0006 #include <signal.h>
0007 #include <bpf/libbpf.h>
0008
0009 static __u64 time_get_ns(void)
0010 {
0011 struct timespec ts;
0012
0013 clock_gettime(CLOCK_MONOTONIC, &ts);
0014 return ts.tv_sec * 1000000000ull + ts.tv_nsec;
0015 }
0016
0017 static __u64 start_time;
0018 static __u64 cnt;
0019
0020 #define MAX_CNT 100000ll
0021
0022 static void print_bpf_output(void *ctx, int cpu, void *data, __u32 size)
0023 {
0024 struct {
0025 __u64 pid;
0026 __u64 cookie;
0027 } *e = data;
0028
0029 if (e->cookie != 0x12345678) {
0030 printf("BUG pid %llx cookie %llx sized %d\n",
0031 e->pid, e->cookie, size);
0032 return;
0033 }
0034
0035 cnt++;
0036
0037 if (cnt == MAX_CNT) {
0038 printf("recv %lld events per sec\n",
0039 MAX_CNT * 1000000000ll / (time_get_ns() - start_time));
0040 return;
0041 }
0042 }
0043
0044 int main(int argc, char **argv)
0045 {
0046 struct bpf_link *link = NULL;
0047 struct bpf_program *prog;
0048 struct perf_buffer *pb;
0049 struct bpf_object *obj;
0050 int map_fd, ret = 0;
0051 char filename[256];
0052 FILE *f;
0053
0054 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
0055 obj = bpf_object__open_file(filename, NULL);
0056 if (libbpf_get_error(obj)) {
0057 fprintf(stderr, "ERROR: opening BPF object file failed\n");
0058 return 0;
0059 }
0060
0061
0062 if (bpf_object__load(obj)) {
0063 fprintf(stderr, "ERROR: loading BPF object file failed\n");
0064 goto cleanup;
0065 }
0066
0067 map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
0068 if (map_fd < 0) {
0069 fprintf(stderr, "ERROR: finding a map in obj file failed\n");
0070 goto cleanup;
0071 }
0072
0073 prog = bpf_object__find_program_by_name(obj, "bpf_prog1");
0074 if (libbpf_get_error(prog)) {
0075 fprintf(stderr, "ERROR: finding a prog in obj file failed\n");
0076 goto cleanup;
0077 }
0078
0079 link = bpf_program__attach(prog);
0080 if (libbpf_get_error(link)) {
0081 fprintf(stderr, "ERROR: bpf_program__attach failed\n");
0082 link = NULL;
0083 goto cleanup;
0084 }
0085
0086 pb = perf_buffer__new(map_fd, 8, print_bpf_output, NULL, NULL, NULL);
0087 ret = libbpf_get_error(pb);
0088 if (ret) {
0089 printf("failed to setup perf_buffer: %d\n", ret);
0090 return 1;
0091 }
0092
0093 f = popen("taskset 1 dd if=/dev/zero of=/dev/null", "r");
0094 (void) f;
0095
0096 start_time = time_get_ns();
0097 while ((ret = perf_buffer__poll(pb, 1000)) >= 0 && cnt < MAX_CNT) {
0098 }
0099 kill(0, SIGINT);
0100
0101 cleanup:
0102 bpf_link__destroy(link);
0103 bpf_object__close(obj);
0104 return ret;
0105 }