1 /*
2  * Copyright (c) 2022, Meta
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <unistd.h>
8 
9 #include <zephyr/ztest.h>
10 
11 struct waker_work {
12 	k_tid_t tid;
13 	struct k_work_delayable dwork;
14 };
15 static struct waker_work wake_work;
16 
waker_func(struct k_work * work)17 static void waker_func(struct k_work *work)
18 {
19 	struct waker_work *ww;
20 	struct k_work_delayable *dwork = k_work_delayable_from_work(work);
21 
22 	ww = CONTAINER_OF(dwork, struct waker_work, dwork);
23 	k_wakeup(ww->tid);
24 }
25 K_WORK_DELAYABLE_DEFINE(waker, waker_func);
26 
ZTEST(sleep,test_sleep)27 ZTEST(sleep, test_sleep)
28 {
29 	uint32_t then;
30 	uint32_t now;
31 	/* call sleep(10), wakeup after 1s, expect >= 8s left */
32 	const uint32_t sleep_min_s = 1;
33 	const uint32_t sleep_max_s = 10;
34 	const uint32_t sleep_rem_s = 8;
35 
36 	/* sleeping for 0s should return 0 */
37 	zassert_ok(sleep(0));
38 
39 	/* test that sleeping for 1s sleeps for at least 1s */
40 	then = k_uptime_get();
41 	zassert_equal(0, sleep(1));
42 	now = k_uptime_get();
43 	zassert_true((now - then) >= 1 * MSEC_PER_SEC);
44 
45 	/* test that sleeping for 2s sleeps for at least 2s */
46 	then = k_uptime_get();
47 	zassert_equal(0, sleep(2));
48 	now = k_uptime_get();
49 	zassert_true((now - then) >= 2 * MSEC_PER_SEC);
50 
51 	/* test that sleep reports the remainder */
52 	wake_work.tid = k_current_get();
53 	k_work_init_delayable(&wake_work.dwork, waker_func);
54 	zassert_equal(1, k_work_schedule(&wake_work.dwork, K_SECONDS(sleep_min_s)));
55 	zassert_true(sleep(sleep_max_s) >= sleep_rem_s);
56 }
57 
ZTEST(sleep,test_usleep)58 ZTEST(sleep, test_usleep)
59 {
60 	uint32_t then;
61 	uint32_t now;
62 
63 	/* test usleep works for small values */
64 	/* Note: k_usleep(), an implementation detail, is a cancellation point */
65 	zassert_equal(0, usleep(0));
66 	zassert_equal(0, usleep(1));
67 
68 	/* sleep for the spec limit */
69 	then = k_uptime_get();
70 	zassert_equal(0, usleep(USEC_PER_SEC - 1));
71 	now = k_uptime_get();
72 	zassert_true(((now - then) * USEC_PER_MSEC) / (USEC_PER_SEC - 1) >= 1);
73 
74 	/* sleep for exactly the limit threshold */
75 	zassert_equal(-1, usleep(USEC_PER_SEC));
76 	zassert_equal(errno, EINVAL);
77 
78 	/* sleep for over the spec limit */
79 	zassert_equal(-1, usleep((useconds_t)ULONG_MAX));
80 	zassert_equal(errno, EINVAL);
81 
82 	/* test that sleep reports errno = EINTR when woken up */
83 	wake_work.tid = k_current_get();
84 	k_work_init_delayable(&wake_work.dwork, waker_func);
85 	zassert_equal(1, k_work_schedule(&wake_work.dwork, K_USEC(USEC_PER_SEC / 2)));
86 	zassert_equal(-1, usleep(USEC_PER_SEC - 1));
87 	zassert_equal(EINTR, errno);
88 }
89 
90 ZTEST_SUITE(sleep, NULL, NULL, NULL, NULL, NULL);
91