1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2015-2016 Cyril Hrubis <[email protected]>
4 * Copyright (c) Linux Test Project, 2016-2024
5 */
6
7 #include <limits.h>
8 #include <stdio.h>
9 #include <stdarg.h>
10 #include <unistd.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <errno.h>
14 #include <sys/mount.h>
15 #include <sys/types.h>
16 #include <sys/wait.h>
17 #include <math.h>
18
19 #define TST_NO_DEFAULT_MAIN
20 #include "tst_test.h"
21 #include "tst_device.h"
22 #include "lapi/abisize.h"
23 #include "lapi/futex.h"
24 #include "lapi/syscalls.h"
25 #include "tst_ansi_color.h"
26 #include "tst_safe_stdio.h"
27 #include "tst_timer_test.h"
28 #include "tst_clocks.h"
29 #include "tst_timer.h"
30 #include "tst_wallclock.h"
31 #include "tst_sys_conf.h"
32 #include "tst_kconfig.h"
33 #include "tst_private.h"
34 #include "old_resource.h"
35 #include "old_device.h"
36 #include "old_tmpdir.h"
37 #include "ltp-version.h"
38
39 /*
40 * Hack to get TCID defined in newlib tests
41 */
42 const char *TCID __attribute__((weak));
43
44 /* update also docparse/testinfo.pl */
45 #define LINUX_GIT_URL "https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id="
46 #define LINUX_STABLE_GIT_URL "https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/commit/?id="
47 #define GLIBC_GIT_URL "https://sourceware.org/git/?p=glibc.git;a=commit;h="
48 #define MUSL_GIT_URL "https://git.musl-libc.org/cgit/musl/commit/src/linux/clone.c?id="
49 #define CVE_DB_URL "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-"
50
51 #define DEFAULT_TIMEOUT 30
52
53 struct tst_test *tst_test;
54
55 static const char *tid;
56 static int iterations = 1;
57 static float duration = -1;
58 static float timeout_mul = -1;
59 static pid_t main_pid, lib_pid;
60 static int mntpoint_mounted;
61 static int ovl_mounted;
62 static struct timespec tst_start_time; /* valid only for test pid */
63 static int tdebug;
64
65 struct results {
66 int passed;
67 int skipped;
68 int failed;
69 int warnings;
70 int broken;
71 unsigned int timeout;
72 int max_runtime;
73 };
74
75 static struct results *results;
76
77 static int ipc_fd;
78
79 extern void *tst_futexes;
80 extern unsigned int tst_max_futexes;
81
82 static char ipc_path[1064];
83 const char *tst_ipc_path = ipc_path;
84
85 static char shm_path[1024];
86
87 int TST_ERR;
88 int TST_PASS;
89 long TST_RET;
90
91 static void do_cleanup(void);
92 static void do_exit(int ret) __attribute__ ((noreturn));
93
setup_ipc(void)94 static void setup_ipc(void)
95 {
96 size_t size = getpagesize();
97
98 if (access("/dev/shm", F_OK) == 0) {
99 snprintf(shm_path, sizeof(shm_path), "/dev/shm/ltp_%s_%d",
100 tid, getpid());
101 } else {
102 char *tmpdir;
103
104 if (!tst_tmpdir_created())
105 tst_tmpdir();
106
107 tmpdir = tst_get_tmpdir();
108 snprintf(shm_path, sizeof(shm_path), "%s/ltp_%s_%d",
109 tmpdir, tid, getpid());
110 free(tmpdir);
111 }
112
113 ipc_fd = open(shm_path, O_CREAT | O_EXCL | O_RDWR, 0600);
114 if (ipc_fd < 0)
115 tst_brk(TBROK | TERRNO, "open(%s)", shm_path);
116 SAFE_CHMOD(shm_path, 0666);
117
118 SAFE_FTRUNCATE(ipc_fd, size);
119
120 results = SAFE_MMAP(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, ipc_fd, 0);
121
122 /* Checkpoints needs to be accessible from processes started by exec() */
123 if (tst_test->needs_checkpoints || tst_test->child_needs_reinit) {
124 sprintf(ipc_path, IPC_ENV_VAR "=%s", shm_path);
125 putenv(ipc_path);
126 } else {
127 SAFE_UNLINK(shm_path);
128 }
129
130 SAFE_CLOSE(ipc_fd);
131
132 if (tst_test->needs_checkpoints) {
133 tst_futexes = (char *)results + sizeof(struct results);
134 tst_max_futexes = (size - sizeof(struct results))/sizeof(futex_t);
135 }
136 }
137
cleanup_ipc(void)138 static void cleanup_ipc(void)
139 {
140 size_t size = getpagesize();
141
142 if (ipc_fd > 0 && close(ipc_fd))
143 tst_res(TWARN | TERRNO, "close(ipc_fd) failed");
144
145 if (shm_path[0] && !access(shm_path, F_OK) && unlink(shm_path))
146 tst_res(TWARN | TERRNO, "unlink(%s) failed", shm_path);
147
148 if (results) {
149 msync((void *)results, size, MS_SYNC);
150 munmap((void *)results, size);
151 results = NULL;
152 }
153 }
154
tst_reinit(void)155 void tst_reinit(void)
156 {
157 const char *path = getenv(IPC_ENV_VAR);
158 size_t size = getpagesize();
159 int fd;
160
161 if (!path)
162 tst_brk(TBROK, IPC_ENV_VAR" is not defined");
163
164 if (access(path, F_OK))
165 tst_brk(TBROK, "File %s does not exist!", path);
166
167 fd = SAFE_OPEN(path, O_RDWR);
168
169 results = SAFE_MMAP(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
170 tst_futexes = (char *)results + sizeof(struct results);
171 tst_max_futexes = (size - sizeof(struct results))/sizeof(futex_t);
172
173 SAFE_CLOSE(fd);
174 }
175
update_results(int ttype)176 static void update_results(int ttype)
177 {
178 if (!results)
179 return;
180
181 switch (ttype) {
182 case TCONF:
183 tst_atomic_inc(&results->skipped);
184 break;
185 case TPASS:
186 tst_atomic_inc(&results->passed);
187 break;
188 case TWARN:
189 tst_atomic_inc(&results->warnings);
190 break;
191 case TFAIL:
192 tst_atomic_inc(&results->failed);
193 break;
194 case TBROK:
195 tst_atomic_inc(&results->broken);
196 break;
197 }
198 }
199
print_result(const char * file,const int lineno,int ttype,const char * fmt,va_list va)200 static void print_result(const char *file, const int lineno, int ttype,
201 const char *fmt, va_list va)
202 {
203 char buf[1024];
204 char *str = buf;
205 int ret, size = sizeof(buf), ssize, int_errno, buflen;
206 const char *str_errno = NULL;
207 const char *res;
208
209 switch (TTYPE_RESULT(ttype)) {
210 case TPASS:
211 res = "TPASS";
212 break;
213 case TFAIL:
214 res = "TFAIL";
215 break;
216 case TBROK:
217 res = "TBROK";
218 break;
219 case TCONF:
220 res = "TCONF";
221 break;
222 case TWARN:
223 res = "TWARN";
224 break;
225 case TINFO:
226 res = "TINFO";
227 break;
228 case TDEBUG:
229 res = "TDEBUG";
230 break;
231 default:
232 tst_brk(TBROK, "Invalid ttype value %i", ttype);
233 abort();
234 }
235
236 if (ttype & TERRNO) {
237 str_errno = tst_strerrno(errno);
238 int_errno = errno;
239 }
240
241 if (ttype & TTERRNO) {
242 str_errno = tst_strerrno(TST_ERR);
243 int_errno = TST_ERR;
244 }
245
246 if (ttype & TRERRNO) {
247 int_errno = TST_RET < 0 ? -(int)TST_RET : (int)TST_RET;
248 str_errno = tst_strerrno(int_errno);
249 }
250
251 ret = snprintf(str, size, "%s:%i: ", file, lineno);
252 str += ret;
253 size -= ret;
254
255 if (tst_color_enabled(STDERR_FILENO))
256 ret = snprintf(str, size, "%s%s: %s", tst_ttype2color(ttype),
257 res, ANSI_COLOR_RESET);
258 else
259 ret = snprintf(str, size, "%s: ", res);
260 str += ret;
261 size -= ret;
262
263 ssize = size - 2;
264 ret = vsnprintf(str, size, fmt, va);
265 str += MIN(ret, ssize);
266 size -= MIN(ret, ssize);
267 if (ret >= ssize) {
268 tst_res_(file, lineno, TWARN,
269 "Next message is too long and truncated:");
270 } else if (str_errno) {
271 ssize = size - 2;
272 ret = snprintf(str, size, ": %s (%d)", str_errno, int_errno);
273 str += MIN(ret, ssize);
274 size -= MIN(ret, ssize);
275 if (ret >= ssize)
276 tst_res_(file, lineno, TWARN,
277 "Next message is too long and truncated:");
278 }
279
280 snprintf(str, size, "\n");
281
282 /* we might be called from signal handler, so use write() */
283 buflen = str - buf + 1;
284 str = buf;
285 while (buflen) {
286 ret = write(STDERR_FILENO, str, buflen);
287 if (ret <= 0)
288 break;
289
290 str += ret;
291 buflen -= ret;
292 }
293 }
294
tst_vres_(const char * file,const int lineno,int ttype,const char * fmt,va_list va)295 void tst_vres_(const char *file, const int lineno, int ttype, const char *fmt,
296 va_list va)
297 {
298 print_result(file, lineno, ttype, fmt, va);
299
300 update_results(TTYPE_RESULT(ttype));
301 }
302
303 void tst_vbrk_(const char *file, const int lineno, int ttype, const char *fmt,
304 va_list va);
305
306 static void (*tst_brk_handler)(const char *file, const int lineno, int ttype,
307 const char *fmt, va_list va) = tst_vbrk_;
308
tst_cvres(const char * file,const int lineno,int ttype,const char * fmt,va_list va)309 static void tst_cvres(const char *file, const int lineno, int ttype,
310 const char *fmt, va_list va)
311 {
312 if (TTYPE_RESULT(ttype) == TBROK) {
313 ttype &= ~TTYPE_MASK;
314 ttype |= TWARN;
315 }
316
317 print_result(file, lineno, ttype, fmt, va);
318 update_results(TTYPE_RESULT(ttype));
319 }
320
do_test_cleanup(void)321 static void do_test_cleanup(void)
322 {
323 tst_brk_handler = tst_cvres;
324
325 if (tst_test->cleanup)
326 tst_test->cleanup();
327
328 tst_free_all();
329
330 tst_brk_handler = tst_vbrk_;
331 }
332
tst_vbrk_(const char * file,const int lineno,int ttype,const char * fmt,va_list va)333 void tst_vbrk_(const char *file, const int lineno, int ttype, const char *fmt,
334 va_list va)
335 {
336 print_result(file, lineno, ttype, fmt, va);
337 update_results(TTYPE_RESULT(ttype));
338
339 /*
340 * The getpid implementation in some C library versions may cause cloned
341 * test threads to show the same pid as their parent when CLONE_VM is
342 * specified but CLONE_THREAD is not. Use direct syscall to avoid
343 * cleanup running in the child.
344 */
345 if (tst_getpid() == main_pid)
346 do_test_cleanup();
347
348 if (getpid() == lib_pid)
349 do_exit(TTYPE_RESULT(ttype));
350
351 exit(TTYPE_RESULT(ttype));
352 }
353
tst_res_(const char * file,const int lineno,int ttype,const char * fmt,...)354 void tst_res_(const char *file, const int lineno, int ttype,
355 const char *fmt, ...)
356 {
357 va_list va;
358
359 if (ttype == TDEBUG && !tdebug)
360 return;
361
362 va_start(va, fmt);
363 tst_vres_(file, lineno, ttype, fmt, va);
364 va_end(va);
365 }
366
tst_brk_(const char * file,const int lineno,int ttype,const char * fmt,...)367 void tst_brk_(const char *file, const int lineno, int ttype,
368 const char *fmt, ...)
369 {
370 va_list va;
371
372 va_start(va, fmt);
373 tst_brk_handler(file, lineno, ttype, fmt, va);
374 va_end(va);
375 }
376
tst_printf(const char * const fmt,...)377 void tst_printf(const char *const fmt, ...)
378 {
379 va_list va;
380
381 va_start(va, fmt);
382 vdprintf(STDERR_FILENO, fmt, va);
383 va_end(va);
384 }
385
check_child_status(pid_t pid,int status)386 static void check_child_status(pid_t pid, int status)
387 {
388 int ret;
389
390 if (WIFSIGNALED(status)) {
391 tst_brk(TBROK, "Child (%i) killed by signal %s", pid,
392 tst_strsig(WTERMSIG(status)));
393 }
394
395 if (!(WIFEXITED(status)))
396 tst_brk(TBROK, "Child (%i) exited abnormally", pid);
397
398 ret = WEXITSTATUS(status);
399 switch (ret) {
400 case TPASS:
401 case TBROK:
402 case TCONF:
403 break;
404 default:
405 tst_brk(TBROK, "Invalid child (%i) exit value %i", pid, ret);
406 }
407 }
408
tst_reap_children(void)409 void tst_reap_children(void)
410 {
411 int status;
412 pid_t pid;
413
414 for (;;) {
415 pid = wait(&status);
416
417 if (pid > 0) {
418 check_child_status(pid, status);
419 continue;
420 }
421
422 if (errno == ECHILD)
423 break;
424
425 if (errno == EINTR)
426 continue;
427
428 tst_brk(TBROK | TERRNO, "wait() failed");
429 }
430 }
431
432
safe_fork(const char * filename,unsigned int lineno)433 pid_t safe_fork(const char *filename, unsigned int lineno)
434 {
435 pid_t pid;
436
437 if (!tst_test->forks_child)
438 tst_brk(TBROK, "test.forks_child must be set!");
439
440 tst_flush();
441
442 pid = fork();
443 if (pid < 0)
444 tst_brk_(filename, lineno, TBROK | TERRNO, "fork() failed");
445
446 if (!pid)
447 atexit(tst_free_all);
448
449 return pid;
450 }
451
452 /* too fast creating namespaces => retrying */
453 #define TST_CHECK_ENOSPC(x) ((x) >= 0 || !(errno == ENOSPC))
454
safe_clone(const char * file,const int lineno,const struct tst_clone_args * args)455 pid_t safe_clone(const char *file, const int lineno,
456 const struct tst_clone_args *args)
457 {
458 pid_t pid;
459
460 if (!tst_test->forks_child)
461 tst_brk(TBROK, "test.forks_child must be set!");
462
463 pid = TST_RETRY_FUNC(tst_clone(args), TST_CHECK_ENOSPC);
464
465 switch (pid) {
466 case -1:
467 tst_brk_(file, lineno, TBROK | TERRNO, "clone3 failed");
468 break;
469 case -2:
470 tst_brk_(file, lineno, TBROK | TERRNO, "clone failed");
471 return -1;
472 }
473
474 if (!pid)
475 atexit(tst_free_all);
476
477 return pid;
478 }
479
parse_mul(float * mul,const char * env_name,float min,float max)480 static void parse_mul(float *mul, const char *env_name, float min, float max)
481 {
482 char *str_mul;
483 int ret;
484
485 if (*mul > 0)
486 return;
487
488 str_mul = getenv(env_name);
489
490 if (!str_mul) {
491 *mul = 1;
492 return;
493 }
494
495 ret = tst_parse_float(str_mul, mul, min, max);
496 if (ret) {
497 tst_brk(TBROK, "Failed to parse %s: %s",
498 env_name, tst_strerrno(ret));
499 }
500 }
501
multiply_runtime(int max_runtime)502 static int multiply_runtime(int max_runtime)
503 {
504 static float runtime_mul = -1;
505
506 if (max_runtime <= 0)
507 return max_runtime;
508
509 parse_mul(&runtime_mul, "LTP_RUNTIME_MUL", 0.0099, 100);
510
511 return max_runtime * runtime_mul;
512 }
513
514 static struct option {
515 char *optstr;
516 char *help;
517 } options[] = {
518 {"h", "-h Prints this help"},
519 {"i:", "-i n Execute test n times"},
520 {"I:", "-I x Execute test for n seconds"},
521 {"D", "-D Prints debug information"},
522 {"V", "-V Prints LTP version"},
523 };
524
print_help(void)525 static void print_help(void)
526 {
527 unsigned int i;
528 int timeout, runtime;
529
530 /* see doc/User-Guidelines.asciidoc, which lists also shell API variables */
531 fprintf(stderr, "Environment Variables\n");
532 fprintf(stderr, "---------------------\n");
533 fprintf(stderr, "KCONFIG_PATH Specify kernel config file\n");
534 fprintf(stderr, "KCONFIG_SKIP_CHECK Skip kernel config check if variable set (not set by default)\n");
535 fprintf(stderr, "LTPROOT Prefix for installed LTP (default: /opt/ltp)\n");
536 fprintf(stderr, "LTP_COLORIZE_OUTPUT Force colorized output behaviour (y/1 always, n/0: never)\n");
537 fprintf(stderr, "LTP_DEV Path to the block device to be used (for .needs_device)\n");
538 fprintf(stderr, "LTP_DEV_FS_TYPE Filesystem used for testing (default: %s)\n", DEFAULT_FS_TYPE);
539 fprintf(stderr, "LTP_SINGLE_FS_TYPE Testing only - specifies filesystem instead all supported (for .all_filesystems)\n");
540 fprintf(stderr, "LTP_TIMEOUT_MUL Timeout multiplier (must be a number >=1)\n");
541 fprintf(stderr, "LTP_RUNTIME_MUL Runtime multiplier (must be a number >=1)\n");
542 fprintf(stderr, "LTP_VIRT_OVERRIDE Overrides virtual machine detection (values: \"\"|kvm|microsoft|xen|zvm)\n");
543 fprintf(stderr, "TMPDIR Base directory for template directory (for .needs_tmpdir, default: %s)\n", TEMPDIR);
544 fprintf(stderr, "\n");
545
546 fprintf(stderr, "Timeout and runtime\n");
547 fprintf(stderr, "-------------------\n");
548
549 if (tst_test->max_runtime) {
550 runtime = multiply_runtime(tst_test->max_runtime);
551
552 if (runtime == TST_UNLIMITED_RUNTIME) {
553 fprintf(stderr, "Test iteration runtime is not limited\n");
554 } else {
555 fprintf(stderr, "Test iteration runtime cap %ih %im %is\n",
556 runtime/3600, (runtime%3600)/60, runtime % 60);
557 }
558 }
559
560 timeout = tst_multiply_timeout(DEFAULT_TIMEOUT);
561
562 fprintf(stderr, "Test timeout (not including runtime) %ih %im %is\n",
563 timeout/3600, (timeout%3600)/60, timeout % 60);
564
565 fprintf(stderr, "\n");
566
567 fprintf(stderr, "Options\n");
568 fprintf(stderr, "-------\n");
569
570 for (i = 0; i < ARRAY_SIZE(options); i++)
571 fprintf(stderr, "%s\n", options[i].help);
572
573 if (!tst_test->options)
574 return;
575
576 for (i = 0; tst_test->options[i].optstr; i++) {
577 fprintf(stderr, "-%c\t %s\n",
578 tst_test->options[i].optstr[0],
579 tst_test->options[i].help);
580 }
581 }
582
print_test_tags(void)583 static void print_test_tags(void)
584 {
585 unsigned int i;
586 const struct tst_tag *tags = tst_test->tags;
587
588 if (!tags)
589 return;
590
591 fprintf(stderr, "\nTags\n");
592 fprintf(stderr, "----\n");
593
594 for (i = 0; tags[i].name; i++) {
595 if (!strcmp(tags[i].name, "CVE"))
596 fprintf(stderr, CVE_DB_URL "%s\n", tags[i].value);
597 else if (!strcmp(tags[i].name, "linux-git"))
598 fprintf(stderr, LINUX_GIT_URL "%s\n", tags[i].value);
599 else if (!strcmp(tags[i].name, "linux-stable-git"))
600 fprintf(stderr, LINUX_STABLE_GIT_URL "%s\n", tags[i].value);
601 else if (!strcmp(tags[i].name, "glibc-git"))
602 fprintf(stderr, GLIBC_GIT_URL "%s\n", tags[i].value);
603 else if (!strcmp(tags[i].name, "musl-git"))
604 fprintf(stderr, MUSL_GIT_URL "%s\n", tags[i].value);
605 else
606 fprintf(stderr, "%s: %s\n", tags[i].name, tags[i].value);
607 }
608
609 fprintf(stderr, "\n");
610 }
611
check_option_collision(void)612 static void check_option_collision(void)
613 {
614 unsigned int i, j;
615 struct tst_option *toptions = tst_test->options;
616
617 if (!toptions)
618 return;
619
620 for (i = 0; toptions[i].optstr; i++) {
621 for (j = 0; j < ARRAY_SIZE(options); j++) {
622 if (toptions[i].optstr[0] == options[j].optstr[0]) {
623 tst_brk(TBROK, "Option collision '%s'",
624 options[j].help);
625 }
626 }
627 }
628 }
629
count_options(void)630 static unsigned int count_options(void)
631 {
632 unsigned int i;
633
634 if (!tst_test->options)
635 return 0;
636
637 for (i = 0; tst_test->options[i].optstr; i++)
638 ;
639
640 return i;
641 }
642
parse_topt(unsigned int topts_len,int opt,char * optarg)643 static void parse_topt(unsigned int topts_len, int opt, char *optarg)
644 {
645 unsigned int i;
646 struct tst_option *toptions = tst_test->options;
647
648 for (i = 0; i < topts_len; i++) {
649 if (toptions[i].optstr[0] == opt)
650 break;
651 }
652
653 if (i >= topts_len)
654 tst_brk(TBROK, "Invalid option '%c' (should not happen)", opt);
655
656 if (*toptions[i].arg)
657 tst_res(TWARN, "Option -%c passed multiple times", opt);
658
659 *(toptions[i].arg) = optarg ? optarg : "";
660 }
661
parse_opts(int argc,char * argv[])662 static void parse_opts(int argc, char *argv[])
663 {
664 unsigned int i, topts_len = count_options();
665 char optstr[2 * ARRAY_SIZE(options) + 2 * topts_len];
666 int opt;
667
668 check_option_collision();
669
670 optstr[0] = 0;
671
672 for (i = 0; i < ARRAY_SIZE(options); i++)
673 strcat(optstr, options[i].optstr);
674
675 for (i = 0; i < topts_len; i++)
676 strcat(optstr, tst_test->options[i].optstr);
677
678 while ((opt = getopt(argc, argv, optstr)) > 0) {
679 switch (opt) {
680 case '?':
681 print_help();
682 tst_brk(TBROK, "Invalid option");
683 break;
684 case 'D':
685 tst_res(TINFO, "Enabling debug info");
686 tdebug = 1;
687 break;
688 case 'h':
689 print_help();
690 print_test_tags();
691 exit(0);
692 case 'i':
693 iterations = SAFE_STRTOL(optarg, 0, INT_MAX);
694 break;
695 case 'I':
696 if (tst_test->max_runtime > 0)
697 tst_test->max_runtime = SAFE_STRTOL(optarg, 1, INT_MAX);
698 else
699 duration = SAFE_STRTOF(optarg, 0.1, HUGE_VALF);
700 break;
701 case 'V':
702 fprintf(stderr, "LTP version: " LTP_VERSION "\n");
703 exit(0);
704 break;
705 default:
706 parse_topt(topts_len, opt, optarg);
707 }
708 }
709
710 if (optind < argc)
711 tst_brk(TBROK, "Unexpected argument(s) '%s'...", argv[optind]);
712 }
713
tst_parse_int(const char * str,int * val,int min,int max)714 int tst_parse_int(const char *str, int *val, int min, int max)
715 {
716 long rval;
717
718 if (!str)
719 return 0;
720
721 int ret = tst_parse_long(str, &rval, min, max);
722
723 if (ret)
724 return ret;
725
726 *val = (int)rval;
727 return 0;
728 }
729
tst_parse_long(const char * str,long * val,long min,long max)730 int tst_parse_long(const char *str, long *val, long min, long max)
731 {
732 long rval;
733 char *end;
734
735 if (!str)
736 return 0;
737
738 errno = 0;
739 rval = strtol(str, &end, 10);
740
741 if (str == end || *end != '\0')
742 return EINVAL;
743
744 if (errno)
745 return errno;
746
747 if (rval > max || rval < min)
748 return ERANGE;
749
750 *val = rval;
751 return 0;
752 }
753
tst_parse_float(const char * str,float * val,float min,float max)754 int tst_parse_float(const char *str, float *val, float min, float max)
755 {
756 double rval;
757 char *end;
758
759 if (!str)
760 return 0;
761
762 errno = 0;
763 rval = strtod(str, &end);
764
765 if (str == end || *end != '\0')
766 return EINVAL;
767
768 if (errno)
769 return errno;
770
771 if (rval > (double)max || rval < (double)min)
772 return ERANGE;
773
774 *val = (float)rval;
775 return 0;
776 }
777
tst_parse_filesize(const char * str,long long * val,long long min,long long max)778 int tst_parse_filesize(const char *str, long long *val, long long min, long long max)
779 {
780 long long rval;
781 char *end;
782
783 if (!str)
784 return 0;
785
786 errno = 0;
787 rval = strtoll(str, &end, 0);
788
789 if (str == end || (end[0] && end[1]))
790 return EINVAL;
791
792 if (errno)
793 return errno;
794
795 switch (*end) {
796 case 'g':
797 case 'G':
798 rval *= (1024 * 1024 * 1024);
799 break;
800 case 'm':
801 case 'M':
802 rval *= (1024 * 1024);
803 break;
804 case 'k':
805 case 'K':
806 rval *= 1024;
807 break;
808 default:
809 break;
810 }
811
812 if (rval > max || rval < min)
813 return ERANGE;
814
815 *val = rval;
816 return 0;
817 }
818
print_colored(const char * str)819 static void print_colored(const char *str)
820 {
821 if (tst_color_enabled(STDOUT_FILENO))
822 fprintf(stderr, "%s%s%s", ANSI_COLOR_YELLOW, str, ANSI_COLOR_RESET);
823 else
824 fprintf(stderr, "%s", str);
825 }
826
print_failure_hint(const char * tag,const char * hint,const char * url)827 static void print_failure_hint(const char *tag, const char *hint,
828 const char *url)
829 {
830 const struct tst_tag *tags = tst_test->tags;
831
832 if (!tags)
833 return;
834
835 unsigned int i;
836 int hint_printed = 0;
837
838 for (i = 0; tags[i].name; i++) {
839 if (!strcmp(tags[i].name, tag)) {
840 if (!hint_printed) {
841 hint_printed = 1;
842 fprintf(stderr, "\n");
843 print_colored("HINT: ");
844 fprintf(stderr, "You _MAY_ be %s:\n\n", hint);
845 }
846
847 if (url)
848 fprintf(stderr, "%s%s\n", url, tags[i].value);
849 else
850 fprintf(stderr, "%s\n", tags[i].value);
851 }
852 }
853 }
854
855 /* update also docparse/testinfo.pl */
print_failure_hints(void)856 static void print_failure_hints(void)
857 {
858 print_failure_hint("linux-git", "missing kernel fixes", LINUX_GIT_URL);
859 print_failure_hint("linux-stable-git", "missing stable kernel fixes",
860 LINUX_STABLE_GIT_URL);
861 print_failure_hint("glibc-git", "missing glibc fixes", GLIBC_GIT_URL);
862 print_failure_hint("musl-git", "missing musl fixes", MUSL_GIT_URL);
863 print_failure_hint("CVE", "vulnerable to CVE(s)", CVE_DB_URL);
864 print_failure_hint("known-fail", "hit by known kernel failures", NULL);
865 }
866
do_exit(int ret)867 static void do_exit(int ret)
868 {
869 if (results) {
870 if (results->passed && ret == TCONF)
871 ret = 0;
872
873 if (results->failed) {
874 ret |= TFAIL;
875 print_failure_hints();
876 }
877
878 if (results->skipped && !results->passed)
879 ret |= TCONF;
880
881 if (results->warnings)
882 ret |= TWARN;
883
884 if (results->broken) {
885 ret |= TBROK;
886 print_failure_hints();
887 }
888
889 fprintf(stderr, "\nSummary:\n");
890 fprintf(stderr, "passed %d\n", results->passed);
891 fprintf(stderr, "failed %d\n", results->failed);
892 fprintf(stderr, "broken %d\n", results->broken);
893 fprintf(stderr, "skipped %d\n", results->skipped);
894 fprintf(stderr, "warnings %d\n", results->warnings);
895 }
896
897 do_cleanup();
898
899 exit(ret);
900 }
901
check_kver(void)902 void check_kver(void)
903 {
904 int v1, v2, v3;
905
906 if (tst_parse_kver(tst_test->min_kver, &v1, &v2, &v3)) {
907 tst_res(TWARN,
908 "Invalid kernel version %s, expected %%d.%%d.%%d",
909 tst_test->min_kver);
910 }
911
912 if (tst_kvercmp(v1, v2, v3) < 0) {
913 tst_brk(TCONF, "The test requires kernel %s or newer",
914 tst_test->min_kver);
915 }
916 }
917
results_equal(struct results * a,struct results * b)918 static int results_equal(struct results *a, struct results *b)
919 {
920 if (a->passed != b->passed)
921 return 0;
922
923 if (a->failed != b->failed)
924 return 0;
925
926 if (a->skipped != b->skipped)
927 return 0;
928
929 if (a->broken != b->broken)
930 return 0;
931
932 return 1;
933 }
934
needs_tmpdir(void)935 static int needs_tmpdir(void)
936 {
937 return tst_test->needs_tmpdir ||
938 tst_test->needs_device ||
939 tst_test->mntpoint ||
940 tst_test->resource_files ||
941 tst_test->needs_checkpoints;
942 }
943
copy_resources(void)944 static void copy_resources(void)
945 {
946 unsigned int i;
947
948 for (i = 0; tst_test->resource_files[i]; i++)
949 TST_RESOURCE_COPY(NULL, tst_test->resource_files[i], NULL);
950 }
951
get_tid(char * argv[])952 static const char *get_tid(char *argv[])
953 {
954 char *p;
955
956 if (!argv[0] || !argv[0][0]) {
957 tst_res(TINFO, "argv[0] is empty!");
958 return "ltp_empty_argv";
959 }
960
961 p = strrchr(argv[0], '/');
962 if (p)
963 return p+1;
964
965 return argv[0];
966 }
967
968 static struct tst_device tdev;
969 struct tst_device *tst_device;
970
assert_test_fn(void)971 static void assert_test_fn(void)
972 {
973 int cnt = 0;
974
975 if (tst_test->test)
976 cnt++;
977
978 if (tst_test->test_all)
979 cnt++;
980
981 if (tst_test->sample)
982 cnt++;
983
984 if (!cnt)
985 tst_brk(TBROK, "No test function specified");
986
987 if (cnt != 1)
988 tst_brk(TBROK, "You can define only one test function");
989
990 if (tst_test->test && !tst_test->tcnt)
991 tst_brk(TBROK, "Number of tests (tcnt) must be > 0");
992
993 if (!tst_test->test && tst_test->tcnt)
994 tst_brk(TBROK, "You can define tcnt only for test()");
995 }
996
prepare_and_mount_ro_fs(const char * dev,const char * mntpoint,const char * fs_type)997 static int prepare_and_mount_ro_fs(const char *dev, const char *mntpoint,
998 const char *fs_type)
999 {
1000 char buf[PATH_MAX];
1001
1002 if (mount(dev, mntpoint, fs_type, 0, NULL)) {
1003 tst_res(TINFO | TERRNO, "Can't mount %s at %s (%s)",
1004 dev, mntpoint, fs_type);
1005 return 1;
1006 }
1007
1008 mntpoint_mounted = 1;
1009
1010 snprintf(buf, sizeof(buf), "%s/dir/", mntpoint);
1011 SAFE_MKDIR(buf, 0777);
1012
1013 snprintf(buf, sizeof(buf), "%s/file", mntpoint);
1014 SAFE_FILE_PRINTF(buf, "file content");
1015 SAFE_CHMOD(buf, 0777);
1016
1017 SAFE_MOUNT(dev, mntpoint, fs_type, MS_REMOUNT | MS_RDONLY, NULL);
1018
1019 return 0;
1020 }
1021
prepare_and_mount_dev_fs(const char * mntpoint)1022 static void prepare_and_mount_dev_fs(const char *mntpoint)
1023 {
1024 const char *flags[] = {"nodev", NULL};
1025 int mounted_nodev;
1026
1027 mounted_nodev = tst_path_has_mnt_flags(NULL, flags);
1028 if (mounted_nodev) {
1029 tst_res(TINFO, "tmpdir isn't suitable for creating devices, "
1030 "mounting tmpfs without nodev on %s", mntpoint);
1031 SAFE_MOUNT(NULL, mntpoint, "tmpfs", 0, NULL);
1032 mntpoint_mounted = 1;
1033 }
1034 }
1035
prepare_and_mount_hugetlb_fs(void)1036 static void prepare_and_mount_hugetlb_fs(void)
1037 {
1038 SAFE_MOUNT("none", tst_test->mntpoint, "hugetlbfs", 0, NULL);
1039 mntpoint_mounted = 1;
1040 }
1041
tst_creat_unlinked(const char * path,int flags)1042 int tst_creat_unlinked(const char *path, int flags)
1043 {
1044 char template[PATH_MAX];
1045 int len, c, range;
1046 int fd;
1047 int start[3] = {'0', 'a', 'A'};
1048
1049 snprintf(template, PATH_MAX, "%s/ltp_%.3sXXXXXX",
1050 path, tid);
1051
1052 len = strlen(template) - 1;
1053 while (template[len] == 'X') {
1054 c = rand() % 3;
1055 range = start[c] == '0' ? 10 : 26;
1056 c = start[c] + (rand() % range);
1057 template[len--] = (char)c;
1058 }
1059
1060 flags |= O_CREAT|O_EXCL|O_RDWR;
1061 fd = SAFE_OPEN(template, flags);
1062 SAFE_UNLINK(template);
1063 return fd;
1064 }
1065
limit_tmpfs_mount_size(const char * mnt_data,char * buf,size_t buf_size,const char * fs_type)1066 static const char *limit_tmpfs_mount_size(const char *mnt_data,
1067 char *buf, size_t buf_size, const char *fs_type)
1068 {
1069 unsigned int tmpfs_size;
1070
1071 if (strcmp(fs_type, "tmpfs"))
1072 return mnt_data;
1073
1074 if (!tst_test->dev_min_size)
1075 tmpfs_size = 32;
1076 else
1077 tmpfs_size = tdev.size;
1078
1079 if ((tst_available_mem() / 1024) < (tmpfs_size * 2))
1080 tst_brk(TCONF, "No enough memory for tmpfs use");
1081
1082 if (mnt_data)
1083 snprintf(buf, buf_size, "%s,size=%uM", mnt_data, tmpfs_size);
1084 else
1085 snprintf(buf, buf_size, "size=%uM", tmpfs_size);
1086
1087 tst_res(TINFO, "Limiting tmpfs size to %uMB", tmpfs_size);
1088
1089 return buf;
1090 }
1091
get_device_name(const char * fs_type)1092 static const char *get_device_name(const char *fs_type)
1093 {
1094 if (!strcmp(fs_type, "tmpfs"))
1095 return "ltp-tmpfs";
1096 else
1097 return tdev.dev;
1098 }
1099
prepare_device(void)1100 static void prepare_device(void)
1101 {
1102 const char *mnt_data;
1103 char buf[1024];
1104
1105 if (tst_test->format_device) {
1106 SAFE_MKFS(tdev.dev, tdev.fs_type, tst_test->dev_fs_opts,
1107 tst_test->dev_extra_opts);
1108 }
1109
1110 if (tst_test->needs_rofs) {
1111 prepare_and_mount_ro_fs(tdev.dev, tst_test->mntpoint,
1112 tdev.fs_type);
1113 return;
1114 }
1115
1116 if (tst_test->mount_device) {
1117 mnt_data = limit_tmpfs_mount_size(tst_test->mnt_data,
1118 buf, sizeof(buf), tdev.fs_type);
1119
1120 SAFE_MOUNT(get_device_name(tdev.fs_type), tst_test->mntpoint,
1121 tdev.fs_type, tst_test->mnt_flags, mnt_data);
1122 mntpoint_mounted = 1;
1123 }
1124 }
1125
do_cgroup_requires(void)1126 static void do_cgroup_requires(void)
1127 {
1128 const struct tst_cg_opts cg_opts = {
1129 .needs_ver = tst_test->needs_cgroup_ver,
1130 .needs_nsdelegate = tst_test->needs_cgroup_nsdelegate,
1131 };
1132 const char *const *ctrl_names = tst_test->needs_cgroup_ctrls;
1133
1134 for (; *ctrl_names; ctrl_names++)
1135 tst_cg_require(*ctrl_names, &cg_opts);
1136
1137 tst_cg_init();
1138 }
1139
1140 #define tst_set_ulimit(conf) \
1141 set_ulimit_(__FILE__, __LINE__, (conf))
1142
1143 /*
1144 * Set resource limits.
1145 */
set_ulimit_(const char * file,const int lineno,const struct tst_ulimit_val * conf)1146 static void set_ulimit_(const char *file, const int lineno, const struct tst_ulimit_val *conf)
1147 {
1148 struct rlimit rlim;
1149
1150 safe_getrlimit(file, lineno, conf->resource, &rlim);
1151
1152 rlim.rlim_cur = conf->rlim_cur;
1153
1154 if (conf->rlim_cur > rlim.rlim_max)
1155 rlim.rlim_max = conf->rlim_cur;
1156
1157 tst_res_(file, lineno, TINFO, "Set ulimit resource: %d rlim_cur: %lu rlim_max: %lu",
1158 conf->resource, rlim.rlim_cur, rlim.rlim_max);
1159
1160 safe_setrlimit(file, lineno, conf->resource, &rlim);
1161 }
1162
do_setup(int argc,char * argv[])1163 static void do_setup(int argc, char *argv[])
1164 {
1165 char *tdebug_env = getenv("LTP_ENABLE_DEBUG");
1166
1167 if (!tst_test)
1168 tst_brk(TBROK, "No tests to run");
1169
1170 if (tst_test->max_runtime < -1) {
1171 tst_brk(TBROK, "Invalid runtime value %i",
1172 results->max_runtime);
1173 }
1174
1175 if (tst_test->tconf_msg)
1176 tst_brk(TCONF, "%s", tst_test->tconf_msg);
1177
1178 assert_test_fn();
1179
1180 TCID = tid = get_tid(argv);
1181
1182 if (tst_test->sample)
1183 tst_test = tst_timer_test_setup(tst_test);
1184
1185 parse_opts(argc, argv);
1186
1187 if (tdebug_env && (!strcmp(tdebug_env, "1") || !strcmp(tdebug_env, "y"))) {
1188 tst_res(TINFO, "Enabling debug info");
1189 tdebug = 1;
1190 }
1191
1192 if (tst_test->needs_kconfigs && tst_kconfig_check(tst_test->needs_kconfigs))
1193 tst_brk(TCONF, "Aborting due to unsuitable kernel config, see above!");
1194
1195 if (tst_test->needs_root && geteuid() != 0)
1196 tst_brk(TCONF, "Test needs to be run as root");
1197
1198 if (tst_test->min_kver)
1199 check_kver();
1200
1201 if (tst_test->supported_archs && !tst_is_on_arch(tst_test->supported_archs))
1202 tst_brk(TCONF, "This arch '%s' is not supported for test!", tst_arch.name);
1203
1204 if (tst_test->skip_in_lockdown && tst_lockdown_enabled() > 0)
1205 tst_brk(TCONF, "Kernel is locked down, skipping test");
1206
1207 if (tst_test->skip_in_secureboot && tst_secureboot_enabled() > 0)
1208 tst_brk(TCONF, "SecureBoot enabled, skipping test");
1209
1210 if (tst_test->skip_in_compat && tst_is_compat_mode())
1211 tst_brk(TCONF, "Not supported in 32-bit compat mode");
1212
1213 if (tst_test->needs_abi_bits && !tst_abi_bits(tst_test->needs_abi_bits))
1214 tst_brk(TCONF, "%dbit ABI is not supported", tst_test->needs_abi_bits);
1215
1216 if (tst_test->needs_cmds) {
1217 const char *cmd;
1218 int i;
1219
1220 for (i = 0; (cmd = tst_test->needs_cmds[i]); ++i)
1221 tst_check_cmd(cmd);
1222 }
1223
1224 if (tst_test->needs_drivers) {
1225 const char *name;
1226 int i;
1227
1228 for (i = 0; (name = tst_test->needs_drivers[i]); ++i)
1229 if (tst_check_driver(name))
1230 tst_brk(TCONF, "%s driver not available", name);
1231 }
1232
1233 if (tst_test->mount_device)
1234 tst_test->format_device = 1;
1235
1236 if (tst_test->format_device)
1237 tst_test->needs_device = 1;
1238
1239 if (tst_test->all_filesystems)
1240 tst_test->needs_device = 1;
1241
1242 if (tst_test->min_cpus > (unsigned long)tst_ncpus())
1243 tst_brk(TCONF, "Test needs at least %lu CPUs online", tst_test->min_cpus);
1244
1245 if (tst_test->min_mem_avail > (unsigned long)(tst_available_mem() / 1024))
1246 tst_brk(TCONF, "Test needs at least %luMB MemAvailable", tst_test->min_mem_avail);
1247
1248 if (tst_test->min_swap_avail > (unsigned long)(tst_available_swap() / 1024))
1249 tst_brk(TCONF, "Test needs at least %luMB SwapFree", tst_test->min_swap_avail);
1250
1251 if (tst_test->hugepages.number)
1252 tst_reserve_hugepages(&tst_test->hugepages);
1253
1254 setup_ipc();
1255
1256 if (tst_test->bufs)
1257 tst_buffers_alloc(tst_test->bufs);
1258
1259 if (needs_tmpdir() && !tst_tmpdir_created())
1260 tst_tmpdir();
1261
1262 if (tst_test->save_restore) {
1263 const struct tst_path_val *pvl = tst_test->save_restore;
1264
1265 while (pvl->path) {
1266 tst_sys_conf_save(pvl);
1267 pvl++;
1268 }
1269 }
1270
1271 if (tst_test->ulimit) {
1272 const struct tst_ulimit_val *pvl = tst_test->ulimit;
1273
1274 while (pvl->resource) {
1275 tst_set_ulimit(pvl);
1276 pvl++;
1277 }
1278 }
1279
1280 if (tst_test->mntpoint)
1281 SAFE_MKDIR(tst_test->mntpoint, 0777);
1282
1283 if ((tst_test->needs_devfs || tst_test->needs_rofs ||
1284 tst_test->mount_device || tst_test->all_filesystems ||
1285 tst_test->needs_hugetlbfs) &&
1286 !tst_test->mntpoint) {
1287 tst_brk(TBROK, "tst_test->mntpoint must be set!");
1288 }
1289
1290 if (!!tst_test->needs_rofs + !!tst_test->needs_devfs +
1291 !!tst_test->needs_device + !!tst_test->needs_hugetlbfs > 1) {
1292 tst_brk(TBROK,
1293 "Two or more of needs_{rofs, devfs, device, hugetlbfs} are set");
1294 }
1295
1296 if (tst_test->needs_devfs)
1297 prepare_and_mount_dev_fs(tst_test->mntpoint);
1298
1299 if (tst_test->needs_rofs) {
1300 /* If we failed to mount read-only tmpfs. Fallback to
1301 * using a device with read-only filesystem.
1302 */
1303 if (prepare_and_mount_ro_fs(NULL, tst_test->mntpoint, "tmpfs")) {
1304 tst_res(TINFO, "Can't mount tmpfs read-only, "
1305 "falling back to block device...");
1306 tst_test->needs_device = 1;
1307 tst_test->format_device = 1;
1308 }
1309 }
1310
1311 if (tst_test->needs_hugetlbfs)
1312 prepare_and_mount_hugetlb_fs();
1313
1314 if (tst_test->needs_device && !mntpoint_mounted) {
1315 tdev.dev = tst_acquire_device_(NULL, tst_test->dev_min_size);
1316
1317 if (!tdev.dev)
1318 tst_brk(TCONF, "Failed to acquire device");
1319
1320 tdev.size = tst_get_device_size(tdev.dev);
1321
1322 tst_device = &tdev;
1323
1324 if (tst_test->dev_fs_type)
1325 tdev.fs_type = tst_test->dev_fs_type;
1326 else
1327 tdev.fs_type = tst_dev_fs_type();
1328
1329 if (!tst_test->all_filesystems)
1330 prepare_device();
1331 }
1332
1333 if (tst_test->needs_overlay && !tst_test->mount_device)
1334 tst_brk(TBROK, "tst_test->mount_device must be set");
1335
1336 if (tst_test->needs_overlay && !mntpoint_mounted)
1337 tst_brk(TBROK, "tst_test->mntpoint must be mounted");
1338
1339 if (tst_test->needs_overlay && !ovl_mounted) {
1340 SAFE_MOUNT_OVERLAY();
1341 ovl_mounted = 1;
1342 }
1343
1344 if (tst_test->resource_files)
1345 copy_resources();
1346
1347 if (tst_test->restore_wallclock)
1348 tst_wallclock_save();
1349
1350 if (tst_test->taint_check)
1351 tst_taint_init(tst_test->taint_check);
1352
1353 if (tst_test->needs_cgroup_ctrls)
1354 do_cgroup_requires();
1355 else if (tst_test->needs_cgroup_ver)
1356 tst_brk(TBROK, "tst_test->needs_cgroup_ctrls must be set");
1357 }
1358
do_test_setup(void)1359 static void do_test_setup(void)
1360 {
1361 main_pid = getpid();
1362
1363 if (!tst_test->all_filesystems && tst_test->skip_filesystems) {
1364 long fs_type = tst_fs_type(".");
1365 const char *fs_name = tst_fs_type_name(fs_type);
1366
1367 if (tst_fs_in_skiplist(fs_name, tst_test->skip_filesystems)) {
1368 tst_brk(TCONF, "%s is not supported by the test",
1369 fs_name);
1370 }
1371
1372 tst_res(TINFO, "%s is supported by the test", fs_name);
1373 }
1374
1375 if (tst_test->caps)
1376 tst_cap_setup(tst_test->caps, TST_CAP_REQ);
1377
1378 if (tst_test->setup)
1379 tst_test->setup();
1380
1381 if (main_pid != tst_getpid())
1382 tst_brk(TBROK, "Runaway child in setup()!");
1383
1384 if (tst_test->caps)
1385 tst_cap_setup(tst_test->caps, TST_CAP_DROP);
1386 }
1387
do_cleanup(void)1388 static void do_cleanup(void)
1389 {
1390 if (tst_test->needs_cgroup_ctrls)
1391 tst_cg_cleanup();
1392
1393 if (ovl_mounted)
1394 SAFE_UMOUNT(OVL_MNT);
1395
1396 if (mntpoint_mounted)
1397 tst_umount(tst_test->mntpoint);
1398
1399 if (tst_test->needs_device && tdev.dev)
1400 tst_release_device(tdev.dev);
1401
1402 if (tst_tmpdir_created()) {
1403 /* avoid munmap() on wrong pointer in tst_rmdir() */
1404 tst_futexes = NULL;
1405 tst_rmdir();
1406 }
1407
1408 tst_sys_conf_restore(0);
1409
1410 if (tst_test->restore_wallclock)
1411 tst_wallclock_restore();
1412
1413 cleanup_ipc();
1414 }
1415
heartbeat(void)1416 static void heartbeat(void)
1417 {
1418 if (tst_clock_gettime(CLOCK_MONOTONIC, &tst_start_time))
1419 tst_res(TWARN | TERRNO, "tst_clock_gettime() failed");
1420
1421 if (getppid() == 1) {
1422 tst_res(TFAIL, "Main test process might have exit!");
1423 /*
1424 * We need kill the task group immediately since the
1425 * main process has exit.
1426 */
1427 kill(0, SIGKILL);
1428 exit(TBROK);
1429 }
1430
1431 kill(getppid(), SIGUSR1);
1432 }
1433
run_tests(void)1434 static void run_tests(void)
1435 {
1436 unsigned int i;
1437 struct results saved_results;
1438
1439 if (!tst_test->test) {
1440 saved_results = *results;
1441 heartbeat();
1442 tst_test->test_all();
1443
1444 if (tst_getpid() != main_pid)
1445 exit(0);
1446
1447 tst_reap_children();
1448
1449 if (results_equal(&saved_results, results))
1450 tst_brk(TBROK, "Test haven't reported results!");
1451 return;
1452 }
1453
1454 for (i = 0; i < tst_test->tcnt; i++) {
1455 saved_results = *results;
1456 heartbeat();
1457 tst_test->test(i);
1458
1459 if (tst_getpid() != main_pid)
1460 exit(0);
1461
1462 tst_reap_children();
1463
1464 if (results_equal(&saved_results, results))
1465 tst_brk(TBROK, "Test %i haven't reported results!", i);
1466 }
1467 }
1468
get_time_ms(void)1469 static unsigned long long get_time_ms(void)
1470 {
1471 struct timespec ts;
1472
1473 if (tst_clock_gettime(CLOCK_MONOTONIC, &ts))
1474 tst_brk(TBROK | TERRNO, "tst_clock_gettime()");
1475
1476 return tst_timespec_to_ms(ts);
1477 }
1478
add_paths(void)1479 static void add_paths(void)
1480 {
1481 char *old_path = getenv("PATH");
1482 const char *start_dir;
1483 char *new_path;
1484
1485 start_dir = tst_get_startwd();
1486
1487 if (old_path)
1488 SAFE_ASPRINTF(&new_path, "%s::%s", old_path, start_dir);
1489 else
1490 SAFE_ASPRINTF(&new_path, "::%s", start_dir);
1491
1492 SAFE_SETENV("PATH", new_path, 1);
1493 free(new_path);
1494 }
1495
testrun(void)1496 static void testrun(void)
1497 {
1498 unsigned int i = 0;
1499 unsigned long long stop_time = 0;
1500 int cont = 1;
1501
1502 heartbeat();
1503 add_paths();
1504 do_test_setup();
1505
1506 if (duration > 0)
1507 stop_time = get_time_ms() + (unsigned long long)(duration * 1000);
1508
1509 for (;;) {
1510 cont = 0;
1511
1512 if (i < (unsigned int)iterations) {
1513 i++;
1514 cont = 1;
1515 }
1516
1517 if (stop_time && get_time_ms() < stop_time)
1518 cont = 1;
1519
1520 if (!cont)
1521 break;
1522
1523 run_tests();
1524 heartbeat();
1525 }
1526
1527 do_test_cleanup();
1528 exit(0);
1529 }
1530
1531 static pid_t test_pid;
1532
1533
1534 static volatile sig_atomic_t sigkill_retries;
1535
1536 #define WRITE_MSG(msg) do { \
1537 if (write(2, msg, sizeof(msg) - 1)) { \
1538 /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425 */ \
1539 } \
1540 } while (0)
1541
alarm_handler(int sig LTP_ATTRIBUTE_UNUSED)1542 static void alarm_handler(int sig LTP_ATTRIBUTE_UNUSED)
1543 {
1544 WRITE_MSG("Test timeouted, sending SIGKILL!\n");
1545 kill(-test_pid, SIGKILL);
1546 alarm(5);
1547
1548 if (++sigkill_retries > 10) {
1549 WRITE_MSG("Cannot kill test processes!\n");
1550 WRITE_MSG("Congratulation, likely test hit a kernel bug.\n");
1551 WRITE_MSG("Exiting uncleanly...\n");
1552 _exit(TFAIL);
1553 }
1554 }
1555
heartbeat_handler(int sig LTP_ATTRIBUTE_UNUSED)1556 static void heartbeat_handler(int sig LTP_ATTRIBUTE_UNUSED)
1557 {
1558 alarm(results->timeout);
1559 sigkill_retries = 0;
1560 }
1561
sigint_handler(int sig LTP_ATTRIBUTE_UNUSED)1562 static void sigint_handler(int sig LTP_ATTRIBUTE_UNUSED)
1563 {
1564 if (test_pid > 0) {
1565 WRITE_MSG("Sending SIGKILL to test process...\n");
1566 kill(-test_pid, SIGKILL);
1567 }
1568 }
1569
tst_remaining_runtime(void)1570 unsigned int tst_remaining_runtime(void)
1571 {
1572 static struct timespec now;
1573 int elapsed;
1574
1575 if (results->max_runtime == TST_UNLIMITED_RUNTIME)
1576 return UINT_MAX;
1577
1578 if (results->max_runtime == 0)
1579 tst_brk(TBROK, "Runtime not set!");
1580
1581 if (tst_clock_gettime(CLOCK_MONOTONIC, &now))
1582 tst_res(TWARN | TERRNO, "tst_clock_gettime() failed");
1583
1584 elapsed = tst_timespec_diff_ms(now, tst_start_time) / 1000;
1585 if (results->max_runtime > elapsed)
1586 return results->max_runtime - elapsed;
1587
1588 return 0;
1589 }
1590
1591
tst_multiply_timeout(unsigned int timeout)1592 unsigned int tst_multiply_timeout(unsigned int timeout)
1593 {
1594 parse_mul(&timeout_mul, "LTP_TIMEOUT_MUL", 0.099, 10000);
1595
1596 if (timeout < 1)
1597 tst_brk(TBROK, "timeout must to be >= 1! (%d)", timeout);
1598
1599 return timeout * timeout_mul;
1600 }
1601
set_timeout(void)1602 static void set_timeout(void)
1603 {
1604 unsigned int timeout = DEFAULT_TIMEOUT;
1605
1606 if (results->max_runtime == TST_UNLIMITED_RUNTIME) {
1607 tst_res(TINFO, "Timeout per run is disabled");
1608 return;
1609 }
1610
1611 if (results->max_runtime < 0) {
1612 tst_brk(TBROK, "max_runtime must to be >= -1! (%d)",
1613 results->max_runtime);
1614 }
1615
1616 results->timeout = tst_multiply_timeout(timeout) + results->max_runtime;
1617
1618 tst_res(TINFO, "Timeout per run is %uh %02um %02us",
1619 results->timeout/3600, (results->timeout%3600)/60,
1620 results->timeout % 60);
1621 }
1622
tst_set_max_runtime(int max_runtime)1623 void tst_set_max_runtime(int max_runtime)
1624 {
1625 results->max_runtime = multiply_runtime(max_runtime);
1626 tst_res(TINFO, "Updating max runtime to %uh %02um %02us",
1627 max_runtime/3600, (max_runtime%3600)/60, max_runtime % 60);
1628 set_timeout();
1629 heartbeat();
1630 }
1631
fork_testrun(void)1632 static int fork_testrun(void)
1633 {
1634 int status;
1635
1636 SAFE_SIGNAL(SIGINT, sigint_handler);
1637 SAFE_SIGNAL(SIGTERM, sigint_handler);
1638
1639 alarm(results->timeout);
1640
1641 test_pid = fork();
1642 if (test_pid < 0)
1643 tst_brk(TBROK | TERRNO, "fork()");
1644
1645 if (!test_pid) {
1646 tst_disable_oom_protection(0);
1647 SAFE_SIGNAL(SIGALRM, SIG_DFL);
1648 SAFE_SIGNAL(SIGUSR1, SIG_DFL);
1649 SAFE_SIGNAL(SIGTERM, SIG_DFL);
1650 SAFE_SIGNAL(SIGINT, SIG_DFL);
1651 SAFE_SETPGID(0, 0);
1652 testrun();
1653 }
1654
1655 SAFE_WAITPID(test_pid, &status, 0);
1656 alarm(0);
1657 SAFE_SIGNAL(SIGTERM, SIG_DFL);
1658 SAFE_SIGNAL(SIGINT, SIG_DFL);
1659
1660 if (tst_test->taint_check && tst_taint_check()) {
1661 tst_res(TFAIL, "Kernel is now tainted.");
1662 return TFAIL;
1663 }
1664
1665 if (tst_test->forks_child && kill(-test_pid, SIGKILL) == 0)
1666 tst_res(TINFO, "Killed the leftover descendant processes");
1667
1668 if (WIFEXITED(status) && WEXITSTATUS(status))
1669 return WEXITSTATUS(status);
1670
1671 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL) {
1672 tst_res(TINFO, "If you are running on slow machine, "
1673 "try exporting LTP_TIMEOUT_MUL > 1");
1674 tst_brk(TBROK, "Test killed! (timeout?)");
1675 }
1676
1677 if (WIFSIGNALED(status))
1678 tst_brk(TBROK, "Test killed by %s!", tst_strsig(WTERMSIG(status)));
1679
1680 return 0;
1681 }
1682
run_tcases_per_fs(void)1683 static int run_tcases_per_fs(void)
1684 {
1685 int ret = 0;
1686 unsigned int i;
1687 const char *const *filesystems = tst_get_supported_fs_types(tst_test->skip_filesystems);
1688
1689 if (!filesystems[0])
1690 tst_brk(TCONF, "There are no supported filesystems");
1691
1692 for (i = 0; filesystems[i]; i++) {
1693
1694 tst_res(TINFO, "=== Testing on %s ===", filesystems[i]);
1695 tdev.fs_type = filesystems[i];
1696
1697 prepare_device();
1698
1699 ret = fork_testrun();
1700
1701 if (mntpoint_mounted) {
1702 tst_umount(tst_test->mntpoint);
1703 mntpoint_mounted = 0;
1704 }
1705
1706 if (ret == TCONF)
1707 continue;
1708
1709 if (ret == 0)
1710 continue;
1711
1712 do_exit(ret);
1713 }
1714
1715 return ret;
1716 }
1717
1718 unsigned int tst_variant;
1719
tst_run_tcases(int argc,char * argv[],struct tst_test * self)1720 void tst_run_tcases(int argc, char *argv[], struct tst_test *self)
1721 {
1722 int ret = 0;
1723 unsigned int test_variants = 1;
1724
1725 lib_pid = getpid();
1726 tst_test = self;
1727
1728 do_setup(argc, argv);
1729 tst_enable_oom_protection(lib_pid);
1730
1731 SAFE_SIGNAL(SIGALRM, alarm_handler);
1732 SAFE_SIGNAL(SIGUSR1, heartbeat_handler);
1733
1734 tst_res(TINFO, "LTP version: "LTP_VERSION);
1735
1736 if (tst_test->max_runtime)
1737 results->max_runtime = multiply_runtime(tst_test->max_runtime);
1738
1739 set_timeout();
1740
1741 if (tst_test->test_variants)
1742 test_variants = tst_test->test_variants;
1743
1744 for (tst_variant = 0; tst_variant < test_variants; tst_variant++) {
1745 if (tst_test->all_filesystems)
1746 ret |= run_tcases_per_fs();
1747 else
1748 ret |= fork_testrun();
1749
1750 if (ret & ~(TCONF))
1751 goto exit;
1752 }
1753
1754 exit:
1755 do_exit(ret);
1756 }
1757
1758
tst_flush(void)1759 void tst_flush(void)
1760 {
1761 int rval;
1762
1763 rval = fflush(stderr);
1764 if (rval != 0)
1765 tst_brk(TBROK | TERRNO, "fflush(stderr) failed");
1766
1767 rval = fflush(stdout);
1768 if (rval != 0)
1769 tst_brk(TBROK | TERRNO, "fflush(stdout) failed");
1770
1771 }
1772