ebpf.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <fcntl.h>
  5. #include <dlfcn.h>
  6. #include <sys/utsname.h>
  7. #include "../libnetdata.h"
  8. char *ebpf_user_config_dir = CONFIG_DIR;
  9. char *ebpf_stock_config_dir = LIBCONFIG_DIR;
  10. /*
  11. static int clean_kprobe_event(FILE *out, char *filename, char *father_pid, netdata_ebpf_events_t *ptr)
  12. {
  13. int fd = open(filename, O_WRONLY | O_APPEND, 0);
  14. if (fd < 0) {
  15. if (out) {
  16. fprintf(out, "Cannot open %s : %s\n", filename, strerror(errno));
  17. }
  18. return 1;
  19. }
  20. char cmd[1024];
  21. int length = snprintf(cmd, 1023, "-:kprobes/%c_netdata_%s_%s", ptr->type, ptr->name, father_pid);
  22. int ret = 0;
  23. if (length > 0) {
  24. ssize_t written = write(fd, cmd, strlen(cmd));
  25. if (written < 0) {
  26. if (out) {
  27. fprintf(
  28. out, "Cannot remove the event (%d, %d) '%s' from %s : %s\n", getppid(), getpid(), cmd, filename,
  29. strerror((int)errno));
  30. }
  31. ret = 1;
  32. }
  33. }
  34. close(fd);
  35. return ret;
  36. }
  37. int clean_kprobe_events(FILE *out, int pid, netdata_ebpf_events_t *ptr)
  38. {
  39. debug(D_EXIT, "Cleaning parent process events.");
  40. char filename[FILENAME_MAX + 1];
  41. snprintf(filename, FILENAME_MAX, "%s%s", NETDATA_DEBUGFS, "kprobe_events");
  42. char removeme[16];
  43. snprintf(removeme, 15, "%d", pid);
  44. int i;
  45. for (i = 0; ptr[i].name; i++) {
  46. if (clean_kprobe_event(out, filename, removeme, &ptr[i])) {
  47. break;
  48. }
  49. }
  50. return 0;
  51. }
  52. */
  53. //----------------------------------------------------------------------------------------------------------------------
  54. /**
  55. * Get Kernel version
  56. *
  57. * Get the current kernel from /proc and returns an integer value representing it
  58. *
  59. * @return it returns a value representing the kernel version.
  60. */
  61. int ebpf_get_kernel_version()
  62. {
  63. char major[16], minor[16], patch[16];
  64. char ver[VERSION_STRING_LEN];
  65. char *version = ver;
  66. int fd = open("/proc/sys/kernel/osrelease", O_RDONLY);
  67. if (fd < 0)
  68. return -1;
  69. ssize_t len = read(fd, ver, sizeof(ver));
  70. if (len < 0) {
  71. close(fd);
  72. return -1;
  73. }
  74. close(fd);
  75. char *move = major;
  76. while (*version && *version != '.')
  77. *move++ = *version++;
  78. *move = '\0';
  79. version++;
  80. move = minor;
  81. while (*version && *version != '.')
  82. *move++ = *version++;
  83. *move = '\0';
  84. if (*version)
  85. version++;
  86. else
  87. return -1;
  88. move = patch;
  89. while (*version && *version != '\n' && *version != '-')
  90. *move++ = *version++;
  91. *move = '\0';
  92. // This new rule is fixing kernel version according the formula:
  93. // KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c)))
  94. // that was extracted from /usr/include/linux/version.h
  95. int ipatch = (int)str2l(patch);
  96. if (ipatch > 255)
  97. ipatch = 255;
  98. return ((int)(str2l(major) * 65536) + (int)(str2l(minor) * 256) + ipatch);
  99. }
  100. /**
  101. * Get RH release
  102. *
  103. * Read Red Hat release from /etc/redhat-release
  104. *
  105. * @return It returns RH release on success and -1 otherwise
  106. */
  107. int get_redhat_release()
  108. {
  109. char buffer[VERSION_STRING_LEN + 1];
  110. int major, minor;
  111. FILE *fp = fopen("/etc/redhat-release", "r");
  112. if (fp) {
  113. major = 0;
  114. minor = -1;
  115. size_t length = fread(buffer, sizeof(char), VERSION_STRING_LEN, fp);
  116. if (length > 4) {
  117. buffer[length] = '\0';
  118. char *end = strchr(buffer, '.');
  119. char *start;
  120. if (end) {
  121. *end = 0x0;
  122. if (end > buffer) {
  123. start = end - 1;
  124. major = strtol(start, NULL, 10);
  125. start = ++end;
  126. end++;
  127. if (end) {
  128. end = 0x00;
  129. minor = strtol(start, NULL, 10);
  130. } else {
  131. minor = -1;
  132. }
  133. }
  134. }
  135. }
  136. fclose(fp);
  137. return ((major * 256) + minor);
  138. } else {
  139. return -1;
  140. }
  141. }
  142. /**
  143. * Check if the kernel is in a list of rejected ones
  144. *
  145. * @return Returns 1 if the kernel is rejected, 0 otherwise.
  146. */
  147. static int kernel_is_rejected()
  148. {
  149. // Get kernel version from system
  150. char version_string[VERSION_STRING_LEN + 1];
  151. int version_string_len = 0;
  152. if (read_file("/proc/version_signature", version_string, VERSION_STRING_LEN)) {
  153. if (read_file("/proc/version", version_string, VERSION_STRING_LEN)) {
  154. struct utsname uname_buf;
  155. if (!uname(&uname_buf)) {
  156. info("Cannot check kernel version");
  157. return 0;
  158. }
  159. version_string_len =
  160. snprintfz(version_string, VERSION_STRING_LEN, "%s %s", uname_buf.release, uname_buf.version);
  161. }
  162. }
  163. if (!version_string_len)
  164. version_string_len = strlen(version_string);
  165. // Open a file with a list of rejected kernels
  166. char *config_dir = getenv("NETDATA_USER_CONFIG_DIR");
  167. if (config_dir == NULL) {
  168. config_dir = CONFIG_DIR;
  169. }
  170. char filename[FILENAME_MAX + 1];
  171. snprintfz(filename, FILENAME_MAX, "%s/ebpf.d/%s", config_dir, EBPF_KERNEL_REJECT_LIST_FILE);
  172. FILE *kernel_reject_list = fopen(filename, "r");
  173. if (!kernel_reject_list) {
  174. // Keep this to have compatibility with old versions
  175. snprintfz(filename, FILENAME_MAX, "%s/%s", config_dir, EBPF_KERNEL_REJECT_LIST_FILE);
  176. kernel_reject_list = fopen(filename, "r");
  177. if (!kernel_reject_list) {
  178. config_dir = getenv("NETDATA_STOCK_CONFIG_DIR");
  179. if (config_dir == NULL) {
  180. config_dir = LIBCONFIG_DIR;
  181. }
  182. snprintfz(filename, FILENAME_MAX, "%s/ebpf.d/%s", config_dir, EBPF_KERNEL_REJECT_LIST_FILE);
  183. kernel_reject_list = fopen(filename, "r");
  184. if (!kernel_reject_list)
  185. return 0;
  186. }
  187. }
  188. // Find if the kernel is in the reject list
  189. char *reject_string = NULL;
  190. size_t buf_len = 0;
  191. ssize_t reject_string_len;
  192. while ((reject_string_len = getline(&reject_string, &buf_len, kernel_reject_list) - 1) > 0) {
  193. if (version_string_len >= reject_string_len) {
  194. if (!strncmp(version_string, reject_string, reject_string_len)) {
  195. info("A buggy kernel is detected");
  196. fclose(kernel_reject_list);
  197. freez(reject_string);
  198. return 1;
  199. }
  200. }
  201. }
  202. fclose(kernel_reject_list);
  203. freez(reject_string);
  204. return 0;
  205. }
  206. static int has_ebpf_kernel_version(int version)
  207. {
  208. if (kernel_is_rejected())
  209. return 0;
  210. // Kernel 4.11.0 or RH > 7.5
  211. return (version >= NETDATA_MINIMUM_EBPF_KERNEL || get_redhat_release() >= NETDATA_MINIMUM_RH_VERSION);
  212. }
  213. int has_condition_to_run(int version)
  214. {
  215. if (!has_ebpf_kernel_version(version))
  216. return 0;
  217. return 1;
  218. }
  219. //----------------------------------------------------------------------------------------------------------------------
  220. /**
  221. * Kernel Name
  222. *
  223. * Select kernel name used by eBPF programs
  224. *
  225. * Netdata delivers for users eBPF programs with specific suffixes that represent the kernels they were
  226. * compiled, when we load the eBPF program, the suffix must be the nereast possible of the kernel running.
  227. *
  228. * @param selector select the kernel version.
  229. *
  230. * @return It returns the string to load kernel.
  231. */
  232. static char *ebpf_select_kernel_name(uint32_t selector)
  233. {
  234. static char *kernel_names[] = { NETDATA_IDX_STR_V3_10, NETDATA_IDX_STR_V4_14, NETDATA_IDX_STR_V4_16,
  235. NETDATA_IDX_STR_V4_18, NETDATA_IDX_STR_V5_4, NETDATA_IDX_STR_V5_10,
  236. NETDATA_IDX_STR_V5_11, NETDATA_IDX_STR_V5_15, NETDATA_IDX_STR_V5_16
  237. };
  238. return kernel_names[selector];
  239. }
  240. /**
  241. * Select Max Index
  242. *
  243. * Select last index that will be tested on host.
  244. *
  245. * @param is_rhf is Red Hat fammily?
  246. * @param kver the kernel version
  247. *
  248. * @return it returns the index to access kernel string.
  249. */
  250. static int ebpf_select_max_index(int is_rhf, uint32_t kver)
  251. {
  252. if (is_rhf > 0) { // Is Red Hat family
  253. if (kver >= NETDATA_EBPF_KERNEL_4_11)
  254. return NETDATA_IDX_V4_18;
  255. } else { // Kernels from kernel.org
  256. if (kver >= NETDATA_EBPF_KERNEL_5_16)
  257. return NETDATA_IDX_V5_16;
  258. else if (kver >= NETDATA_EBPF_KERNEL_5_15)
  259. return NETDATA_IDX_V5_15;
  260. else if (kver >= NETDATA_EBPF_KERNEL_5_11)
  261. return NETDATA_IDX_V5_11;
  262. else if (kver >= NETDATA_EBPF_KERNEL_5_10)
  263. return NETDATA_IDX_V5_10;
  264. else if (kver >= NETDATA_EBPF_KERNEL_4_17)
  265. return NETDATA_IDX_V5_4;
  266. else if (kver >= NETDATA_EBPF_KERNEL_4_15)
  267. return NETDATA_IDX_V4_16;
  268. else if (kver >= NETDATA_EBPF_KERNEL_4_11)
  269. return NETDATA_IDX_V4_14;
  270. }
  271. return NETDATA_IDX_V3_10;
  272. }
  273. /**
  274. * Select Index
  275. *
  276. * Select index to load data.
  277. *
  278. * @param kernels is the variable with kernel versions.
  279. * @param is_rhf is Red Hat fammily?
  280. * param kver the kernel version
  281. */
  282. static uint32_t ebpf_select_index(uint32_t kernels, int is_rhf, uint32_t kver)
  283. {
  284. uint32_t start = ebpf_select_max_index(is_rhf, kver);
  285. uint32_t idx;
  286. for (idx = start; idx; idx--) {
  287. if (kernels & 1 << idx)
  288. break;
  289. }
  290. return idx;
  291. }
  292. /**
  293. * Mount Name
  294. *
  295. * Mount name of eBPF program to be loaded.
  296. *
  297. * Netdata eBPF programs has the following format:
  298. *
  299. * Tnetdata_ebpf_N.V.o
  300. *
  301. * where:
  302. * T - Is the eBPF type. When starts with 'p', this means we are only adding probes,
  303. * and when they start with 'r' we are using retprobes.
  304. * N - The eBPF program name.
  305. * V - The kernel version in string format.
  306. *
  307. * @param out the vector where the name will be stored
  308. * @param path
  309. * @param len the size of the out vector.
  310. * @param kver the kernel version
  311. * @param name the eBPF program name.
  312. * @param is_return is return or entry ?
  313. */
  314. static void ebpf_mount_name(char *out, size_t len, char *path, uint32_t kver, const char *name, int is_return)
  315. {
  316. char *version = ebpf_select_kernel_name(kver);
  317. snprintfz(out, len, "%s/ebpf.d/%cnetdata_ebpf_%s.%s.o",
  318. path,
  319. (is_return) ? 'r' : 'p',
  320. name,
  321. version);
  322. }
  323. //----------------------------------------------------------------------------------------------------------------------
  324. /**
  325. * Statistics from targets
  326. *
  327. * Count the information from targets.
  328. *
  329. * @param report the output structure
  330. * @param targets vector with information about the eBPF plugin.
  331. */
  332. static void ebpf_stats_targets(ebpf_plugin_stats_t *report, netdata_ebpf_targets_t *targets)
  333. {
  334. if (!targets) {
  335. report->probes = report->tracepoints = report->trampolines = 0;
  336. return;
  337. }
  338. int i = 0;
  339. while (targets[i].name) {
  340. switch (targets[i].mode) {
  341. case EBPF_LOAD_PROBE: {
  342. report->probes++;
  343. break;
  344. }
  345. case EBPF_LOAD_RETPROBE: {
  346. report->retprobes++;
  347. break;
  348. }
  349. case EBPF_LOAD_TRACEPOINT: {
  350. report->tracepoints++;
  351. break;
  352. }
  353. case EBPF_LOAD_TRAMPOLINE: {
  354. report->trampolines++;
  355. break;
  356. }
  357. }
  358. i++;
  359. }
  360. }
  361. /**
  362. * Update General stats
  363. *
  364. * Update eBPF plugin statistics that has relationship with the thread.
  365. *
  366. * This function must be called with mutex associated to charts is locked.
  367. *
  368. * @param report the output structure
  369. * @param em the structure with information about how the module/thread is working.
  370. */
  371. void ebpf_update_stats(ebpf_plugin_stats_t *report, ebpf_module_t *em)
  372. {
  373. report->threads++;
  374. // It is not necessary to report more information.
  375. if (!em->enabled)
  376. return;
  377. report->running++;
  378. // In theory the `else if` is useless, because when this function is called, the module should not stay in
  379. // EBPF_LOAD_PLAY_DICE. We have this additional condition to detect errors from developers.
  380. if (em->load == EBPF_LOAD_LEGACY)
  381. report->legacy++;
  382. else if (em->load == EBPF_LOAD_CORE)
  383. report->core++;
  384. ebpf_stats_targets(report, em->targets);
  385. }
  386. //----------------------------------------------------------------------------------------------------------------------
  387. void ebpf_update_pid_table(ebpf_local_maps_t *pid, ebpf_module_t *em)
  388. {
  389. pid->user_input = em->pid_map_size;
  390. }
  391. /**
  392. * Update map size
  393. *
  394. * Update map size with information read from configuration files.
  395. *
  396. * @param map the structure with file descriptor to update.
  397. * @param lmap the structure with information from configuration files.
  398. * @param em the structure with information about how the module/thread is working.
  399. * @param map_name the name of the file used to log.
  400. */
  401. void ebpf_update_map_size(struct bpf_map *map, ebpf_local_maps_t *lmap, ebpf_module_t *em, const char *map_name)
  402. {
  403. uint32_t apps_type = NETDATA_EBPF_MAP_PID | NETDATA_EBPF_MAP_RESIZABLE;
  404. if (lmap->user_input && lmap->user_input != lmap->internal_input) {
  405. #ifdef NETDATA_INTERNAL_CHECKS
  406. info("Changing map %s from size %u to %u ", map_name, lmap->internal_input, lmap->user_input);
  407. #endif
  408. #ifdef LIBBPF_MAJOR_VERSION
  409. bpf_map__set_max_entries(map, lmap->user_input);
  410. #else
  411. bpf_map__resize(map, lmap->user_input);
  412. #endif
  413. } else if (((lmap->type & apps_type) == apps_type) && (!em->apps_charts) && (!em->cgroup_charts)) {
  414. lmap->user_input = ND_EBPF_DEFAULT_MIN_PID;
  415. #ifdef LIBBPF_MAJOR_VERSION
  416. bpf_map__set_max_entries(map, lmap->user_input);
  417. #else
  418. bpf_map__resize(map, lmap->user_input);
  419. #endif
  420. }
  421. }
  422. /**
  423. * Update Legacy map sizes
  424. *
  425. * Update map size for eBPF legacy code.
  426. *
  427. * @param program the structure with values read from binary.
  428. * @param em the structure with information about how the module/thread is working.
  429. */
  430. static void ebpf_update_legacy_map_sizes(struct bpf_object *program, ebpf_module_t *em)
  431. {
  432. struct bpf_map *map;
  433. ebpf_local_maps_t *maps = em->maps;
  434. if (!maps)
  435. return;
  436. bpf_map__for_each(map, program)
  437. {
  438. const char *map_name = bpf_map__name(map);
  439. int i = 0; ;
  440. while (maps[i].name) {
  441. ebpf_local_maps_t *w = &maps[i];
  442. if (w->type & NETDATA_EBPF_MAP_RESIZABLE) {
  443. if (!strcmp(w->name, map_name)) {
  444. ebpf_update_map_size(map, w, em, map_name);
  445. }
  446. }
  447. i++;
  448. }
  449. }
  450. }
  451. size_t ebpf_count_programs(struct bpf_object *obj)
  452. {
  453. size_t tot = 0;
  454. struct bpf_program *prog;
  455. bpf_object__for_each_program(prog, obj)
  456. {
  457. tot++;
  458. }
  459. return tot;
  460. }
  461. static ebpf_specify_name_t *ebpf_find_names(ebpf_specify_name_t *names, const char *prog_name)
  462. {
  463. size_t i = 0;
  464. while (names[i].program_name) {
  465. if (!strcmp(prog_name, names[i].program_name))
  466. return &names[i];
  467. i++;
  468. }
  469. return NULL;
  470. }
  471. static struct bpf_link **ebpf_attach_programs(struct bpf_object *obj, size_t length, ebpf_specify_name_t *names)
  472. {
  473. struct bpf_link **links = callocz(length , sizeof(struct bpf_link *));
  474. size_t i = 0;
  475. struct bpf_program *prog;
  476. ebpf_specify_name_t *w;
  477. bpf_object__for_each_program(prog, obj)
  478. {
  479. if (names) {
  480. const char *name = bpf_program__name(prog);
  481. w = ebpf_find_names(names, name);
  482. } else
  483. w = NULL;
  484. if (w) {
  485. enum bpf_prog_type type = bpf_program__get_type(prog);
  486. if (type == BPF_PROG_TYPE_KPROBE)
  487. links[i] = bpf_program__attach_kprobe(prog, w->retprobe, w->optional);
  488. } else
  489. links[i] = bpf_program__attach(prog);
  490. if (libbpf_get_error(links[i])) {
  491. links[i] = NULL;
  492. }
  493. i++;
  494. }
  495. return links;
  496. }
  497. static void ebpf_update_maps(ebpf_module_t *em, struct bpf_object *obj)
  498. {
  499. if (!em->maps)
  500. return;
  501. ebpf_local_maps_t *maps = em->maps;
  502. struct bpf_map *map;
  503. bpf_map__for_each(map, obj)
  504. {
  505. int fd = bpf_map__fd(map);
  506. if (maps) {
  507. const char *map_name = bpf_map__name(map);
  508. int j = 0; ;
  509. while (maps[j].name) {
  510. ebpf_local_maps_t *w = &maps[j];
  511. if (w->map_fd == ND_EBPF_MAP_FD_NOT_INITIALIZED && !strcmp(map_name, w->name))
  512. w->map_fd = fd;
  513. j++;
  514. }
  515. }
  516. }
  517. }
  518. /**
  519. * Update Controller
  520. *
  521. * Update controller value with user input.
  522. *
  523. * @param fd the table file descriptor
  524. * @param em structure with information about eBPF program we will load.
  525. */
  526. void ebpf_update_controller(int fd, ebpf_module_t *em)
  527. {
  528. uint32_t key = NETDATA_CONTROLLER_APPS_ENABLED;
  529. uint32_t value = (em->apps_charts & NETDATA_EBPF_APPS_FLAG_YES) | em->cgroup_charts;
  530. int ret = bpf_map_update_elem(fd, &key, &value, 0);
  531. if (ret)
  532. error("Add key(%u) for controller table failed.", key);
  533. }
  534. /**
  535. * Update Legacy controller
  536. *
  537. * Update legacy controller table when eBPF program has it.
  538. *
  539. * @param em structure with information about eBPF program we will load.
  540. * @param obj bpf object with tables.
  541. */
  542. static void ebpf_update_legacy_controller(ebpf_module_t *em, struct bpf_object *obj)
  543. {
  544. ebpf_local_maps_t *maps = em->maps;
  545. if (!maps)
  546. return;
  547. struct bpf_map *map;
  548. bpf_map__for_each(map, obj)
  549. {
  550. size_t i = 0;
  551. while (maps[i].name) {
  552. ebpf_local_maps_t *w = &maps[i];
  553. if (w->map_fd != ND_EBPF_MAP_FD_NOT_INITIALIZED && (w->type & NETDATA_EBPF_MAP_CONTROLLER)) {
  554. w->type &= ~NETDATA_EBPF_MAP_CONTROLLER;
  555. w->type |= NETDATA_EBPF_MAP_CONTROLLER_UPDATED;
  556. ebpf_update_controller(w->map_fd, em);
  557. }
  558. i++;
  559. }
  560. }
  561. }
  562. /**
  563. * Load Program
  564. *
  565. * Load eBPF program into kernel
  566. *
  567. * @param plugins_dir directory where binary are stored
  568. * @param em structure with information about eBPF program we will load.
  569. * @param kver the kernel version according /usr/include/linux/version.h
  570. * @param is_rhf is a kernel from Red Hat Family?
  571. * @param obj structure where we will store object loaded.
  572. *
  573. * @return it returns a link for each target we associated an eBPF program.
  574. */
  575. struct bpf_link **ebpf_load_program(char *plugins_dir, ebpf_module_t *em, int kver, int is_rhf,
  576. struct bpf_object **obj)
  577. {
  578. char lpath[4096];
  579. uint32_t idx = ebpf_select_index(em->kernels, is_rhf, kver);
  580. ebpf_mount_name(lpath, 4095, plugins_dir, idx, em->thread_name, em->mode);
  581. *obj = bpf_object__open_file(lpath, NULL);
  582. if (libbpf_get_error(obj)) {
  583. error("Cannot open BPF object %s", lpath);
  584. bpf_object__close(*obj);
  585. return NULL;
  586. }
  587. ebpf_update_legacy_map_sizes(*obj, em);
  588. if (bpf_object__load(*obj)) {
  589. error("ERROR: loading BPF object file failed %s\n", lpath);
  590. bpf_object__close(*obj);
  591. return NULL;
  592. }
  593. ebpf_update_maps(em, *obj);
  594. ebpf_update_legacy_controller(em, *obj);
  595. size_t count_programs = ebpf_count_programs(*obj);
  596. #ifdef NETDATA_INTERNAL_CHECKS
  597. info("eBPF program %s loaded with success!", lpath);
  598. #endif
  599. return ebpf_attach_programs(*obj, count_programs, em->names);
  600. }
  601. char *ebpf_find_symbol(char *search)
  602. {
  603. char filename[FILENAME_MAX + 1];
  604. char *ret = NULL;
  605. snprintfz(filename, FILENAME_MAX, "%s%s", netdata_configured_host_prefix, NETDATA_KALLSYMS);
  606. procfile *ff = procfile_open(filename, " \t", PROCFILE_FLAG_DEFAULT);
  607. if(unlikely(!ff)) {
  608. error("Cannot open %s%s", netdata_configured_host_prefix, NETDATA_KALLSYMS);
  609. return ret;
  610. }
  611. ff = procfile_readall(ff);
  612. if(unlikely(!ff))
  613. return ret;
  614. unsigned long i, lines = procfile_lines(ff);
  615. size_t length = strlen(search);
  616. for(i = 0; i < lines ; i++) {
  617. char *cmp = procfile_lineword(ff, i,2);;
  618. if (!strncmp(search, cmp, length)) {
  619. ret = strdupz(cmp);
  620. break;
  621. }
  622. }
  623. procfile_close(ff);
  624. return ret;
  625. }
  626. void ebpf_update_names(ebpf_specify_name_t *opt, ebpf_module_t *em)
  627. {
  628. int mode = em->mode;
  629. em->names = opt;
  630. size_t i = 0;
  631. while (opt[i].program_name) {
  632. opt[i].retprobe = (mode == MODE_RETURN);
  633. opt[i].optional = ebpf_find_symbol(opt[i].function_to_attach);
  634. i++;
  635. }
  636. }
  637. //----------------------------------------------------------------------------------------------------------------------
  638. void ebpf_mount_config_name(char *filename, size_t length, char *path, const char *config)
  639. {
  640. snprintf(filename, length, "%s/ebpf.d/%s", path, config);
  641. }
  642. int ebpf_load_config(struct config *config, char *filename)
  643. {
  644. return appconfig_load(config, filename, 0, NULL);
  645. }
  646. static netdata_run_mode_t ebpf_select_mode(char *mode)
  647. {
  648. if (!strcasecmp(mode,EBPF_CFG_LOAD_MODE_RETURN ))
  649. return MODE_RETURN;
  650. else if (!strcasecmp(mode, "dev"))
  651. return MODE_DEVMODE;
  652. return MODE_ENTRY;
  653. }
  654. static void ebpf_select_mode_string(char *output, size_t len, netdata_run_mode_t sel)
  655. {
  656. if (sel == MODE_RETURN)
  657. strncpyz(output, EBPF_CFG_LOAD_MODE_RETURN, len);
  658. else
  659. strncpyz(output, EBPF_CFG_LOAD_MODE_DEFAULT, len);
  660. }
  661. /**
  662. * Convert string to load mode
  663. *
  664. * Convert the string given as argument to value present in enum.
  665. *
  666. * @param str value read from configuraion file.
  667. *
  668. * @return It returns the value to be used.
  669. */
  670. netdata_ebpf_load_mode_t epbf_convert_string_to_load_mode(char *str)
  671. {
  672. if (!strcasecmp(str, EBPF_CFG_CORE_PROGRAM))
  673. return EBPF_LOAD_CORE;
  674. else if (!strcasecmp(str, EBPF_CFG_LEGACY_PROGRAM))
  675. return EBPF_LOAD_LEGACY;
  676. return EBPF_LOAD_PLAY_DICE;
  677. }
  678. /**
  679. * Convert load mode to string
  680. *
  681. * @param mode value that will select the string
  682. *
  683. * @return It returns the string associated to mode.
  684. */
  685. static char *ebpf_convert_load_mode_to_string(netdata_ebpf_load_mode_t mode)
  686. {
  687. if (mode == EBPF_LOAD_CORE)
  688. return EBPF_CFG_CORE_PROGRAM;
  689. else if (mode == EBPF_LOAD_LEGACY)
  690. return EBPF_CFG_LEGACY_PROGRAM;
  691. return EBPF_CFG_DEFAULT_PROGRAM;
  692. }
  693. /**
  694. * CO-RE type
  695. *
  696. * Select the preferential type of CO-RE
  697. *
  698. * @param str value read from configuration file.
  699. * @param lmode load mode used by collector.
  700. */
  701. netdata_ebpf_program_loaded_t ebpf_convert_core_type(char *str, netdata_run_mode_t lmode)
  702. {
  703. if (!strcasecmp(str, EBPF_CFG_ATTACH_TRACEPOINT))
  704. return EBPF_LOAD_TRACEPOINT;
  705. else if (!strcasecmp(str, EBPF_CFG_ATTACH_PROBE)) {
  706. return (lmode == MODE_ENTRY) ? EBPF_LOAD_PROBE : EBPF_LOAD_RETPROBE;
  707. }
  708. return EBPF_LOAD_TRAMPOLINE;
  709. }
  710. #ifdef LIBBPF_MAJOR_VERSION
  711. /**
  712. * Adjust Thread Load
  713. *
  714. * Adjust thread configuraton according specified load.
  715. *
  716. * @param mod the main structure that will be adjusted.
  717. * @param file the btf file used with thread.
  718. */
  719. void ebpf_adjust_thread_load(ebpf_module_t *mod, struct btf *file)
  720. {
  721. if (!file) {
  722. mod->load = EBPF_LOAD_LEGACY;
  723. } else if (mod->load == EBPF_LOAD_PLAY_DICE && file) {
  724. mod->load = EBPF_LOAD_CORE;
  725. }
  726. }
  727. /**
  728. * Parse BTF file
  729. *
  730. * Parse a specific BTF file present on filesystem
  731. *
  732. * @param filename the file that will be parsed.
  733. *
  734. * @return It returns a pointer for the file on success and NULL otherwise.
  735. */
  736. struct btf *ebpf_parse_btf_file(const char *filename)
  737. {
  738. struct btf *bf = btf__parse(filename, NULL);
  739. if (libbpf_get_error(bf)) {
  740. fprintf(stderr, "Cannot parse btf file");
  741. btf__free(bf);
  742. return NULL;
  743. }
  744. return bf;
  745. }
  746. /**
  747. * Load default btf file
  748. *
  749. * Load the default BTF file on environment.
  750. *
  751. * @param path is the fullpath
  752. * @param filename is the file inside BTF path.
  753. */
  754. struct btf *ebpf_load_btf_file(char *path, char *filename)
  755. {
  756. char fullpath[PATH_MAX + 1];
  757. snprintfz(fullpath, PATH_MAX, "%s/%s", path, filename);
  758. struct btf *ret = ebpf_parse_btf_file(fullpath);
  759. if (!ret)
  760. info("Your environment does not have BTF file %s/%s. The plugin will work with 'legacy' code.",
  761. path, filename);
  762. return ret;
  763. }
  764. /**
  765. * Find BTF attach type
  766. *
  767. * Search type fr current btf file.
  768. *
  769. * @param file is the structure for the btf file already parsed.
  770. */
  771. static inline const struct btf_type *ebpf_find_btf_attach_type(struct btf *file)
  772. {
  773. int id = btf__find_by_name_kind(file, "bpf_attach_type", BTF_KIND_ENUM);
  774. if (id < 0) {
  775. fprintf(stderr, "Cannot find 'bpf_attach_type'");
  776. return NULL;
  777. }
  778. return btf__type_by_id(file, id);
  779. }
  780. /**
  781. * Is function inside BTF
  782. *
  783. * Look for a specific function inside the given BTF file.
  784. *
  785. * @param file is the structure for the btf file already parsed.
  786. * @param function is the function that we want to find.
  787. */
  788. int ebpf_is_function_inside_btf(struct btf *file, char *function)
  789. {
  790. const struct btf_type *type = ebpf_find_btf_attach_type(file);
  791. if (!type)
  792. return -1;
  793. const struct btf_enum *e = btf_enum(type);
  794. int i, id;
  795. for (id = -1, i = 0; i < btf_vlen(type); i++, e++) {
  796. if (!strcmp(btf__name_by_offset(file, e->name_off), "BPF_TRACE_FENTRY")) {
  797. id = btf__find_by_name_kind(file, function, BTF_KIND_FUNC);
  798. break;
  799. }
  800. }
  801. return (id > 0) ? 1 : 0;
  802. }
  803. #endif
  804. /**
  805. * Update target with configuration
  806. *
  807. * Update target load mode with value.
  808. *
  809. * @param em the module structure
  810. * @param value value used to update.
  811. */
  812. static void ebpf_update_target_with_conf(ebpf_module_t *em, netdata_ebpf_program_loaded_t value)
  813. {
  814. netdata_ebpf_targets_t *targets = em->targets;
  815. if (!targets) {
  816. return;
  817. }
  818. int i = 0;
  819. while (targets[i].name) {
  820. targets[i].mode = value;
  821. i++;
  822. }
  823. }
  824. /**
  825. * Update Module using config
  826. *
  827. * Update configuration for a specific thread.
  828. *
  829. * @param modules structure that will be updated
  830. */
  831. void ebpf_update_module_using_config(ebpf_module_t *modules)
  832. {
  833. char default_value[EBPF_MAX_MODE_LENGTH + 1];
  834. ebpf_select_mode_string(default_value, EBPF_MAX_MODE_LENGTH, modules->mode);
  835. char *value = appconfig_get(modules->cfg, EBPF_GLOBAL_SECTION, EBPF_CFG_LOAD_MODE, default_value);
  836. modules->mode = ebpf_select_mode(value);
  837. modules->update_every = (int)appconfig_get_number(modules->cfg, EBPF_GLOBAL_SECTION,
  838. EBPF_CFG_UPDATE_EVERY, modules->update_every);
  839. modules->apps_charts = appconfig_get_boolean(modules->cfg, EBPF_GLOBAL_SECTION, EBPF_CFG_APPLICATION,
  840. (int) (modules->apps_charts & NETDATA_EBPF_APPS_FLAG_YES));
  841. modules->cgroup_charts = appconfig_get_boolean(modules->cfg, EBPF_GLOBAL_SECTION, EBPF_CFG_CGROUP,
  842. modules->cgroup_charts);
  843. modules->pid_map_size = (uint32_t)appconfig_get_number(modules->cfg, EBPF_GLOBAL_SECTION, EBPF_CFG_PID_SIZE,
  844. modules->pid_map_size);
  845. value = ebpf_convert_load_mode_to_string(modules->load);
  846. value = appconfig_get(modules->cfg, EBPF_GLOBAL_SECTION, EBPF_CFG_TYPE_FORMAT, value);
  847. modules->load = epbf_convert_string_to_load_mode(value);
  848. value = appconfig_get(modules->cfg, EBPF_GLOBAL_SECTION, EBPF_CFG_CORE_ATTACH, EBPF_CFG_ATTACH_TRAMPOLINE);
  849. netdata_ebpf_program_loaded_t fill_lm = ebpf_convert_core_type(value, modules->mode);
  850. ebpf_update_target_with_conf(modules, fill_lm);
  851. }
  852. /**
  853. * Update module
  854. *
  855. * When this function is called, it will load the configuration file and after this
  856. * it updates the global information of ebpf_module.
  857. * If the module has specific configuration, this function will load it, but it will not
  858. * update the variables.
  859. *
  860. * @param em the module structure
  861. */
  862. void ebpf_update_module(ebpf_module_t *em)
  863. {
  864. char filename[FILENAME_MAX+1];
  865. ebpf_mount_config_name(filename, FILENAME_MAX, ebpf_user_config_dir, em->config_file);
  866. if (!ebpf_load_config(em->cfg, filename)) {
  867. ebpf_mount_config_name(filename, FILENAME_MAX, ebpf_stock_config_dir, em->config_file);
  868. if (!ebpf_load_config(em->cfg, filename)) {
  869. error("Cannot load the ebpf configuration file %s", em->config_file);
  870. return;
  871. }
  872. }
  873. ebpf_update_module_using_config(em);
  874. }
  875. //----------------------------------------------------------------------------------------------------------------------
  876. /**
  877. * Load Address
  878. *
  879. * Helper used to get address from /proc/kallsym
  880. *
  881. * @param fa address structure
  882. * @param fd file descriptor loaded inside kernel.
  883. */
  884. void ebpf_load_addresses(ebpf_addresses_t *fa, int fd)
  885. {
  886. if (fa->addr)
  887. return ;
  888. procfile *ff = procfile_open("/proc/kallsyms", " \t:", PROCFILE_FLAG_DEFAULT);
  889. if (!ff)
  890. return;
  891. ff = procfile_readall(ff);
  892. if (!ff)
  893. return;
  894. fa->hash = simple_hash(fa->function);
  895. size_t lines = procfile_lines(ff), l;
  896. for(l = 0; l < lines ;l++) {
  897. char *fcnt = procfile_lineword(ff, l, 2);
  898. uint32_t hash = simple_hash(fcnt);
  899. if (fa->hash == hash && !strcmp(fcnt, fa->function)) {
  900. char addr[128];
  901. snprintf(addr, 127, "0x%s", procfile_lineword(ff, l, 0));
  902. fa->addr = (unsigned long) strtoul(addr, NULL, 16);
  903. uint32_t key = 0;
  904. bpf_map_update_elem(fd, &key, &fa->addr, BPF_ANY);
  905. }
  906. }
  907. procfile_close(ff);
  908. }
  909. //----------------------------------------------------------------------------------------------------------------------
  910. /**
  911. * Fill Algorithms
  912. *
  913. * Set one unique dimension for all vector position.
  914. *
  915. * @param algorithms the output vector
  916. * @param length number of elements of algorithms vector
  917. * @param algorithm algorithm used on charts.
  918. */
  919. void ebpf_fill_algorithms(int *algorithms, size_t length, int algorithm)
  920. {
  921. size_t i;
  922. for (i = 0; i < length; i++) {
  923. algorithms[i] = algorithm;
  924. }
  925. }
  926. /**
  927. * Fill Histogram dimension
  928. *
  929. * Fill the histogram dimension with the specified ranges
  930. */
  931. char **ebpf_fill_histogram_dimension(size_t maximum)
  932. {
  933. char *dimensions[] = { "us", "ms", "s"};
  934. int previous_dim = 0, current_dim = 0;
  935. uint32_t previous_level = 1000, current_level = 1000;
  936. uint32_t previous_divisor = 1, current_divisor = 1;
  937. uint32_t current = 1, previous = 0;
  938. uint32_t selector;
  939. char **out = callocz(maximum, sizeof(char *));
  940. char range[128];
  941. size_t end = maximum - 1;
  942. for (selector = 0; selector < end; selector++) {
  943. snprintf(range, 127, "%u%s->%u%s", previous/previous_divisor, dimensions[previous_dim],
  944. current/current_divisor, dimensions[current_dim]);
  945. out[selector] = strdupz(range);
  946. previous = current;
  947. current <<= 1;
  948. if (previous_dim != 2 && previous > previous_level) {
  949. previous_dim++;
  950. previous_divisor *= 1000;
  951. previous_level *= 1000;
  952. }
  953. if (current_dim != 2 && current > current_level) {
  954. current_dim++;
  955. current_divisor *= 1000;
  956. current_level *= 1000;
  957. }
  958. }
  959. snprintf(range, 127, "%u%s->+Inf", previous/previous_divisor, dimensions[previous_dim]);
  960. out[selector] = strdupz(range);
  961. return out;
  962. }
  963. /**
  964. * Histogram dimension cleanup
  965. *
  966. * Cleanup dimensions allocated with function ebpf_fill_histogram_dimension
  967. *
  968. * @param ptr
  969. * @param length
  970. */
  971. void ebpf_histogram_dimension_cleanup(char **ptr, size_t length)
  972. {
  973. size_t i;
  974. for (i = 0; i < length; i++) {
  975. freez(ptr[i]);
  976. }
  977. freez(ptr);
  978. }
  979. //----------------------------------------------------------------------------------------------------------------------
  980. /**
  981. * Open tracepoint path
  982. *
  983. * @param filename pointer to store the path
  984. * @param length file length
  985. * @param subsys is the name of your subsystem.
  986. * @param eventname is the name of the event to trace.
  987. * @param flags flags used with syscall open
  988. *
  989. * @return it returns a positive value on success and a negative otherwise.
  990. */
  991. static inline int ebpf_open_tracepoint_path(char *filename, size_t length, char *subsys, char *eventname, int flags)
  992. {
  993. snprintfz(filename, length, "%s/events/%s/%s/enable", NETDATA_DEBUGFS, subsys, eventname);
  994. return open(filename, flags, 0);
  995. }
  996. /**
  997. * Is tracepoint enabled
  998. *
  999. * Check whether the tracepoint is enabled.
  1000. *
  1001. * @param subsys is the name of your subsystem.
  1002. * @param eventname is the name of the event to trace.
  1003. *
  1004. * @return it returns 1 when it is enabled, 0 when it is disabled and -1 on error.
  1005. */
  1006. int ebpf_is_tracepoint_enabled(char *subsys, char *eventname)
  1007. {
  1008. char text[FILENAME_MAX + 1];
  1009. int fd = ebpf_open_tracepoint_path(text, FILENAME_MAX, subsys, eventname, O_RDONLY);
  1010. if (fd < 0) {
  1011. return -1;
  1012. }
  1013. ssize_t length = read(fd, text, 1);
  1014. if (length != 1) {
  1015. close(fd);
  1016. return -1;
  1017. }
  1018. close(fd);
  1019. return (text[0] == '1') ? CONFIG_BOOLEAN_YES : CONFIG_BOOLEAN_NO;
  1020. }
  1021. /**
  1022. * Change Tracing values
  1023. *
  1024. * Change value for specific tracepoint enabling or disabling it according value given.
  1025. *
  1026. * @param subsys is the name of your subsystem.
  1027. * @param eventname is the name of the event to trace.
  1028. * @param value a value to enable (1) or disable (0) a tracepoint.
  1029. *
  1030. * @return It returns 0 on success and -1 otherwise
  1031. */
  1032. static int ebpf_change_tracing_values(char *subsys, char *eventname, char *value)
  1033. {
  1034. if (strcmp("0", value) && strcmp("1", value)) {
  1035. error("Invalid value given to either enable or disable a tracepoint.");
  1036. return -1;
  1037. }
  1038. char filename[1024];
  1039. int fd = ebpf_open_tracepoint_path(filename, 1023, subsys, eventname, O_WRONLY);
  1040. if (fd < 0) {
  1041. return -1;
  1042. }
  1043. ssize_t written = write(fd, value, strlen(value));
  1044. if (written < 0) {
  1045. close(fd);
  1046. return -1;
  1047. }
  1048. close(fd);
  1049. return 0;
  1050. }
  1051. /**
  1052. * Enable tracing values
  1053. *
  1054. * Enable a tracepoint on a system
  1055. *
  1056. * @param subsys is the name of your subsystem.
  1057. * @param eventname is the name of the event to trace.
  1058. *
  1059. * @return It returns 0 on success and -1 otherwise
  1060. */
  1061. int ebpf_enable_tracing_values(char *subsys, char *eventname)
  1062. {
  1063. return ebpf_change_tracing_values(subsys, eventname, "1");
  1064. }
  1065. /**
  1066. * Disable tracing values
  1067. *
  1068. * Disable tracing points enabled by collector
  1069. *
  1070. * @param subsys is the name of your subsystem.
  1071. * @param eventname is the name of the event to trace.
  1072. *
  1073. * @return It returns 0 on success and -1 otherwise
  1074. */
  1075. int ebpf_disable_tracing_values(char *subsys, char *eventname)
  1076. {
  1077. return ebpf_change_tracing_values(subsys, eventname, "0");
  1078. }
  1079. /**
  1080. * Select PC prefix
  1081. *
  1082. * Identify the prefix to run on PC architecture.
  1083. *
  1084. * @return It returns 32 or 64 according to host arch.
  1085. */
  1086. static uint32_t ebpf_select_pc_prefix()
  1087. {
  1088. long counter = 1;
  1089. uint32_t i;
  1090. for (i = 0; i < 128; i++) {
  1091. counter <<= 1;
  1092. if (counter < 0)
  1093. break;
  1094. }
  1095. return counter;
  1096. }
  1097. /**
  1098. * Select Host Prefix
  1099. *
  1100. * Select prefix to syscall when host is running a kernel newer than 4.17.0
  1101. *
  1102. * @param output the vector to store data.
  1103. * @param length length of output vector.
  1104. * @param syscall the syscall that prefix will be attached;
  1105. * @param kver the current kernel version in format MAJOR*65536 + MINOR*256 + PATCH
  1106. */
  1107. void ebpf_select_host_prefix(char *output, size_t length, char *syscall, int kver)
  1108. {
  1109. if (kver < NETDATA_EBPF_KERNEL_4_17)
  1110. snprintfz(output, length, "sys_%s", syscall);
  1111. else {
  1112. uint32_t arch = ebpf_select_pc_prefix();
  1113. // Prefix selected according https://www.kernel.org/doc/html/latest/process/adding-syscalls.html
  1114. char *prefix = (arch == 32) ? "__ia32" : "__x64";
  1115. snprintfz(output, length, "%s_sys_%s", prefix, syscall);
  1116. }
  1117. }