Debian Codegraph @

src/lib/rt-utils.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2009 Carsten Emde <[email protected]>
4 * Copyright (C) 2010 Clark Williams <[email protected]>
5 * Copyright (C) 2015 John Kacur <[email protected]>
6 *
7 * based on functions from cyclictest that has
8 * (C) 2008-2009 Clark Williams <[email protected]>
9 * (C) 2005-2007 Thomas Gleixner <[email protected]>
10 */
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sched.h>
15 #include <stdarg.h>
16 #include <errno.h>
17 #include <ctype.h>
18 #include <fcntl.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #include <sys/syscall.h> /* For SYS_gettid definitions */
23 #include <sys/utsname.h>
24 #include <time.h>
25 #include <sys/time.h>
26
27 #include "rt-utils.h"
28 #include "rt-sched.h"
29 #include "rt-error.h"
30
31 #define TRACEBUFSIZ 1024
32 #define MAX_COMMAND_LINE 4096
33 #define MAX_TS_SIZE 64
34
35 static char tracefs_prefix[MAX_PATH];
36 static int trace_fd = -1;
37 static int tracemark_fd = -1;
38 static __thread char tracebuf[TRACEBUFSIZ];
39 static char test_cmdline[MAX_COMMAND_LINE];
40 static char ts_start[MAX_TS_SIZE];
41
42 /*
43 * Finds the tracing directory
44 */
45 char *get_tracefs_prefix(void)
46 {
47 char type[100];
48 FILE *fp;
49 int found = 0;
50 struct stat s;
51
52 if (tracefs_prefix[0] != '\0')
53 goto out;
54
55 /* look in the "standard" mount point first */
56 if ((stat("/sys/kernel/tracing", &s) == 0) && S_ISDIR(s.st_mode)) {
57 strcpy(tracefs_prefix, "/sys/kernel/tracing/");
58 goto out;
59 }
60
61 /* oh well, parse /proc/mounts and see if it's there */
62 if ((fp = fopen("/proc/mounts", "r")) == NULL)
63 goto out;
64
65 while (fscanf(fp, "%*s %"
66 STR(MAX_PATH)
67 "s %99s %*s %*d %*d\n",
68 tracefs_prefix, type) == 2) {
69 if (strcmp(type, "tracefs") == 0) {
70 found = 1;
71 break;
72 }
73 }
74 fclose(fp);
75
76 if (!found) {
77 tracefs_prefix[0] = '\0';
78 goto out;
79 }
80 out:
81 return tracefs_prefix;
82 }
83
84 static char **tracer_list;
85 static char *tracer_buffer;
86 static int num_tracers;
87 #define CHUNKSZ 1024
88
89 /*
90 * return a list of the tracers configured into the running kernel
91 */
92
93 int get_tracers(char ***list)
94 {
95 int ret;
96 FILE *fp;
97 char buffer[CHUNKSZ];
98 char *prefix = get_tracefs_prefix();
99 char *tmpbuf = NULL;
100 char *ptr;
101 int tmpsz = 0;
102
103 /* if we've already parse it, return what we have */
104 if (tracer_list) {
105 *list = tracer_list;
106 return num_tracers;
107 }
108
109 /* open the tracing file available_tracers */
110 sprintf(buffer, "%savailable_tracers", prefix);
111 if ((fp = fopen(buffer, "r")) == NULL)
112 fatal("Can't open %s for reading\n", buffer);
113
114 /* allocate initial buffer */
115 ptr = tmpbuf = malloc(CHUNKSZ);
116 if (ptr == NULL)
117 fatal("error allocating initial space for tracer list\n");
118
119 /* read in the list of available tracers */
120 while ((ret = fread(buffer, sizeof(char), CHUNKSZ, fp))) {
121 if ((ptr+ret+1) > (tmpbuf+tmpsz)) {
122 tmpbuf = realloc(tmpbuf, tmpsz + CHUNKSZ);
123 if (tmpbuf == NULL)
124 fatal("error allocating space for list of valid tracers\n");
125 tmpsz += CHUNKSZ;
126 }
127 strncpy(ptr, buffer, ret);
128 ptr += ret;
129 }
130 fclose(fp);
131 if (tmpsz == 0)
132 fatal("error reading available tracers\n");
133
134 tracer_buffer = tmpbuf;
135
136 /* get a buffer for the pointers to tracers */
137 if (!(tracer_list = malloc(sizeof(char *))))
138 fatal("error allocatinging tracer list buffer\n");
139
140 /* parse the buffer */
141 ptr = strtok(tmpbuf, " \t\n\r");
142 do {
143 tracer_list[num_tracers++] = ptr;
144 tracer_list = realloc(tracer_list, sizeof(char*)*(num_tracers+1));
145 tracer_list[num_tracers] = NULL;
146 } while ((ptr = strtok(NULL, " \t\n\r")) != NULL);
147
148 /* return the list and number of tracers */
149 *list = tracer_list;
150 return num_tracers;
151 }
152
153
154 /*
155 * return zero if tracername is not a valid tracer, non-zero if it is
156 */
157
158 int valid_tracer(char *tracername)
159 {
160 char **list;
161 int ntracers;
162 int i;
163
164 ntracers = get_tracers(&list);
165 if (ntracers == 0 || tracername == NULL)
166 return 0;
167 for (i = 0; i < ntracers; i++)
168 if (strncmp(list[i], tracername, strlen(list[i])) == 0)
169 return 1;
170 return 0;
171 }
172
173 /*
174 * enable event tracepoint
175 */
176 int setevent(char *event, char *val)
177 {
178 char *prefix = get_tracefs_prefix();
179 char buffer[MAX_PATH];
180 int fd;
181 int ret;
182
183 sprintf(buffer, "%s%s", prefix, event);
184 if ((fd = open(buffer, O_WRONLY)) < 0) {
185 warn("unable to open %s\n", buffer);
186 return -1;
187 }
188 if ((ret = write(fd, val, strlen(val))) < 0) {
189 warn("unable to write %s to %s\n", val, buffer);
190 close(fd);
191 return -1;
192 }
193 close(fd);
194 return 0;
195 }
196
197 int event_enable_all(void)
198 {
199 return setevent("events/enable", "1");
200 }
201
202 int event_disable_all(void)
203 {
204 return setevent("events/enable", "0");
205 }
206
207 int event_enable(char *event)
208 {
209 char path[MAX_PATH];
210
211 sprintf(path, "events/%s/enable", event);
212 return setevent(path, "1");
213 }
214
215 int event_disable(char *event)
216 {
217 char path[MAX_PATH];
218
219 sprintf(path, "events/%s/enable", event);
220 return setevent(path, "0");
221 }
222
223 int check_privs(void)
224 {
225 int policy = sched_getscheduler(0);
226 struct sched_param param, old_param;
227
228 /* if we're already running a realtime scheduler
229 * then we *should* be able to change things later
230 */
231 if (policy == SCHED_FIFO || policy == SCHED_RR)
232 return 0;
233
234 /* first get the current parameters */
235 if (sched_getparam(0, &old_param)) {
236 fprintf(stderr, "unable to get scheduler parameters\n");
237 return 1;
238 }
239 param = old_param;
240
241 /* try to change to SCHED_FIFO */
242 param.sched_priority = 1;
243 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
244 fprintf(stderr, "Unable to change scheduling policy!\n");
•245 fprintf(stderr, "Probably missing capabilities, either run as "
246 "root or increase RLIMIT_RTPRIO limits.\n");
247 return 1;
248 }
249
250 /* we're good; change back and return success */
251 return sched_setscheduler(0, policy, &old_param);
252 }
253
254 const char *policy_to_string(int policy)
255 {
256 switch (policy) {
257 case SCHED_OTHER:
258 return "SCHED_OTHER";
259 case SCHED_FIFO:
260 return "SCHED_FIFO";
261 case SCHED_RR:
262 return "SCHED_RR";
263 case SCHED_BATCH:
264 return "SCHED_BATCH";
265 case SCHED_IDLE:
266 return "SCHED_IDLE";
267 case SCHED_DEADLINE:
268 return "SCHED_DEADLINE";
269 }
270
271 return "unknown";
272 }
273
274 uint32_t string_to_policy(const char *str)
275 {
276 if (!strcmp(str, "other"))
277 return SCHED_OTHER;
278 else if (!strcmp(str, "fifo"))
279 return SCHED_FIFO;
280 else if (!strcmp(str, "rr"))
281 return SCHED_RR;
282 else if (!strcmp(str, "batch"))
283 return SCHED_BATCH;
284 else if (!strcmp(str, "idle"))
285 return SCHED_IDLE;
286 else if (!strcmp(str, "deadline"))
287 return SCHED_DEADLINE;
288
289 return 0;
290 }
291
292 pid_t gettid(void)
293 {
294 return syscall(SYS_gettid);
295 }
296
297 /*
298 * parse an input value as a base10 value followed by an optional
299 * suffix. The input value is presumed to be in seconds, unless
300 * followed by a modifier suffix: m=minutes, h=hours, d=days
301 *
302 * the return value is a value in seconds
303 */
304 int parse_time_string(char *val)
305 {
306 char *end;
307 int t = strtol(val, &end, 10);
308 if (end) {
309 switch (*end) {
310 case 'm':
311 case 'M':
312 t *= 60;
313 break;
314
315 case 'h':
316 case 'H':
317 t *= 60*60;
318 break;
319
320 case 'd':
321 case 'D':
322 t *= 24*60*60;
323 break;
324
325 }
326 }
327 return t;
328 }
329
330 int parse_mem_string(char *str, uint64_t *val)
331 {
332 char *endptr;
333 int v = strtol(str, &endptr, 10);
334
335 if (!*endptr)
336 return v;
337
338 switch (*endptr) {
339 case 'g':
340 case 'G':
341 v *= 1024;
342 __attribute__ ((fallthrough));
343 case 'm':
344 case 'M':
345 v *= 1024;
346 __attribute__ ((fallthrough));
347 case 'k':
348 case 'K':
349 v *= 1024;
350 __attribute__ ((fallthrough));
351 case 'b':
352 case 'B':
353 break;
354 default:
355 return -1;
356 }
357
358 *val = v;
359
360 return 0;
361 }
362
363 static void open_tracemark_fd(void)
364 {
365 char path[MAX_PATH];
366 int n;
367
368 /*
369 * open the tracemark file if it's not already open
370 */
371 if (tracemark_fd < 0) {
372 n = snprintf(path, sizeof(path), "%s/%s", tracefs_prefix, "trace_marker");
373 if (n >= sizeof(path)) {
374 warn("tracefs path too long\n");
375 return;
376 }
377 tracemark_fd = open(path, O_WRONLY);
378 if (tracemark_fd < 0) {
379 warn("unable to open trace_marker file: %s\n", path);
380 return;
381 }
382 }
383
384 /*
385 * if we're not tracing and the tracing_on fd is not open,
386 * open the tracing_on file so that we can stop the trace
387 * if we hit a breaktrace threshold
388 */
389 if (trace_fd < 0) {
390 n = snprintf(path, sizeof(path), "%s/%s", tracefs_prefix, "tracing_on");
391 if (n >= sizeof(path)) {
392 warn("tracefs path too long\n");
393 return;
394 }
395 if ((trace_fd = open(path, O_WRONLY)) < 0)
396 warn("unable to open tracing_on file: %s\n", path);
397 }
398 }
399
400 static void close_tracemark_fd(void)
401 {
402 if (tracemark_fd > 0)
403 close(tracemark_fd);
404
405 if (trace_fd > 0)
406 close(trace_fd);
407 }
408
409 static int trace_file_exists(char *name)
410 {
411 struct stat sbuf;
412 return stat(tracefs_prefix, &sbuf) ? 0 : 1;
413 }
414
415 static void tracefs_prepare(void)
416 {
417 get_tracefs_prefix();
418 if (!trace_file_exists("tracing_enabled") &&
419 !trace_file_exists("tracing_on"))
420 warn("tracing_enabled or tracing_on not found\n"
421 "tracefs not found");
422 }
423
424 void tracemark(char *fmt, ...)
425 {
426 va_list ap;
427 int len;
428 int ret;
429
430 /* bail out if we're not tracing */
431 /* or if the kernel doesn't support trace_mark */
432 if (tracemark_fd < 0)
433 return;
434
435 va_start(ap, fmt);
436 len = vsnprintf(tracebuf, TRACEBUFSIZ, fmt, ap);
437 va_end(ap);
438
439 /* write the tracemark message */
440 ret = write(tracemark_fd, tracebuf, len);
441 if (ret != len)
442 warn("trace mark write failed\n");
443 }
444
445 void tracing_stop(void)
446 {
447 int ret;
448
449 if (trace_fd < 0)
450 return;
451 ret = write(trace_fd, "0\n", 2);
452 if (ret != 2)
453 warn("trace stop write failed\n");
454 }
455
456 void enable_trace_mark(void)
457 {
458 tracefs_prepare();
459 open_tracemark_fd();
460 }
461
462 void disable_trace_mark(void)
463 {
464 close_tracemark_fd();
465 }
466
467 static void get_timestamp(char *tsbuf)
468 {
469 struct timeval tv;
470 struct tm *tm;
471 time_t t;
472
473 gettimeofday(&tv, NULL);
474 t = tv.tv_sec;
475 tm = localtime(&t);
476 /* RFC 2822-compliant date format */
477 strftime(tsbuf, MAX_TS_SIZE, "%a, %d %b %Y %T %z", tm);
478 }
479
480 void rt_init(int argc, char *argv[])
481 {
482 int offset = 0;
483 int len, i;
484
485 test_cmdline[0] = '\0';
486
487 /*
488 * getopt_long() permutes the contents of argv as it scans, so
489 * that eventually all the nonoptions are at the end. Make a
490 * copy before calling getopt_long().
491 */
492 for (i = 0; i < argc;) {
493 len = strlen(argv[i]);
494 if (offset + len + 1 >= MAX_COMMAND_LINE)
495 break;
496
497 strcat(test_cmdline, argv[i]);
498 i++;
499 if (i < argc)
500 strcat(test_cmdline, " ");
501
502 offset += len + 1;
503 }
504
505 get_timestamp(ts_start);
506 }
507
508 void rt_write_json(const char *filename, int return_code,
509 void (*cb)(FILE *, void *),
510 void *data)
511 {
512 unsigned char buf[1];
513 struct utsname uts;
514 char ts_end[MAX_TS_SIZE];
515 FILE *f, *s;
516 size_t n;
517 int rt = 0;
518
519 if (!filename || !strcmp("-", filename)) {
520 f = stdout;
521 } else {
522 f = fopen(filename, "w");
523 if (!f)
524 err_exit(errno, "Failed to open '%s'\n", filename);
525 }
526
527 get_timestamp(ts_end);
528
529 s = fopen("/sys/kernel/realtime", "r");
530 if (s) {
531 n = fread(buf, 1, 1, s);
532 if (n == 1 && buf[0] == '1')
533 rt = 1;
534 fclose(s);
535 }
536
537 if (uname(&uts))
538 err_exit(errno, "Could not retrieve system information");
539
540 fprintf(f, "{\n");
541 fprintf(f, " \"file_version\": 1,\n");
542 fprintf(f, " \"cmdline:\": \"%s\",\n", test_cmdline);
543 fprintf(f, " \"rt_test_version:\": \"%1.2f\",\n", VERSION);
544 fprintf(f, " \"start_time\": \"%s\",\n", ts_start);
545 fprintf(f, " \"end_time\": \"%s\",\n", ts_end);
546 fprintf(f, " \"return_code\": %d,\n", return_code);
547 fprintf(f, " \"sysinfo\": {\n");
548 fprintf(f, " \"sysname\": \"%s\",\n", uts.sysname);
549 fprintf(f, " \"nodename\": \"%s\",\n", uts.nodename);
550 fprintf(f, " \"release\": \"%s\",\n", uts.release);
551 fprintf(f, " \"version\": \"%s\",\n", uts.version);
552 fprintf(f, " \"machine\": \"%s\",\n", uts.machine);
553 fprintf(f, " \"realtime\": %d\n", rt);
554
555 if (cb) {
556 fprintf(f, " },\n");
557 (cb)(f, data);
558 } else {
559 fprintf(f, " }\n");
560 }
561
562 fprintf(f, "}\n");
563
564 if (!filename || strcmp("-", filename))
565 fclose(f);
566 }