test_cgrp2_array_pin.c 2.2 KB

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