test_cgrp2_array_pin.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2016 Facebook
  3. */
  4. #include <linux/unistd.h>
  5. #include <linux/bpf.h>
  6. #include <stdio.h>
  7. #include <stdint.h>
  8. #include <unistd.h>
  9. #include <string.h>
  10. #include <errno.h>
  11. #include <fcntl.h>
  12. #include <bpf/bpf.h>
  13. static void usage(void)
  14. {
  15. printf("Usage: test_cgrp2_array_pin [...]\n");
  16. printf(" -F <file> File to pin an BPF cgroup array\n");
  17. printf(" -U <file> Update an already pinned BPF cgroup array\n");
  18. printf(" -v <value> Full path of the cgroup2\n");
  19. printf(" -h Display this help\n");
  20. }
  21. int main(int argc, char **argv)
  22. {
  23. const char *pinned_file = NULL, *cg2 = NULL;
  24. int create_array = 1;
  25. int array_key = 0;
  26. int array_fd = -1;
  27. int cg2_fd = -1;
  28. int ret = -1;
  29. int opt;
  30. while ((opt = getopt(argc, argv, "F:U:v:")) != -1) {
  31. switch (opt) {
  32. /* General args */
  33. case 'F':
  34. pinned_file = optarg;
  35. break;
  36. case 'U':
  37. pinned_file = optarg;
  38. create_array = 0;
  39. break;
  40. case 'v':
  41. cg2 = optarg;
  42. break;
  43. default:
  44. usage();
  45. goto out;
  46. }
  47. }
  48. if (!cg2 || !pinned_file) {
  49. usage();
  50. goto out;
  51. }
  52. cg2_fd = open(cg2, O_RDONLY);
  53. if (cg2_fd < 0) {
  54. fprintf(stderr, "open(%s,...): %s(%d)\n",
  55. cg2, strerror(errno), errno);
  56. goto out;
  57. }
  58. if (create_array) {
  59. array_fd = bpf_create_map(BPF_MAP_TYPE_CGROUP_ARRAY,
  60. sizeof(uint32_t), sizeof(uint32_t),
  61. 1, 0);
  62. if (array_fd < 0) {
  63. fprintf(stderr,
  64. "bpf_create_map(BPF_MAP_TYPE_CGROUP_ARRAY,...): %s(%d)\n",
  65. strerror(errno), errno);
  66. goto out;
  67. }
  68. } else {
  69. array_fd = bpf_obj_get(pinned_file);
  70. if (array_fd < 0) {
  71. fprintf(stderr, "bpf_obj_get(%s): %s(%d)\n",
  72. pinned_file, strerror(errno), errno);
  73. goto out;
  74. }
  75. }
  76. ret = bpf_map_update_elem(array_fd, &array_key, &cg2_fd, 0);
  77. if (ret) {
  78. perror("bpf_map_update_elem");
  79. goto out;
  80. }
  81. if (create_array) {
  82. ret = bpf_obj_pin(array_fd, pinned_file);
  83. if (ret) {
  84. fprintf(stderr, "bpf_obj_pin(..., %s): %s(%d)\n",
  85. pinned_file, strerror(errno), errno);
  86. goto out;
  87. }
  88. }
  89. out:
  90. if (array_fd != -1)
  91. close(array_fd);
  92. if (cg2_fd != -1)
  93. close(cg2_fd);
  94. return ret;
  95. }