Blame view

samples/bpf/test_cgrp2_sock2.c 1.38 KB
b24413180   Greg Kroah-Hartman   License cleanup: ...
1
  // SPDX-License-Identifier: GPL-2.0
554ae6e79   David Ahern   samples/bpf: add ...
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  /* eBPF example program:
   *
   * - Loads eBPF program
   *
   *   The eBPF program loads a filter from file and attaches the
   *   program to a cgroup using BPF_PROG_ATTACH
   */
  
  #define _GNU_SOURCE
  
  #include <stdio.h>
  #include <stdlib.h>
  #include <stddef.h>
  #include <string.h>
  #include <unistd.h>
  #include <assert.h>
  #include <errno.h>
  #include <fcntl.h>
  #include <net/if.h>
  #include <linux/bpf.h>
8d9304507   Jakub Kicinski   samples: bpf: ren...
22
  #include <bpf/bpf.h>
554ae6e79   David Ahern   samples/bpf: add ...
23

8d9304507   Jakub Kicinski   samples: bpf: ren...
24
  #include "bpf_insn.h"
554ae6e79   David Ahern   samples/bpf: add ...
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  #include "bpf_load.h"
  
  static int usage(const char *argv0)
  {
  	printf("Usage: %s cg-path filter-path [filter-id]
  ", argv0);
  	return EXIT_FAILURE;
  }
  
  int main(int argc, char **argv)
  {
  	int cg_fd, ret, filter_id = 0;
  
  	if (argc < 3)
  		return usage(argv[0]);
  
  	cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
  	if (cg_fd < 0) {
  		printf("Failed to open cgroup path: '%s'
  ", strerror(errno));
  		return EXIT_FAILURE;
  	}
  
  	if (load_bpf_file(argv[2]))
  		return EXIT_FAILURE;
  
  	printf("Output from kernel verifier:
  %s
  -------
  ", bpf_log_buf);
  
  	if (argc > 3)
  		filter_id = atoi(argv[3]);
ee583014a   Dan Carpenter   samples/bpf: test...
58
  	if (filter_id >= prog_cnt) {
554ae6e79   David Ahern   samples/bpf: add ...
59
60
61
62
63
64
  		printf("Invalid program id; program not found in file
  ");
  		return EXIT_FAILURE;
  	}
  
  	ret = bpf_prog_attach(prog_fd[filter_id], cg_fd,
7f6776333   Alexei Starovoitov   bpf: introduce BP...
65
  			      BPF_CGROUP_INET_SOCK_CREATE, 0);
554ae6e79   David Ahern   samples/bpf: add ...
66
67
68
69
70
71
72
73
74
  	if (ret < 0) {
  		printf("Failed to attach prog to cgroup: '%s'
  ",
  		       strerror(errno));
  		return EXIT_FAILURE;
  	}
  
  	return EXIT_SUCCESS;
  }