chiark / gitweb /
Prep v238: Uncomment now needed headers and unmask now needed functions in src/basic...
[elogind.git] / src / basic / procfs-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4
5 #include "alloc-util.h"
6 #include "def.h"
7 #include "fd-util.h"
8 #include "fileio.h"
9 #include "parse-util.h"
10 #include "process-util.h"
11 #include "procfs-util.h"
12 #include "stdio-util.h"
13 #include "string-util.h"
14
15 int procfs_tasks_get_limit(uint64_t *ret) {
16         _cleanup_free_ char *value = NULL;
17         uint64_t pid_max, threads_max;
18         int r;
19
20         assert(ret);
21
22         /* So there are two sysctl files that control the system limit of processes:
23          *
24          * 1. kernel.threads-max: this is probably the sysctl that makes more sense, as it directly puts a limit on
25          *    concurrent tasks.
26          *
27          * 2. kernel.pid_max: this limits the numeric range PIDs can take, and thus indirectly also limits the number
28          *    of concurrent threads. AFAICS it's primarily a compatibility concept: some crappy old code used a signed
29          *    16bit type for PIDs, hence the kernel provides a way to ensure the PIDs never go beyond INT16_MAX by
30          *    default.
31          *
32          * By default #2 is set to much lower values than #1, hence the limit people come into contact with first, as
33          * it's the lowest boundary they need to bump when they want higher number of processes.
34          *
35          * Also note the weird definition of #2: PIDs assigned will be kept below this value, which means the number of
36          * tasks that can be created is one lower, as PID 0 is not a valid process ID. */
37
38         r = read_one_line_file("/proc/sys/kernel/pid_max", &value);
39         if (r < 0)
40                 return r;
41
42         r = safe_atou64(value, &pid_max);
43         if (r < 0)
44                 return r;
45
46         value = mfree(value);
47         r = read_one_line_file("/proc/sys/kernel/threads-max", &value);
48         if (r < 0)
49                 return r;
50
51         r = safe_atou64(value, &threads_max);
52         if (r < 0)
53                 return r;
54
55         /* Subtract one from pid_max, since PID 0 is not a valid PID */
56         *ret = MIN(pid_max-1, threads_max);
57         return 0;
58 }
59
60 #if 0 /// UNNEEDED by elogind
61 int procfs_tasks_set_limit(uint64_t limit) {
62         char buffer[DECIMAL_STR_MAX(uint64_t)+1];
63         _cleanup_free_ char *value = NULL;
64         uint64_t pid_max;
65         int r;
66
67         if (limit == 0) /* This makes no sense, we are userspace and hence count as tasks too, and we want to live,
68                          * hence the limit conceptually has to be above 0. Also, most likely if anyone asks for a zero
69                          * limit he/she probably means "no limit", hence let's better refuse this to avoid
70                          * confusion. */
71                 return -EINVAL;
72
73         /* The Linux kernel doesn't allow this value to go below 20, hence don't allow this either, higher values than
74          * TASKS_MAX are not accepted by the pid_max sysctl. We'll treat anything this high as "unbounded" and hence
75          * set it to the maximum. */
76         limit = CLAMP(limit, 20U, TASKS_MAX);
77
78         r = read_one_line_file("/proc/sys/kernel/pid_max", &value);
79         if (r < 0)
80                 return r;
81         r = safe_atou64(value, &pid_max);
82         if (r < 0)
83                 return r;
84
85         /* As pid_max is about the numeric pid_t range we'll bump it if necessary, but only ever increase it, never
86          * decrease it, as threads-max is the much more relevant sysctl. */
87         if (limit > pid_max-1) {
88                 sprintf(buffer, "%" PRIu64, limit+1); /* Add one, since PID 0 is not a valid PID */
89                 r = write_string_file("/proc/sys/kernel/pid_max", buffer, WRITE_STRING_FILE_DISABLE_BUFFER);
90                 if (r < 0)
91                         return r;
92         }
93
94         sprintf(buffer, "%" PRIu64, limit);
95         r = write_string_file("/proc/sys/kernel/threads-max", buffer, WRITE_STRING_FILE_DISABLE_BUFFER);
96         if (r < 0) {
97                 uint64_t threads_max;
98
99                 /* Hmm, we couldn't write this? If so, maybe it was already set properly? In that case let's not
100                  * generate an error */
101
102                 value = mfree(value);
103                 if (read_one_line_file("/proc/sys/kernel/threads-max", &value) < 0)
104                         return r; /* return original error */
105
106                 if (safe_atou64(value, &threads_max) < 0)
107                         return r; /* return original error */
108
109                 if (MIN(pid_max-1, threads_max) != limit)
110                         return r; /* return original error */
111
112                 /* Yay! Value set already matches what we were trying to set, hence consider this a success. */
113         }
114
115         return 0;
116 }
117
118 int procfs_tasks_get_current(uint64_t *ret) {
119         _cleanup_free_ char *value = NULL;
120         const char *p, *nr;
121         size_t n;
122         int r;
123
124         assert(ret);
125
126         r = read_one_line_file("/proc/loadavg", &value);
127         if (r < 0)
128                 return r;
129
130         /* Look for the second part of the fourth field, which is separated by a slash from the first part. None of the
131          * earlier fields use a slash, hence let's use this to find the right spot. */
132         p = strchr(value, '/');
133         if (!p)
134                 return -EINVAL;
135
136         p++;
137         n = strspn(p, DIGITS);
138         nr = strndupa(p, n);
139
140         return safe_atou64(nr, ret);
141 }
142
143 static uint64_t calc_gcd64(uint64_t a, uint64_t b) {
144
145         while (b > 0) {
146                 uint64_t t;
147
148                 t = a % b;
149
150                 a = b;
151                 b = t;
152         }
153
154         return a;
155 }
156
157 int procfs_cpu_get_usage(nsec_t *ret) {
158         _cleanup_free_ char *first_line = NULL;
159         unsigned long user_ticks, nice_ticks, system_ticks, irq_ticks, softirq_ticks,
160                 guest_ticks = 0, guest_nice_ticks = 0;
161         long ticks_per_second;
162         uint64_t sum, gcd, a, b;
163         const char *p;
164         int r;
165
166         assert(ret);
167
168         r = read_one_line_file("/proc/stat", &first_line);
169         if (r < 0)
170                 return r;
171
172         p = first_word(first_line, "cpu");
173         if (!p)
174                 return -EINVAL;
175
176         if (sscanf(p, "%lu %lu %lu %*u %*u %lu %lu %*u %lu %lu",
177                    &user_ticks,
178                    &nice_ticks,
179                    &system_ticks,
180                    &irq_ticks,
181                    &softirq_ticks,
182                    &guest_ticks,
183                    &guest_nice_ticks) < 5) /* we only insist on the first five fields */
184                 return -EINVAL;
185
186         ticks_per_second = sysconf(_SC_CLK_TCK);
187         if (ticks_per_second  < 0)
188                 return -errno;
189         assert(ticks_per_second > 0);
190
191         sum = (uint64_t) user_ticks + (uint64_t) nice_ticks + (uint64_t) system_ticks +
192                 (uint64_t) irq_ticks + (uint64_t) softirq_ticks +
193                 (uint64_t) guest_ticks + (uint64_t) guest_nice_ticks;
194
195         /* Let's reduce this fraction before we apply it to avoid overflows when converting this to µsec */
196         gcd = calc_gcd64(NSEC_PER_SEC, ticks_per_second);
197
198         a = (uint64_t) NSEC_PER_SEC / gcd;
199         b = (uint64_t) ticks_per_second / gcd;
200
201         *ret = DIV_ROUND_UP((nsec_t) sum * (nsec_t) a, (nsec_t) b);
202         return 0;
203 }
204
205 int procfs_memory_get_current(uint64_t *ret) {
206         uint64_t mem_total = UINT64_MAX, mem_free = UINT64_MAX;
207         _cleanup_fclose_ FILE *f = NULL;
208         int r;
209
210         assert(ret);
211
212         f = fopen("/proc/meminfo", "re");
213         if (!f)
214                 return -errno;
215
216         for (;;) {
217                 _cleanup_free_ char *line = NULL;
218                 uint64_t *v;
219                 char *p, *e;
220                 size_t n;
221
222                 r = read_line(f, LONG_LINE_MAX, &line);
223                 if (r < 0)
224                         return r;
225                 if (r == 0)
226                         return -EINVAL; /* EOF: Couldn't find one or both fields? */
227
228                 p = first_word(line, "MemTotal:");
229                 if (p)
230                         v = &mem_total;
231                 else {
232                         p = first_word(line, "MemFree:");
233                         if (p)
234                                 v = &mem_free;
235                         else
236                                 continue;
237                 }
238
239                 /* Determine length of numeric value */
240                 n = strspn(p, DIGITS);
241                 if (n == 0)
242                         return -EINVAL;
243                 e = p + n;
244
245                 /* Ensure the line ends in " kB" */
246                 n = strspn(e, WHITESPACE);
247                 if (n == 0)
248                         return -EINVAL;
249                 if (!streq(e + n, "kB"))
250                         return -EINVAL;
251
252                 *e = 0;
253                 r = safe_atou64(p, v);
254                 if (r < 0)
255                         return r;
256                 if (*v == UINT64_MAX)
257                         return -EINVAL;
258
259                 if (mem_total != UINT64_MAX && mem_free != UINT64_MAX)
260                         break;
261         }
262
263         if (mem_free > mem_total)
264                 return -EINVAL;
265
266         *ret = (mem_total - mem_free) * 1024U;
267         return 0;
268 }
269 #endif // 0