1 /*
2 * Copyright (c) 2018 Intel Corporation
3 * Copyright (c) 2021 Nordic Semiconductor ASA
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/ztest.h>
10
ZTEST(no_multithreading,test_k_busy_wait)11 ZTEST(no_multithreading, test_k_busy_wait)
12 {
13 int64_t now = k_uptime_get();
14 uint32_t watchdog = CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC;
15
16 while (k_uptime_get() != now) {
17 /* Wait until uptime progresses */
18 watchdog--;
19 if (watchdog == 0) {
20 zassert_false(true, "No progress in uptime");
21 }
22 }
23
24 now = k_uptime_get();
25 /* Check that k_busy_wait is working as expected. */
26 k_busy_wait(10000);
27
28 int64_t diff = k_uptime_get() - now;
29
30 zassert_within(diff, 10, 2);
31 }
32
timeout_handler(struct k_timer * timer)33 static void timeout_handler(struct k_timer *timer)
34 {
35 bool *flag = k_timer_user_data_get(timer);
36
37 *flag = true;
38 }
39
40 K_TIMER_DEFINE(timer, timeout_handler, NULL);
41
ZTEST(no_multithreading,test_irq_locking)42 ZTEST(no_multithreading, test_irq_locking)
43 {
44 volatile bool timeout_run = false;
45
46 k_timer_user_data_set(&timer, (void *)&timeout_run);
47 k_timer_start(&timer, K_MSEC(10), K_NO_WAIT);
48
49 unsigned int key = irq_lock();
50
51 k_busy_wait(15000);
52 zassert_false(timeout_run, "Timeout should not expire because irq is locked");
53
54 irq_unlock(key);
55
56 zassert_true(timeout_run, "Timeout should expire because irq got unlocked");
57 }
58
ZTEST(no_multithreading,test_cpu_idle)59 ZTEST(no_multithreading, test_cpu_idle)
60 {
61 volatile bool timeout_run = false;
62 int64_t now, diff;
63
64 k_timer_user_data_set(&timer, (void *)&timeout_run);
65 now = k_uptime_get();
66 /* Start timer and go to idle, cpu should sleep until it is waken up
67 * by sys clock interrupt.
68 */
69 k_timer_start(&timer, K_MSEC(10), K_NO_WAIT);
70
71 k_cpu_idle();
72
73 diff = k_uptime_get() - now;
74 zassert_true(timeout_run, "Timeout should expire");
75 zassert_within(diff, 10, 2, "Unexpected time passed: %d ms", (int)diff);
76 }
77
78 #define IDX_PRE_KERNEL_1 0
79 #define IDX_PRE_KERNEL_2 1
80 #define IDX_POST_KERNEL 2
81
82 #define SYS_INIT_CREATE(level) \
83 static int pre_kernel_##level##_init_func(void) \
84 { \
85 if (init_order != IDX_##level && sys_init_result == 0) { \
86 sys_init_result = -1; \
87 return -EIO; \
88 } \
89 init_order++; \
90 return 0;\
91 } \
92 SYS_INIT(pre_kernel_##level##_init_func, level, 0)
93
94 static int init_order;
95 static int sys_init_result;
96
97 FOR_EACH(SYS_INIT_CREATE, (;), PRE_KERNEL_1, PRE_KERNEL_2, POST_KERNEL);
98
ZTEST(no_multithreading,test_sys_init)99 ZTEST(no_multithreading, test_sys_init)
100 {
101 zassert_equal(init_order, 3, "SYS_INIT failed: %d", init_order);
102 }
103
104 ZTEST_SUITE(no_multithreading, NULL, NULL, NULL, NULL, NULL);
105