1 /*
2  * Copyright (c) 2024 Akaiwa Wataru <akaiwa@sonas.co.jp>
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #include <zephyr/kernel.h>
7 #include <zephyr/ztest.h>
8 
9 static k_tid_t thread_id;
10 
alarm_callback(struct k_timer * timer)11 static void alarm_callback(struct k_timer *timer)
12 {
13 	k_wakeup(thread_id);
14 }
15 
16 K_TIMER_DEFINE(alarm, alarm_callback, NULL);
17 
18 /**
19  * @brief Test 32-bit tick wraparound during k_sleep() execution
20  */
ZTEST(wraparound,test_tick_wraparound_in_sleep)21 ZTEST(wraparound, test_tick_wraparound_in_sleep)
22 {
23 	static const uint32_t start_ticks = 0xffffff00; /* It wraps around after 256 ticks! */
24 	static const uint32_t timeout_ticks = 300;      /* 3 seconds @ 100Hz tick */
25 	static const uint32_t wakeup_ticks = 10;        /* 100 ms @ 100Hz tick */
26 
27 	sys_clock_tick_set(start_ticks);
28 
29 	/* Wake up myself by alarm */
30 	thread_id = k_current_get();
31 	k_timer_start(&alarm, K_TICKS(wakeup_ticks), K_FOREVER);
32 
33 	/* Waiting alarm's k_wakeup() call */
34 	int32_t left_ms = k_sleep(K_TICKS(timeout_ticks));
35 
36 	zassert(left_ms > 0, "k_sleep() timed out");
37 
38 	k_timer_stop(&alarm);
39 }
40 
41 ZTEST_SUITE(wraparound, NULL, NULL, NULL, NULL, NULL);
42