1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * 07/2001 Ported by Wayne Boyer
5 * Copyright (C) Cyril Hrubis <chrubis@suse.cz>
6 */
7
8 /*
9 * Test Description:
10 * Verify that nanosleep() will be successful to suspend the execution
11 * of a process, returns after the receipt of a signal and writes the
12 * remaining sleep time into the structure.
13 */
14
15 #include <errno.h>
16
17 #include "tst_test.h"
18 #include "tst_timer.h"
19 #include "tst_safe_macros.h"
20
21 /*
22 * Define here the "rem" precision in microseconds,
23 * Various implementations will provide different
24 * precisions. The -aa tree provides up to usec precision.
25 * NOTE: all the trees that don't provide a precision of
26 * the order of the microseconds are subject to an userspace
27 * live lock condition with glibc under a flood of signals,
28 * the "rem" field would never change without the increased
29 * usec precision in the -aa tree.
30 */
31 #define USEC_PRECISION 250000 /* Error margin allowed in usec */
32
do_child(void)33 static void do_child(void)
34 {
35 struct timespec timereq = {.tv_sec = 5, .tv_nsec = 9999};
36 struct timespec timerem, exp_rem;
37
38 tst_timer_start(CLOCK_MONOTONIC);
39 TEST(nanosleep(&timereq, &timerem));
40 tst_timer_stop();
41
42 if (!TST_RET)
43 tst_brk(TBROK, "nanosleep was not interrupted");
44 if (TST_ERR != EINTR)
45 tst_brk(TBROK | TTERRNO, "nanosleep() failed");
46
47 if (tst_timespec_lt(timereq, tst_timer_elapsed()))
48 tst_brk(TFAIL, "nanosleep() slept more than timereq");
49
50 exp_rem = tst_timespec_diff(timereq, tst_timer_elapsed());
51
52 if (tst_timespec_abs_diff_us(timerem, exp_rem) > USEC_PRECISION) {
53 tst_res(TFAIL,
54 "nanosleep() remaining time %llius, expected %llius, diff %llius",
55 tst_timespec_to_us(timerem), tst_timespec_to_us(exp_rem),
56 tst_timespec_abs_diff_us(timerem, exp_rem));
57 } else {
58 tst_res(TPASS,
59 "nanosleep() slept for %llius, remaining time difference %llius",
60 tst_timer_elapsed_us(),
61 tst_timespec_abs_diff_us(timerem, exp_rem));
62 }
63 }
64
run(void)65 void run(void)
66 {
67 pid_t cpid;
68
69 cpid = SAFE_FORK();
70 if (cpid == 0) {
71 do_child();
72 } else {
73 sleep(1);
74
75 SAFE_KILL(cpid, SIGINT);
76
77 tst_reap_children();
78 }
79 }
80
sig_handler(int si LTP_ATTRIBUTE_UNUSED)81 static void sig_handler(int si LTP_ATTRIBUTE_UNUSED)
82 {
83 }
84
setup(void)85 static void setup(void)
86 {
87 tst_timer_check(CLOCK_MONOTONIC);
88 SAFE_SIGNAL(SIGINT, sig_handler);
89 }
90
91 static struct tst_test test = {
92 .forks_child = 1,
93 .setup = setup,
94 .test_all = run,
95 };
96