1 // SPDX-License-Identifier: GPL-2.0
7 #ifdef HAVE_LIBCPUPOWER_SUPPORT
9 #endif /* HAVE_LIBCPUPOWER_SUPPORT */
23 #define MAX_MSG_LENGTH 1024
27 * err_msg - print an error message to the stderr
29 void err_msg(const char *fmt, ...)
31 char message[MAX_MSG_LENGTH];
35 vsnprintf(message, sizeof(message), fmt, ap);
38 fprintf(stderr, "%s", message);
42 * debug_msg - print a debug message to stderr if debug is set
44 void debug_msg(const char *fmt, ...)
46 char message[MAX_MSG_LENGTH];
53 vsnprintf(message, sizeof(message), fmt, ap);
56 fprintf(stderr, "%s", message);
60 * get_llong_from_str - get a long long int from a string
62 long long get_llong_from_str(char *start)
68 value = strtoll(start, &end, 10);
69 if (errno || start == end)
76 * get_duration - fill output with a human readable duration since start_time
78 void get_duration(time_t start_time, char *output, int output_size)
80 time_t now = time(NULL);
84 duration = difftime(now, start_time);
85 tm_info = gmtime(&duration);
87 snprintf(output, output_size, "%3d %02d:%02d:%02d",
95 * parse_cpu_set - parse a cpu_list filling cpu_set_t argument
97 * Receives a cpu list, like 1-3,5 (cpus 1, 2, 3, 5), and then set
98 * filling cpu_set_t argument.
100 * Returns 1 on success, 0 otherwise.
102 int parse_cpu_set(char *cpu_list, cpu_set_t *set)
112 nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
114 for (p = cpu_list; *p; ) {
116 if (cpu < 0 || (!cpu && *p != '0') || cpu >= nr_cpus)
124 if (end_cpu < cpu || (!end_cpu && *p != '0') || end_cpu >= nr_cpus)
131 if (cpu == end_cpu) {
132 debug_msg("cpu_set: adding cpu %d\n", cpu);
135 for (i = cpu; i <= end_cpu; i++) {
136 debug_msg("cpu_set: adding cpu %d\n", i);
147 debug_msg("Error parsing the cpu set %s\n", cpu_list);
152 * parse_duration - parse duration with s/m/h/d suffix converting it to seconds
154 long parse_seconds_duration(char *val)
159 t = strtol(val, &end, 10);
186 * parse_ns_duration - parse duration with ns/us/ms/s converting it to nanoseconds
188 long parse_ns_duration(char *val)
193 t = strtol(val, &end, 10);
196 if (!strncmp(end, "ns", 2)) {
198 } else if (!strncmp(end, "us", 2)) {
201 } else if (!strncmp(end, "ms", 2)) {
204 } else if (!strncmp(end, "s", 1)) {
205 t *= 1000 * 1000 * 1000;
215 * This is a set of helper functions to use SCHED_DEADLINE.
217 #ifndef __NR_sched_setattr
219 # define __NR_sched_setattr 314
221 # define __NR_sched_setattr 351
223 # define __NR_sched_setattr 380
224 # elif __aarch64__ || __riscv
225 # define __NR_sched_setattr 274
227 # define __NR_sched_setattr 355
229 # define __NR_sched_setattr 345
233 #define SCHED_DEADLINE 6
235 static inline int syscall_sched_setattr(pid_t pid, const struct sched_attr *attr,
236 unsigned int flags) {
237 return syscall(__NR_sched_setattr, pid, attr, flags);
240 int __set_sched_attr(int pid, struct sched_attr *attr)
245 retval = syscall_sched_setattr(pid, attr, flags);
247 err_msg("Failed to set sched attributes to the pid %d: %s\n",
248 pid, strerror(errno));
256 * procfs_is_workload_pid - check if a procfs entry contains a comm_prefix* comm
258 * Check if the procfs entry is a directory of a process, and then check if the
259 * process has a comm with the prefix set in char *comm_prefix. As the
260 * current users of this function only check for kernel threads, there is no
261 * need to check for the threads for the process.
263 * Return: True if the proc_entry contains a comm file with comm_prefix*.
264 * Otherwise returns false.
266 static int procfs_is_workload_pid(const char *comm_prefix, struct dirent *proc_entry)
268 char buffer[MAX_PATH];
272 if (proc_entry->d_type != DT_DIR)
275 if (*proc_entry->d_name == '.')
278 /* check if the string is a pid */
279 for (t_name = proc_entry->d_name; t_name; t_name++) {
280 if (!isdigit(*t_name))
287 snprintf(buffer, MAX_PATH, "/proc/%s/comm", proc_entry->d_name);
288 comm_fd = open(buffer, O_RDONLY);
292 memset(buffer, 0, MAX_PATH);
293 retval = read(comm_fd, buffer, MAX_PATH);
300 retval = strncmp(comm_prefix, buffer, strlen(comm_prefix));
304 /* comm already have \n */
305 debug_msg("Found workload pid:%s comm:%s", proc_entry->d_name, buffer);
311 * set_comm_sched_attr - set sched params to threads starting with char *comm_prefix
313 * This function uses procfs to list the currently running threads and then set the
314 * sched_attr *attr to the threads that start with char *comm_prefix. It is
315 * mainly used to set the priority to the kernel threads created by the
318 int set_comm_sched_attr(const char *comm_prefix, struct sched_attr *attr)
320 struct dirent *proc_entry;
324 if (strlen(comm_prefix) >= MAX_PATH) {
325 err_msg("Command prefix is too long: %d < strlen(%s)\n",
326 MAX_PATH, comm_prefix);
330 procfs = opendir("/proc");
332 err_msg("Could not open procfs\n");
336 while ((proc_entry = readdir(procfs))) {
338 retval = procfs_is_workload_pid(comm_prefix, proc_entry);
342 /* procfs_is_workload_pid confirmed it is a pid */
343 retval = __set_sched_attr(atoi(proc_entry->d_name), attr);
345 err_msg("Error setting sched attributes for pid:%s\n", proc_entry->d_name);
349 debug_msg("Set sched attributes for pid:%s\n", proc_entry->d_name);
358 #define INVALID_VAL (~0L)
359 static long get_long_ns_after_colon(char *start)
361 long val = INVALID_VAL;
364 start = strstr(start, ":");
370 val = parse_ns_duration(start);
375 static long get_long_after_colon(char *start)
377 long val = INVALID_VAL;
380 start = strstr(start, ":");
386 val = get_llong_from_str(start);
392 * parse priority in the format:
406 int parse_prio(char *arg, struct sched_attr *sched_param)
412 memset(sched_param, 0, sizeof(*sched_param));
413 sched_param->size = sizeof(*sched_param);
418 /* d:runtime:period */
422 runtime = get_long_ns_after_colon(arg);
423 if (runtime == INVALID_VAL)
426 period = get_long_ns_after_colon(&arg[2]);
427 if (period == INVALID_VAL)
430 if (runtime > period)
433 sched_param->sched_policy = SCHED_DEADLINE;
434 sched_param->sched_runtime = runtime;
435 sched_param->sched_deadline = period;
436 sched_param->sched_period = period;
441 prio = get_long_after_colon(arg);
442 if (prio == INVALID_VAL)
445 if (prio < sched_get_priority_min(SCHED_FIFO))
447 if (prio > sched_get_priority_max(SCHED_FIFO))
450 sched_param->sched_policy = SCHED_FIFO;
451 sched_param->sched_priority = prio;
456 prio = get_long_after_colon(arg);
457 if (prio == INVALID_VAL)
460 if (prio < sched_get_priority_min(SCHED_RR))
462 if (prio > sched_get_priority_max(SCHED_RR))
465 sched_param->sched_policy = SCHED_RR;
466 sched_param->sched_priority = prio;
471 prio = get_long_after_colon(arg);
472 if (prio == INVALID_VAL)
480 sched_param->sched_policy = SCHED_OTHER;
481 sched_param->sched_nice = prio;
490 * set_cpu_dma_latency - set the /dev/cpu_dma_latecy
492 * This is used to reduce the exit from idle latency. The value
493 * will be reset once the file descriptor of /dev/cpu_dma_latecy
496 * Return: the /dev/cpu_dma_latecy file descriptor
498 int set_cpu_dma_latency(int32_t latency)
503 fd = open("/dev/cpu_dma_latency", O_RDWR);
505 err_msg("Error opening /dev/cpu_dma_latency\n");
509 retval = write(fd, &latency, 4);
511 err_msg("Error setting /dev/cpu_dma_latency\n");
516 debug_msg("Set /dev/cpu_dma_latency to %d\n", latency);
521 #ifdef HAVE_LIBCPUPOWER_SUPPORT
522 static unsigned int **saved_cpu_idle_disable_state;
523 static size_t saved_cpu_idle_disable_state_alloc_ctr;
526 * save_cpu_idle_state_disable - save disable for all idle states of a cpu
528 * Saves the current disable of all idle states of a cpu, to be subsequently
529 * restored via restore_cpu_idle_disable_state.
531 * Return: idle state count on success, negative on error
533 int save_cpu_idle_disable_state(unsigned int cpu)
535 unsigned int nr_states;
540 nr_states = cpuidle_state_count(cpu);
545 if (saved_cpu_idle_disable_state == NULL) {
546 nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
547 saved_cpu_idle_disable_state = calloc(nr_cpus, sizeof(unsigned int *));
548 if (!saved_cpu_idle_disable_state)
552 saved_cpu_idle_disable_state[cpu] = calloc(nr_states, sizeof(unsigned int));
553 if (!saved_cpu_idle_disable_state[cpu])
555 saved_cpu_idle_disable_state_alloc_ctr++;
557 for (state = 0; state < nr_states; state++) {
558 disabled = cpuidle_is_state_disabled(cpu, state);
561 saved_cpu_idle_disable_state[cpu][state] = disabled;
568 * restore_cpu_idle_disable_state - restore disable for all idle states of a cpu
570 * Restores the current disable state of all idle states of a cpu that was
571 * previously saved by save_cpu_idle_disable_state.
573 * Return: idle state count on success, negative on error
575 int restore_cpu_idle_disable_state(unsigned int cpu)
577 unsigned int nr_states;
582 nr_states = cpuidle_state_count(cpu);
587 if (!saved_cpu_idle_disable_state)
590 for (state = 0; state < nr_states; state++) {
591 if (!saved_cpu_idle_disable_state[cpu])
593 disabled = saved_cpu_idle_disable_state[cpu][state];
594 result = cpuidle_state_disable(cpu, state, disabled);
599 free(saved_cpu_idle_disable_state[cpu]);
600 saved_cpu_idle_disable_state[cpu] = NULL;
601 saved_cpu_idle_disable_state_alloc_ctr--;
602 if (saved_cpu_idle_disable_state_alloc_ctr == 0) {
603 free(saved_cpu_idle_disable_state);
604 saved_cpu_idle_disable_state = NULL;
611 * free_cpu_idle_disable_states - free saved idle state disable for all cpus
613 * Frees the memory used for storing cpu idle state disable for all cpus
616 * Normally, the memory is freed automatically in
617 * restore_cpu_idle_disable_state; this is mostly for cleaning up after an
620 void free_cpu_idle_disable_states(void)
625 if (!saved_cpu_idle_disable_state)
628 nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
630 for (cpu = 0; cpu < nr_cpus; cpu++) {
631 free(saved_cpu_idle_disable_state[cpu]);
632 saved_cpu_idle_disable_state[cpu] = NULL;
635 free(saved_cpu_idle_disable_state);
636 saved_cpu_idle_disable_state = NULL;
640 * set_deepest_cpu_idle_state - limit idle state of cpu
642 * Disables all idle states deeper than the one given in
643 * deepest_state (assuming states with higher number are deeper).
645 * This is used to reduce the exit from idle latency. Unlike
646 * set_cpu_dma_latency, it can disable idle states per cpu.
648 * Return: idle state count on success, negative on error
650 int set_deepest_cpu_idle_state(unsigned int cpu, unsigned int deepest_state)
652 unsigned int nr_states;
656 nr_states = cpuidle_state_count(cpu);
658 for (state = deepest_state + 1; state < nr_states; state++) {
659 result = cpuidle_state_disable(cpu, state, 1);
666 #endif /* HAVE_LIBCPUPOWER_SUPPORT */
669 #define STR(x) _STR(x)
672 * find_mount - find a the mount point of a given fs
674 * Returns 0 if mount is not found, otherwise return 1 and fill mp
675 * with the mount point.
677 static const int find_mount(const char *fs, char *mp, int sizeof_mp)
679 char mount_point[MAX_PATH+1];
684 fp = fopen("/proc/mounts", "r");
688 while (fscanf(fp, "%*s %" STR(MAX_PATH) "s %99s %*s %*d %*d\n", mount_point, type) == 2) {
689 if (strcmp(type, fs) == 0) {
699 memset(mp, 0, sizeof_mp);
700 strncpy(mp, mount_point, sizeof_mp - 1);
702 debug_msg("Fs %s found at %s\n", fs, mp);
707 * get_self_cgroup - get the current thread cgroup path
709 * Parse /proc/$$/cgroup file to get the thread's cgroup. As an example of line to parse:
711 * 0::/user.slice/user-0.slice/session-3.scope'\n'
713 * This function is interested in the content after the second : and before the '\n'.
715 * Returns 1 if a string was found, 0 otherwise.
717 static int get_self_cgroup(char *self_cg, int sizeof_self_cg)
719 char path[MAX_PATH], *start;
722 snprintf(path, MAX_PATH, "/proc/%d/cgroup", getpid());
724 fd = open(path, O_RDONLY);
728 retval = read(fd, path, MAX_PATH);
737 start = strstr(start, ":");
744 start = strstr(start, ":");
751 if (strlen(start) >= sizeof_self_cg)
754 snprintf(self_cg, sizeof_self_cg, "%s", start);
756 /* Swap '\n' with '\0' */
757 start = strstr(self_cg, "\n");
759 /* there must be '\n' */
763 /* ok, it found a string after the second : and before the \n */
770 * set_comm_cgroup - Set cgroup to pid_t pid
772 * If cgroup argument is not NULL, the threads will move to the given cgroup.
773 * Otherwise, the cgroup of the calling, i.e., rtla, thread will be used.
775 * Supports cgroup v2.
777 * Returns 1 on success, 0 otherwise.
779 int set_pid_cgroup(pid_t pid, const char *cgroup)
781 char cgroup_path[MAX_PATH - strlen("/cgroup.procs")];
782 char cgroup_procs[MAX_PATH];
787 retval = find_mount("cgroup2", cgroup_path, sizeof(cgroup_path));
789 err_msg("Did not find cgroupv2 mount point\n");
794 retval = get_self_cgroup(&cgroup_path[strlen(cgroup_path)],
795 sizeof(cgroup_path) - strlen(cgroup_path));
797 err_msg("Did not find self cgroup\n");
801 snprintf(&cgroup_path[strlen(cgroup_path)],
802 sizeof(cgroup_path) - strlen(cgroup_path), "%s/", cgroup);
805 snprintf(cgroup_procs, MAX_PATH, "%s/cgroup.procs", cgroup_path);
807 debug_msg("Using cgroup path at: %s\n", cgroup_procs);
809 cg_fd = open(cgroup_procs, O_RDWR);
813 snprintf(pid_str, sizeof(pid_str), "%d\n", pid);
815 retval = write(cg_fd, pid_str, strlen(pid_str));
817 err_msg("Error setting cgroup attributes for pid:%s - %s\n",
818 pid_str, strerror(errno));
820 debug_msg("Set cgroup attributes for pid:%s\n", pid_str);
824 return (retval >= 0);
828 * set_comm_cgroup - Set cgroup to threads starting with char *comm_prefix
830 * If cgroup argument is not NULL, the threads will move to the given cgroup.
831 * Otherwise, the cgroup of the calling, i.e., rtla, thread will be used.
833 * Supports cgroup v2.
835 * Returns 1 on success, 0 otherwise.
837 int set_comm_cgroup(const char *comm_prefix, const char *cgroup)
839 char cgroup_path[MAX_PATH - strlen("/cgroup.procs")];
840 char cgroup_procs[MAX_PATH];
841 struct dirent *proc_entry;
846 if (strlen(comm_prefix) >= MAX_PATH) {
847 err_msg("Command prefix is too long: %d < strlen(%s)\n",
848 MAX_PATH, comm_prefix);
852 retval = find_mount("cgroup2", cgroup_path, sizeof(cgroup_path));
854 err_msg("Did not find cgroupv2 mount point\n");
859 retval = get_self_cgroup(&cgroup_path[strlen(cgroup_path)],
860 sizeof(cgroup_path) - strlen(cgroup_path));
862 err_msg("Did not find self cgroup\n");
866 snprintf(&cgroup_path[strlen(cgroup_path)],
867 sizeof(cgroup_path) - strlen(cgroup_path), "%s/", cgroup);
870 snprintf(cgroup_procs, MAX_PATH, "%s/cgroup.procs", cgroup_path);
872 debug_msg("Using cgroup path at: %s\n", cgroup_procs);
874 cg_fd = open(cgroup_procs, O_RDWR);
878 procfs = opendir("/proc");
880 err_msg("Could not open procfs\n");
884 while ((proc_entry = readdir(procfs))) {
886 retval = procfs_is_workload_pid(comm_prefix, proc_entry);
890 retval = write(cg_fd, proc_entry->d_name, strlen(proc_entry->d_name));
892 err_msg("Error setting cgroup attributes for pid:%s - %s\n",
893 proc_entry->d_name, strerror(errno));
897 debug_msg("Set cgroup attributes for pid:%s\n", proc_entry->d_name);
912 * auto_house_keeping - Automatically move rtla out of measurement threads
914 * Try to move rtla away from the tracer, if possible.
916 * Returns 1 on success, 0 otherwise.
918 int auto_house_keeping(cpu_set_t *monitored_cpus)
920 cpu_set_t rtla_cpus, house_keeping_cpus;
923 /* first get the CPUs in which rtla can actually run. */
924 retval = sched_getaffinity(getpid(), sizeof(rtla_cpus), &rtla_cpus);
926 debug_msg("Could not get rtla affinity, rtla might run with the threads!\n");
930 /* then check if the existing setup is already good. */
931 CPU_AND(&house_keeping_cpus, &rtla_cpus, monitored_cpus);
932 if (!CPU_COUNT(&house_keeping_cpus)) {
933 debug_msg("rtla and the monitored CPUs do not share CPUs.");
934 debug_msg("Skipping auto house-keeping\n");
938 /* remove the intersection */
939 CPU_XOR(&house_keeping_cpus, &rtla_cpus, monitored_cpus);
941 /* get only those that rtla can run */
942 CPU_AND(&house_keeping_cpus, &house_keeping_cpus, &rtla_cpus);
944 /* is there any cpu left? */
945 if (!CPU_COUNT(&house_keeping_cpus)) {
946 debug_msg("Could not find any CPU for auto house-keeping\n");
950 retval = sched_setaffinity(getpid(), sizeof(house_keeping_cpus), &house_keeping_cpus);
952 debug_msg("Could not set affinity for auto house-keeping\n");
956 debug_msg("rtla automatically moved to an auto house-keeping cpu set\n");