0001
0002
0003
0004 #include <linux/unistd.h>
0005 #include <linux/bpf.h>
0006
0007 #include <stdio.h>
0008 #include <stdint.h>
0009 #include <unistd.h>
0010 #include <string.h>
0011 #include <errno.h>
0012 #include <fcntl.h>
0013
0014 #include <bpf/bpf.h>
0015
0016 static void usage(void)
0017 {
0018 printf("Usage: test_cgrp2_array_pin [...]\n");
0019 printf(" -F <file> File to pin an BPF cgroup array\n");
0020 printf(" -U <file> Update an already pinned BPF cgroup array\n");
0021 printf(" -v <value> Full path of the cgroup2\n");
0022 printf(" -h Display this help\n");
0023 }
0024
0025 int main(int argc, char **argv)
0026 {
0027 const char *pinned_file = NULL, *cg2 = NULL;
0028 int create_array = 1;
0029 int array_key = 0;
0030 int array_fd = -1;
0031 int cg2_fd = -1;
0032 int ret = -1;
0033 int opt;
0034
0035 while ((opt = getopt(argc, argv, "F:U:v:")) != -1) {
0036 switch (opt) {
0037
0038 case 'F':
0039 pinned_file = optarg;
0040 break;
0041 case 'U':
0042 pinned_file = optarg;
0043 create_array = 0;
0044 break;
0045 case 'v':
0046 cg2 = optarg;
0047 break;
0048 default:
0049 usage();
0050 goto out;
0051 }
0052 }
0053
0054 if (!cg2 || !pinned_file) {
0055 usage();
0056 goto out;
0057 }
0058
0059 cg2_fd = open(cg2, O_RDONLY);
0060 if (cg2_fd < 0) {
0061 fprintf(stderr, "open(%s,...): %s(%d)\n",
0062 cg2, strerror(errno), errno);
0063 goto out;
0064 }
0065
0066 if (create_array) {
0067 array_fd = bpf_map_create(BPF_MAP_TYPE_CGROUP_ARRAY, NULL,
0068 sizeof(uint32_t), sizeof(uint32_t),
0069 1, NULL);
0070 if (array_fd < 0) {
0071 fprintf(stderr,
0072 "bpf_create_map(BPF_MAP_TYPE_CGROUP_ARRAY,...): %s(%d)\n",
0073 strerror(errno), errno);
0074 goto out;
0075 }
0076 } else {
0077 array_fd = bpf_obj_get(pinned_file);
0078 if (array_fd < 0) {
0079 fprintf(stderr, "bpf_obj_get(%s): %s(%d)\n",
0080 pinned_file, strerror(errno), errno);
0081 goto out;
0082 }
0083 }
0084
0085 ret = bpf_map_update_elem(array_fd, &array_key, &cg2_fd, 0);
0086 if (ret) {
0087 perror("bpf_map_update_elem");
0088 goto out;
0089 }
0090
0091 if (create_array) {
0092 ret = bpf_obj_pin(array_fd, pinned_file);
0093 if (ret) {
0094 fprintf(stderr, "bpf_obj_pin(..., %s): %s(%d)\n",
0095 pinned_file, strerror(errno), errno);
0096 goto out;
0097 }
0098 }
0099
0100 out:
0101 if (array_fd != -1)
0102 close(array_fd);
0103 if (cg2_fd != -1)
0104 close(cg2_fd);
0105 return ret;
0106 }