1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright (C) 2021 Red Hat Inc, Daniel Bristot de Oliveira <bristot@kernel.org> 4 */ 5 6 #define _GNU_SOURCE 7 #ifdef HAVE_LIBCPUPOWER_SUPPORT 8 #include <cpuidle.h> 9 #endif /* HAVE_LIBCPUPOWER_SUPPORT */ 10 #include <dirent.h> 11 #include <stdarg.h> 12 #include <stdlib.h> 13 #include <string.h> 14 #include <unistd.h> 15 #include <ctype.h> 16 #include <errno.h> 17 #include <fcntl.h> 18 #include <sched.h> 19 #include <stdio.h> 20 #include <limits.h> 21 22 #include "common.h" 23 24 #define MAX_MSG_LENGTH 1024 25 int config_debug; 26 27 /* 28 * err_msg - print an error message to the stderr 29 */ 30 void err_msg(const char *fmt, ...) 31 { 32 char message[MAX_MSG_LENGTH]; 33 va_list ap; 34 35 va_start(ap, fmt); 36 vsnprintf(message, sizeof(message), fmt, ap); 37 va_end(ap); 38 39 fprintf(stderr, "%s", message); 40 } 41 42 /* 43 * debug_msg - print a debug message to stderr if debug is set 44 */ 45 void debug_msg(const char *fmt, ...) 46 { 47 char message[MAX_MSG_LENGTH]; 48 va_list ap; 49 50 if (!config_debug) 51 return; 52 53 va_start(ap, fmt); 54 vsnprintf(message, sizeof(message), fmt, ap); 55 va_end(ap); 56 57 fprintf(stderr, "%s", message); 58 } 59 60 /* 61 * fatal - print an error message and EOL to stderr and exit with ERROR 62 */ 63 void fatal(const char *fmt, ...) 64 { 65 va_list ap; 66 67 va_start(ap, fmt); 68 vfprintf(stderr, fmt, ap); 69 va_end(ap); 70 fprintf(stderr, "\n"); 71 72 exit(ERROR); 73 } 74 75 /* 76 * get_llong_from_str - get a long long int from a string 77 */ 78 long long get_llong_from_str(char *start) 79 { 80 long long value; 81 char *end; 82 83 errno = 0; 84 value = strtoll(start, &end, 10); 85 if (errno || start == end) 86 return -1; 87 88 return value; 89 } 90 91 /* 92 * get_duration - fill output with a human readable duration since start_time 93 */ 94 void get_duration(time_t start_time, char *output, int output_size) 95 { 96 time_t now = time(NULL); 97 struct tm *tm_info; 98 time_t duration; 99 100 duration = difftime(now, start_time); 101 tm_info = gmtime(&duration); 102 103 snprintf(output, output_size, "%3d %02d:%02d:%02d", 104 tm_info->tm_yday, 105 tm_info->tm_hour, 106 tm_info->tm_min, 107 tm_info->tm_sec); 108 } 109 110 /* 111 * parse_cpu_set - parse a cpu_list filling cpu_set_t argument 112 * 113 * Receives a cpu list, like 1-3,5 (cpus 1, 2, 3, 5), and then set 114 * filling cpu_set_t argument. 115 * 116 * Returns 0 on success, 1 otherwise. 117 */ 118 int parse_cpu_set(char *cpu_list, cpu_set_t *set) 119 { 120 const char *p; 121 int end_cpu; 122 int cpu; 123 int i; 124 125 CPU_ZERO(set); 126 127 for (p = cpu_list; *p; ) { 128 cpu = atoi(p); 129 if (cpu < 0 || (!cpu && *p != '0') || cpu >= nr_cpus) 130 goto err; 131 132 while (isdigit(*p)) 133 p++; 134 if (*p == '-') { 135 p++; 136 end_cpu = atoi(p); 137 if (end_cpu < cpu || (!end_cpu && *p != '0') || end_cpu >= nr_cpus) 138 goto err; 139 while (isdigit(*p)) 140 p++; 141 } else 142 end_cpu = cpu; 143 144 if (cpu == end_cpu) { 145 debug_msg("cpu_set: adding cpu %d\n", cpu); 146 CPU_SET(cpu, set); 147 } else { 148 for (i = cpu; i <= end_cpu; i++) { 149 debug_msg("cpu_set: adding cpu %d\n", i); 150 CPU_SET(i, set); 151 } 152 } 153 154 if (*p == ',') 155 p++; 156 } 157 158 return 0; 159 err: 160 debug_msg("Error parsing the cpu set %s\n", cpu_list); 161 return 1; 162 } 163 164 /* 165 * parse_stack_format - parse the stack format 166 * 167 * Return: the stack format on success, -1 otherwise. 168 */ 169 int parse_stack_format(char *arg) 170 { 171 if (!strcmp(arg, "truncate")) 172 return STACK_FORMAT_TRUNCATE; 173 if (!strcmp(arg, "skip")) 174 return STACK_FORMAT_SKIP; 175 if (!strcmp(arg, "full")) 176 return STACK_FORMAT_FULL; 177 178 debug_msg("Error parsing the stack format %s\n", arg); 179 return -1; 180 } 181 182 /* 183 * parse_duration - parse duration with s/m/h/d suffix converting it to seconds 184 */ 185 long parse_seconds_duration(char *val) 186 { 187 char *end; 188 long t; 189 190 t = strtol(val, &end, 10); 191 192 if (end) { 193 switch (*end) { 194 case 's': 195 case 'S': 196 break; 197 case 'm': 198 case 'M': 199 t *= 60; 200 break; 201 case 'h': 202 case 'H': 203 t *= 60 * 60; 204 break; 205 206 case 'd': 207 case 'D': 208 t *= 24 * 60 * 60; 209 break; 210 } 211 } 212 213 return t; 214 } 215 216 /* 217 * parse_ns_duration - parse duration with ns/us/ms/s converting it to nanoseconds 218 */ 219 long parse_ns_duration(char *val) 220 { 221 char *end; 222 long t; 223 224 t = strtol(val, &end, 10); 225 226 if (end) { 227 if (!strncmp(end, "ns", 2)) { 228 return t; 229 } else if (!strncmp(end, "us", 2)) { 230 t *= 1000; 231 return t; 232 } else if (!strncmp(end, "ms", 2)) { 233 t *= 1000 * 1000; 234 return t; 235 } else if (!strncmp(end, "s", 1)) { 236 t *= 1000 * 1000 * 1000; 237 return t; 238 } 239 return -1; 240 } 241 242 return t; 243 } 244 245 /* 246 * This is a set of helper functions to use SCHED_DEADLINE. 247 */ 248 #ifndef __NR_sched_setattr 249 # ifdef __x86_64__ 250 # define __NR_sched_setattr 314 251 # elif __i386__ 252 # define __NR_sched_setattr 351 253 # elif __arm__ 254 # define __NR_sched_setattr 380 255 # elif __aarch64__ || __riscv 256 # define __NR_sched_setattr 274 257 # elif __powerpc__ 258 # define __NR_sched_setattr 355 259 # elif __s390x__ 260 # define __NR_sched_setattr 345 261 # elif __loongarch__ 262 # define __NR_sched_setattr 274 263 # endif 264 #endif 265 266 #define SCHED_DEADLINE 6 267 268 static inline int syscall_sched_setattr(pid_t pid, const struct sched_attr *attr, 269 unsigned int flags) { 270 return syscall(__NR_sched_setattr, pid, attr, flags); 271 } 272 273 int __set_sched_attr(int pid, struct sched_attr *attr) 274 { 275 int flags = 0; 276 int retval; 277 278 retval = syscall_sched_setattr(pid, attr, flags); 279 if (retval < 0) { 280 err_msg("Failed to set sched attributes to the pid %d: %s\n", 281 pid, strerror(errno)); 282 return 1; 283 } 284 285 return 0; 286 } 287 288 /* 289 * procfs_is_workload_pid - check if a procfs entry contains a comm_prefix* comm 290 * 291 * Check if the procfs entry is a directory of a process, and then check if the 292 * process has a comm with the prefix set in char *comm_prefix. As the 293 * current users of this function only check for kernel threads, there is no 294 * need to check for the threads for the process. 295 * 296 * Return: True if the proc_entry contains a comm file with comm_prefix*. 297 * Otherwise returns false. 298 */ 299 static int procfs_is_workload_pid(const char *comm_prefix, struct dirent *proc_entry) 300 { 301 char buffer[MAX_PATH]; 302 int comm_fd, retval; 303 char *t_name; 304 305 if (proc_entry->d_type != DT_DIR) 306 return 0; 307 308 if (*proc_entry->d_name == '.') 309 return 0; 310 311 /* check if the string is a pid */ 312 for (t_name = proc_entry->d_name; t_name; t_name++) { 313 if (!isdigit(*t_name)) 314 break; 315 } 316 317 if (*t_name != '\0') 318 return 0; 319 320 snprintf(buffer, MAX_PATH, "/proc/%s/comm", proc_entry->d_name); 321 comm_fd = open(buffer, O_RDONLY); 322 if (comm_fd < 0) 323 return 0; 324 325 memset(buffer, 0, MAX_PATH); 326 retval = read(comm_fd, buffer, MAX_PATH); 327 328 close(comm_fd); 329 330 if (retval <= 0) 331 return 0; 332 333 buffer[MAX_PATH-1] = '\0'; 334 if (!str_has_prefix(buffer, comm_prefix)) 335 return 0; 336 337 /* comm already have \n */ 338 debug_msg("Found workload pid:%s comm:%s", proc_entry->d_name, buffer); 339 340 return 1; 341 } 342 343 /* 344 * set_comm_sched_attr - set sched params to threads starting with char *comm_prefix 345 * 346 * This function uses procfs to list the currently running threads and then set the 347 * sched_attr *attr to the threads that start with char *comm_prefix. It is 348 * mainly used to set the priority to the kernel threads created by the 349 * tracers. 350 */ 351 int set_comm_sched_attr(const char *comm_prefix, struct sched_attr *attr) 352 { 353 struct dirent *proc_entry; 354 DIR *procfs; 355 int retval; 356 int pid; 357 358 if (strlen(comm_prefix) >= MAX_PATH) { 359 err_msg("Command prefix is too long: %d < strlen(%s)\n", 360 MAX_PATH, comm_prefix); 361 return 1; 362 } 363 364 procfs = opendir("/proc"); 365 if (!procfs) { 366 err_msg("Could not open procfs\n"); 367 return 1; 368 } 369 370 while ((proc_entry = readdir(procfs))) { 371 372 retval = procfs_is_workload_pid(comm_prefix, proc_entry); 373 if (!retval) 374 continue; 375 376 if (strtoi(proc_entry->d_name, &pid)) { 377 err_msg("'%s' is not a valid pid", proc_entry->d_name); 378 goto out_err; 379 } 380 /* procfs_is_workload_pid confirmed it is a pid */ 381 retval = __set_sched_attr(pid, attr); 382 if (retval) { 383 err_msg("Error setting sched attributes for pid:%s\n", proc_entry->d_name); 384 goto out_err; 385 } 386 387 debug_msg("Set sched attributes for pid:%s\n", proc_entry->d_name); 388 } 389 return 0; 390 391 out_err: 392 closedir(procfs); 393 return 1; 394 } 395 396 #define INVALID_VAL (~0L) 397 static long get_long_ns_after_colon(char *start) 398 { 399 long val = INVALID_VAL; 400 401 /* find the ":" */ 402 start = strstr(start, ":"); 403 if (!start) 404 return -1; 405 406 /* skip ":" */ 407 start++; 408 val = parse_ns_duration(start); 409 410 return val; 411 } 412 413 static long get_long_after_colon(char *start) 414 { 415 long val = INVALID_VAL; 416 417 /* find the ":" */ 418 start = strstr(start, ":"); 419 if (!start) 420 return -1; 421 422 /* skip ":" */ 423 start++; 424 val = get_llong_from_str(start); 425 426 return val; 427 } 428 429 /* 430 * parse priority in the format: 431 * SCHED_OTHER: 432 * o:<prio> 433 * O:<prio> 434 * SCHED_RR: 435 * r:<prio> 436 * R:<prio> 437 * SCHED_FIFO: 438 * f:<prio> 439 * F:<prio> 440 * SCHED_DEADLINE: 441 * d:runtime:period 442 * D:runtime:period 443 */ 444 int parse_prio(char *arg, struct sched_attr *sched_param) 445 { 446 long prio; 447 long runtime; 448 long period; 449 450 memset(sched_param, 0, sizeof(*sched_param)); 451 sched_param->size = sizeof(*sched_param); 452 453 switch (arg[0]) { 454 case 'd': 455 case 'D': 456 /* d:runtime:period */ 457 if (strlen(arg) < 4) 458 return -1; 459 460 runtime = get_long_ns_after_colon(arg); 461 if (runtime == INVALID_VAL) 462 return -1; 463 464 period = get_long_ns_after_colon(&arg[2]); 465 if (period == INVALID_VAL) 466 return -1; 467 468 if (runtime > period) 469 return -1; 470 471 sched_param->sched_policy = SCHED_DEADLINE; 472 sched_param->sched_runtime = runtime; 473 sched_param->sched_deadline = period; 474 sched_param->sched_period = period; 475 break; 476 case 'f': 477 case 'F': 478 /* f:prio */ 479 prio = get_long_after_colon(arg); 480 if (prio == INVALID_VAL) 481 return -1; 482 483 if (prio < sched_get_priority_min(SCHED_FIFO)) 484 return -1; 485 if (prio > sched_get_priority_max(SCHED_FIFO)) 486 return -1; 487 488 sched_param->sched_policy = SCHED_FIFO; 489 sched_param->sched_priority = prio; 490 break; 491 case 'r': 492 case 'R': 493 /* r:prio */ 494 prio = get_long_after_colon(arg); 495 if (prio == INVALID_VAL) 496 return -1; 497 498 if (prio < sched_get_priority_min(SCHED_RR)) 499 return -1; 500 if (prio > sched_get_priority_max(SCHED_RR)) 501 return -1; 502 503 sched_param->sched_policy = SCHED_RR; 504 sched_param->sched_priority = prio; 505 break; 506 case 'o': 507 case 'O': 508 /* o:prio */ 509 prio = get_long_after_colon(arg); 510 if (prio == INVALID_VAL) 511 return -1; 512 513 if (prio < MIN_NICE) 514 return -1; 515 if (prio > MAX_NICE) 516 return -1; 517 518 sched_param->sched_policy = SCHED_OTHER; 519 sched_param->sched_nice = prio; 520 break; 521 default: 522 return -1; 523 } 524 return 0; 525 } 526 527 /* 528 * set_cpu_dma_latency - set the /dev/cpu_dma_latecy 529 * 530 * This is used to reduce the exit from idle latency. The value 531 * will be reset once the file descriptor of /dev/cpu_dma_latecy 532 * is closed. 533 * 534 * Return: the /dev/cpu_dma_latecy file descriptor 535 */ 536 int set_cpu_dma_latency(int32_t latency) 537 { 538 int retval; 539 int fd; 540 541 fd = open("/dev/cpu_dma_latency", O_RDWR); 542 if (fd < 0) { 543 err_msg("Error opening /dev/cpu_dma_latency\n"); 544 return -1; 545 } 546 547 retval = write(fd, &latency, 4); 548 if (retval < 1) { 549 err_msg("Error setting /dev/cpu_dma_latency\n"); 550 close(fd); 551 return -1; 552 } 553 554 debug_msg("Set /dev/cpu_dma_latency to %d\n", latency); 555 556 return fd; 557 } 558 559 #ifdef HAVE_LIBCPUPOWER_SUPPORT 560 static unsigned int **saved_cpu_idle_disable_state; 561 static size_t saved_cpu_idle_disable_state_alloc_ctr; 562 563 /* 564 * save_cpu_idle_state_disable - save disable for all idle states of a cpu 565 * 566 * Saves the current disable of all idle states of a cpu, to be subsequently 567 * restored via restore_cpu_idle_disable_state. 568 * 569 * Return: idle state count on success, negative on error 570 */ 571 int save_cpu_idle_disable_state(unsigned int cpu) 572 { 573 unsigned int nr_states; 574 unsigned int state; 575 int disabled; 576 577 nr_states = cpuidle_state_count(cpu); 578 579 if (nr_states == 0) 580 return 0; 581 582 if (saved_cpu_idle_disable_state == NULL) { 583 saved_cpu_idle_disable_state = calloc(nr_cpus, sizeof(unsigned int *)); 584 if (!saved_cpu_idle_disable_state) 585 return -1; 586 } 587 588 saved_cpu_idle_disable_state[cpu] = calloc(nr_states, sizeof(unsigned int)); 589 if (!saved_cpu_idle_disable_state[cpu]) 590 return -1; 591 saved_cpu_idle_disable_state_alloc_ctr++; 592 593 for (state = 0; state < nr_states; state++) { 594 disabled = cpuidle_is_state_disabled(cpu, state); 595 if (disabled < 0) 596 return disabled; 597 saved_cpu_idle_disable_state[cpu][state] = disabled; 598 } 599 600 return nr_states; 601 } 602 603 /* 604 * restore_cpu_idle_disable_state - restore disable for all idle states of a cpu 605 * 606 * Restores the current disable state of all idle states of a cpu that was 607 * previously saved by save_cpu_idle_disable_state. 608 * 609 * Return: idle state count on success, negative on error 610 */ 611 int restore_cpu_idle_disable_state(unsigned int cpu) 612 { 613 unsigned int nr_states; 614 unsigned int state; 615 int disabled; 616 int result; 617 618 nr_states = cpuidle_state_count(cpu); 619 620 if (nr_states == 0) 621 return 0; 622 623 if (!saved_cpu_idle_disable_state) 624 return -1; 625 626 for (state = 0; state < nr_states; state++) { 627 if (!saved_cpu_idle_disable_state[cpu]) 628 return -1; 629 disabled = saved_cpu_idle_disable_state[cpu][state]; 630 result = cpuidle_state_disable(cpu, state, disabled); 631 if (result < 0) 632 return result; 633 } 634 635 free(saved_cpu_idle_disable_state[cpu]); 636 saved_cpu_idle_disable_state[cpu] = NULL; 637 saved_cpu_idle_disable_state_alloc_ctr--; 638 if (saved_cpu_idle_disable_state_alloc_ctr == 0) { 639 free(saved_cpu_idle_disable_state); 640 saved_cpu_idle_disable_state = NULL; 641 } 642 643 return nr_states; 644 } 645 646 /* 647 * free_cpu_idle_disable_states - free saved idle state disable for all cpus 648 * 649 * Frees the memory used for storing cpu idle state disable for all cpus 650 * and states. 651 * 652 * Normally, the memory is freed automatically in 653 * restore_cpu_idle_disable_state; this is mostly for cleaning up after an 654 * error. 655 */ 656 void free_cpu_idle_disable_states(void) 657 { 658 int cpu; 659 660 if (!saved_cpu_idle_disable_state) 661 return; 662 663 for (cpu = 0; cpu < nr_cpus; cpu++) { 664 free(saved_cpu_idle_disable_state[cpu]); 665 saved_cpu_idle_disable_state[cpu] = NULL; 666 } 667 668 free(saved_cpu_idle_disable_state); 669 saved_cpu_idle_disable_state = NULL; 670 } 671 672 /* 673 * set_deepest_cpu_idle_state - limit idle state of cpu 674 * 675 * Disables all idle states deeper than the one given in 676 * deepest_state (assuming states with higher number are deeper). 677 * 678 * This is used to reduce the exit from idle latency. Unlike 679 * set_cpu_dma_latency, it can disable idle states per cpu. 680 * 681 * Return: idle state count on success, negative on error 682 */ 683 int set_deepest_cpu_idle_state(unsigned int cpu, unsigned int deepest_state) 684 { 685 unsigned int nr_states; 686 unsigned int state; 687 int result; 688 689 nr_states = cpuidle_state_count(cpu); 690 691 for (state = deepest_state + 1; state < nr_states; state++) { 692 result = cpuidle_state_disable(cpu, state, 1); 693 if (result < 0) 694 return result; 695 } 696 697 return nr_states; 698 } 699 #endif /* HAVE_LIBCPUPOWER_SUPPORT */ 700 701 #define _STR(x) #x 702 #define STR(x) _STR(x) 703 704 /* 705 * find_mount - find a the mount point of a given fs 706 * 707 * Returns 0 if mount is not found, otherwise return 1 and fill mp 708 * with the mount point. 709 */ 710 static const int find_mount(const char *fs, char *mp, int sizeof_mp) 711 { 712 char mount_point[MAX_PATH+1]; 713 char type[100]; 714 int found = 0; 715 FILE *fp; 716 717 fp = fopen("/proc/mounts", "r"); 718 if (!fp) 719 return 0; 720 721 while (fscanf(fp, "%*s %" STR(MAX_PATH) "s %99s %*s %*d %*d\n", mount_point, type) == 2) { 722 if (strcmp(type, fs) == 0) { 723 found = 1; 724 break; 725 } 726 } 727 fclose(fp); 728 729 if (!found) 730 return 0; 731 732 memset(mp, 0, sizeof_mp); 733 strncpy(mp, mount_point, sizeof_mp - 1); 734 735 debug_msg("Fs %s found at %s\n", fs, mp); 736 return 1; 737 } 738 739 /* 740 * get_self_cgroup - get the current thread cgroup path 741 * 742 * Parse /proc/$$/cgroup file to get the thread's cgroup. As an example of line to parse: 743 * 744 * 0::/user.slice/user-0.slice/session-3.scope'\n' 745 * 746 * This function is interested in the content after the second : and before the '\n'. 747 * 748 * Returns 1 if a string was found, 0 otherwise. 749 */ 750 static int get_self_cgroup(char *self_cg, int sizeof_self_cg) 751 { 752 char path[MAX_PATH], *start; 753 int fd, retval; 754 755 snprintf(path, MAX_PATH, "/proc/%d/cgroup", getpid()); 756 757 fd = open(path, O_RDONLY); 758 if (fd < 0) 759 return 0; 760 761 memset(path, 0, sizeof(path)); 762 retval = read(fd, path, MAX_PATH); 763 764 close(fd); 765 766 if (retval <= 0) 767 return 0; 768 769 path[MAX_PATH-1] = '\0'; 770 start = path; 771 772 start = strstr(start, ":"); 773 if (!start) 774 return 0; 775 776 /* skip ":" */ 777 start++; 778 779 start = strstr(start, ":"); 780 if (!start) 781 return 0; 782 783 /* skip ":" */ 784 start++; 785 786 if (strlen(start) >= sizeof_self_cg) 787 return 0; 788 789 snprintf(self_cg, sizeof_self_cg, "%s", start); 790 791 /* Swap '\n' with '\0' */ 792 start = strstr(self_cg, "\n"); 793 794 /* there must be '\n' */ 795 if (!start) 796 return 0; 797 798 /* ok, it found a string after the second : and before the \n */ 799 *start = '\0'; 800 801 return 1; 802 } 803 804 /* 805 * open_cgroup_procs - Open the cgroup.procs file for the given cgroup 806 * 807 * If cgroup argument is not NULL, the cgroup.procs file for that cgroup 808 * will be opened. Otherwise, the cgroup of the calling, i.e., rtla, thread 809 * will be used. 810 * 811 * Supports cgroup v2. 812 * 813 * Returns the file descriptor on success, -1 otherwise. 814 */ 815 static int open_cgroup_procs(const char *cgroup) 816 { 817 char cgroup_path[MAX_PATH - strlen("/cgroup.procs")]; 818 char cgroup_procs[MAX_PATH]; 819 int retval; 820 int cg_fd; 821 size_t cg_path_len; 822 823 retval = find_mount("cgroup2", cgroup_path, sizeof(cgroup_path)); 824 if (!retval) { 825 err_msg("Did not find cgroupv2 mount point\n"); 826 return -1; 827 } 828 829 cg_path_len = strlen(cgroup_path); 830 831 if (!cgroup) { 832 retval = get_self_cgroup(&cgroup_path[cg_path_len], 833 sizeof(cgroup_path) - cg_path_len); 834 if (!retval) { 835 err_msg("Did not find self cgroup\n"); 836 return -1; 837 } 838 } else { 839 snprintf(&cgroup_path[cg_path_len], 840 sizeof(cgroup_path) - cg_path_len, "%s/", cgroup); 841 } 842 843 snprintf(cgroup_procs, MAX_PATH, "%s/cgroup.procs", cgroup_path); 844 845 debug_msg("Using cgroup path at: %s\n", cgroup_procs); 846 847 cg_fd = open(cgroup_procs, O_RDWR); 848 if (cg_fd < 0) 849 return -1; 850 851 return cg_fd; 852 } 853 854 /* 855 * set_pid_cgroup - Set cgroup to pid_t pid 856 * 857 * If cgroup argument is not NULL, the threads will move to the given cgroup. 858 * Otherwise, the cgroup of the calling, i.e., rtla, thread will be used. 859 * 860 * Supports cgroup v2. 861 * 862 * Returns 1 on success, 0 otherwise. 863 */ 864 int set_pid_cgroup(pid_t pid, const char *cgroup) 865 { 866 char pid_str[24]; 867 int retval; 868 int cg_fd; 869 870 cg_fd = open_cgroup_procs(cgroup); 871 if (cg_fd < 0) 872 return 0; 873 874 snprintf(pid_str, sizeof(pid_str), "%d\n", pid); 875 876 retval = write(cg_fd, pid_str, strlen(pid_str)); 877 if (retval < 0) 878 err_msg("Error setting cgroup attributes for pid:%s - %s\n", 879 pid_str, strerror(errno)); 880 else 881 debug_msg("Set cgroup attributes for pid:%s\n", pid_str); 882 883 close(cg_fd); 884 885 return (retval >= 0); 886 } 887 888 /** 889 * set_comm_cgroup - Set cgroup to threads starting with char *comm_prefix 890 * 891 * If cgroup argument is not NULL, the threads will move to the given cgroup. 892 * Otherwise, the cgroup of the calling, i.e., rtla, thread will be used. 893 * 894 * Supports cgroup v2. 895 * 896 * Returns 1 on success, 0 otherwise. 897 */ 898 int set_comm_cgroup(const char *comm_prefix, const char *cgroup) 899 { 900 struct dirent *proc_entry; 901 DIR *procfs; 902 int retval; 903 int cg_fd; 904 905 if (strlen(comm_prefix) >= MAX_PATH) { 906 err_msg("Command prefix is too long: %d < strlen(%s)\n", 907 MAX_PATH, comm_prefix); 908 return 0; 909 } 910 911 cg_fd = open_cgroup_procs(cgroup); 912 if (cg_fd < 0) 913 return 0; 914 915 procfs = opendir("/proc"); 916 if (!procfs) { 917 err_msg("Could not open procfs\n"); 918 goto out_cg; 919 } 920 921 while ((proc_entry = readdir(procfs))) { 922 923 retval = procfs_is_workload_pid(comm_prefix, proc_entry); 924 if (!retval) 925 continue; 926 927 retval = write(cg_fd, proc_entry->d_name, strlen(proc_entry->d_name)); 928 if (retval < 0) { 929 err_msg("Error setting cgroup attributes for pid:%s - %s\n", 930 proc_entry->d_name, strerror(errno)); 931 goto out_procfs; 932 } 933 934 debug_msg("Set cgroup attributes for pid:%s\n", proc_entry->d_name); 935 } 936 937 closedir(procfs); 938 close(cg_fd); 939 return 1; 940 941 out_procfs: 942 closedir(procfs); 943 out_cg: 944 close(cg_fd); 945 return 0; 946 } 947 948 /** 949 * auto_house_keeping - Automatically move rtla out of measurement threads 950 * 951 * Try to move rtla away from the tracer, if possible. 952 * 953 * Returns 1 on success, 0 otherwise. 954 */ 955 int auto_house_keeping(cpu_set_t *monitored_cpus) 956 { 957 cpu_set_t rtla_cpus, house_keeping_cpus; 958 int retval; 959 960 /* first get the CPUs in which rtla can actually run. */ 961 retval = sched_getaffinity(getpid(), sizeof(rtla_cpus), &rtla_cpus); 962 if (retval == -1) { 963 debug_msg("Could not get rtla affinity, rtla might run with the threads!\n"); 964 return 0; 965 } 966 967 /* then check if the existing setup is already good. */ 968 CPU_AND(&house_keeping_cpus, &rtla_cpus, monitored_cpus); 969 if (!CPU_COUNT(&house_keeping_cpus)) { 970 debug_msg("rtla and the monitored CPUs do not share CPUs."); 971 debug_msg("Skipping auto house-keeping\n"); 972 return 1; 973 } 974 975 /* remove the intersection */ 976 CPU_XOR(&house_keeping_cpus, &rtla_cpus, monitored_cpus); 977 978 /* get only those that rtla can run */ 979 CPU_AND(&house_keeping_cpus, &house_keeping_cpus, &rtla_cpus); 980 981 /* is there any cpu left? */ 982 if (!CPU_COUNT(&house_keeping_cpus)) { 983 debug_msg("Could not find any CPU for auto house-keeping\n"); 984 return 0; 985 } 986 987 retval = sched_setaffinity(getpid(), sizeof(house_keeping_cpus), &house_keeping_cpus); 988 if (retval == -1) { 989 debug_msg("Could not set affinity for auto house-keeping\n"); 990 return 0; 991 } 992 993 debug_msg("rtla automatically moved to an auto house-keeping cpu set\n"); 994 995 return 1; 996 } 997 998 /** 999 * parse_optional_arg - Parse optional argument value 1000 * 1001 * Parse optional argument value, which can be in the form of: 1002 * -sarg, -s/--long=arg, -s/--long arg 1003 * 1004 * Returns arg value if found, NULL otherwise. 1005 */ 1006 char *parse_optional_arg(int argc, char **argv) 1007 { 1008 if (optarg) { 1009 if (optarg[0] == '=') { 1010 /* skip the = */ 1011 return &optarg[1]; 1012 } else { 1013 return optarg; 1014 } 1015 /* parse argument of form -s [arg] and --long [arg]*/ 1016 } else if (optind < argc && argv[optind][0] != '-') { 1017 /* consume optind */ 1018 return argv[optind++]; 1019 } else { 1020 return NULL; 1021 } 1022 } 1023 1024 /* 1025 * strtoi - convert string to integer with error checking 1026 * 1027 * Returns 0 on success, -1 if conversion fails or result is out of int range. 1028 */ 1029 int strtoi(const char *s, int *res) 1030 { 1031 char *end_ptr; 1032 long lres; 1033 1034 if (!*s) 1035 return -1; 1036 1037 errno = 0; 1038 lres = strtol(s, &end_ptr, 0); 1039 if (errno || *end_ptr || lres > INT_MAX || lres < INT_MIN) 1040 return -1; 1041 1042 *res = (int) lres; 1043 return 0; 1044 } 1045 1046 static inline void fatal_alloc(void) 1047 { 1048 fatal("Error allocating memory\n"); 1049 } 1050 1051 void *calloc_fatal(size_t n, size_t size) 1052 { 1053 void *p = calloc(n, size); 1054 1055 if (!p) 1056 fatal_alloc(); 1057 1058 return p; 1059 } 1060 1061 void *reallocarray_fatal(void *p, size_t n, size_t size) 1062 { 1063 p = reallocarray(p, n, size); 1064 1065 if (!p) 1066 fatal_alloc(); 1067 1068 return p; 1069 } 1070 1071 char *strdup_fatal(const char *s) 1072 { 1073 char *p = strdup(s); 1074 1075 if (!p) 1076 fatal_alloc(); 1077 1078 return p; 1079 } 1080