Debian Codegraph @

src/action-impls/gsm-setaffinity.c

raw symbols SCIP
1 /*
2 * SPDX-License-Identifier: GPL-2.0-or-later
3 */
4
5 #include "config.h"
6
7 #define _GNU_SOURCE
8
9 #include <glib/gi18n-lib.h>
10
11 #include <errno.h>
12 #include <sched.h>
13 #include <sys/types.h>
14
15 #include "gsm-setaffinity.h"
16
17
18 #ifdef __linux__
19 static inline gboolean
20 is_task (const char *tasks_dir, const char *name)
21 {
22 g_autofree char *path = g_build_filename (tasks_dir, name, NULL);
23
24 return g_file_test (path, G_FILE_TEST_IS_DIR);
25 }
26
27
28 static inline void
29 threads_setaffinity (pid_t pid,
30 size_t sizeof_set,
31 cpu_set_t *set,
32 GError **error)
33 {
34 g_autoptr (GError) local_error = NULL;
35 g_autofree char *tasks = g_strdup_printf ("/proc/%d/task", pid);
36 g_autoptr (GDir) dir = g_dir_open (tasks, 0, &local_error);
37
38 if (local_error) {
39 g_propagate_prefixed_error (error,
40 local_error,
41 "Failed to find threads: %s",
42 local_error->message);
43 return;
44 }
45
46 while (TRUE) {
47 const char *name = g_dir_read_name (dir);
48 int64_t task_no;
49
50 if (!name) {
51 break;
52 }
53
54 if (!is_task (tasks, name)) {
55 continue;
56 }
57
58 g_ascii_string_to_signed (name,
59 10,
60 0,
61 G_MAXINT,
62 &task_no,
63 &local_error);
64 if (local_error) {
65 g_autofree char *display = g_filename_display_name (name);
66 g_warning ("‘%s’ doesn't look like an ID: %s",
67 display,
68 local_error->message);
69 continue;
70 }
71
72 /* We let this fail silently */
73 sched_setaffinity ((pid_t) task_no, sizeof_set, set);
74 }
75 }
76 #endif
77
78
79 void
80 gsm_setaffinity (pid_t pid,
81 size_t n_cpus,
82 uint16_t cpus[],
83 gboolean apply_to_threads,
84 GError **error)
85 {
86 #ifdef __linux__
87 cpu_set_t set;
88 size_t sizeof_set;
89
90 CPU_ZERO (&set);
91
92 for (size_t i = 0; i < n_cpus; i++) {
93 CPU_SET (cpus[i], &set);
94 }
95
96 sizeof_set = sizeof (set);
97 if (sched_setaffinity (pid, sizeof_set, &set) < 0) {
98 int err = errno;
99
100 g_set_error (error,
101 G_FILE_ERROR,
102 g_file_error_from_errno (err),
103 _("Affinity failed on %i: %s"),
104 pid,
105 g_strerror (err));
106
107 return;
108 }
109
110 /* set child threads if required */
111 if (apply_to_threads) {
112 threads_setaffinity (pid, sizeof_set, &set, error);
113 }
114 #else
115 g_set_error (error,
116 G_FILE_ERROR,
117 G_FILE_ERROR_FAILED,
118 _("Affinity unsupported"));
119 #endif
120 }