1 /*
2  * Copyright (c) 1997-2016 Wind River Systems, Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 
9 #include <zephyr/init.h>
10 #include <zephyr/syscall_handler.h>
11 #include <stdbool.h>
12 #include <zephyr/spinlock.h>
13 #include <ksched.h>
14 #include <wait_q.h>
15 
16 static struct k_spinlock lock;
17 
18 #ifdef CONFIG_OBJ_CORE_TIMER
19 static struct k_obj_type obj_type_timer;
20 #endif
21 
22 /**
23  * @brief Handle expiration of a kernel timer object.
24  *
25  * @param t  Timeout used by the timer.
26  */
z_timer_expiration_handler(struct _timeout * t)27 void z_timer_expiration_handler(struct _timeout *t)
28 {
29 	struct k_timer *timer = CONTAINER_OF(t, struct k_timer, timeout);
30 	struct k_thread *thread;
31 	k_spinlock_key_t key = k_spin_lock(&lock);
32 
33 	/* In sys_clock_announce(), when a timeout expires, it is first removed
34 	 * from the timeout list, then its expiration handler is called (with
35 	 * unlocked interrupts). For kernel timers, the expiration handler is
36 	 * this function. Usually, the timeout structure related to the timer
37 	 * that is handled here will not be linked to the timeout list at this
38 	 * point. But it may happen that before this function is executed and
39 	 * interrupts are locked again, a given timer gets restarted from an
40 	 * interrupt context that has a priority higher than the system timer
41 	 * interrupt. Then, the timeout structure for this timer will turn out
42 	 * to be linked to the timeout list. And in such case, since the timer
43 	 * was restarted, its expiration handler should not be executed then,
44 	 * so the function exits immediately.
45 	 */
46 	if (sys_dnode_is_linked(&t->node)) {
47 		k_spin_unlock(&lock, key);
48 		return;
49 	}
50 
51 	/*
52 	 * if the timer is periodic, start it again; don't add _TICK_ALIGN
53 	 * since we're already aligned to a tick boundary
54 	 */
55 	if (!K_TIMEOUT_EQ(timer->period, K_NO_WAIT) &&
56 	    !K_TIMEOUT_EQ(timer->period, K_FOREVER)) {
57 		k_timeout_t next = timer->period;
58 
59 		/* see note about z_add_timeout() in z_impl_k_timer_start() */
60 		next.ticks = MAX(next.ticks - 1, 0);
61 
62 #ifdef CONFIG_TIMEOUT_64BIT
63 		/* Exploit the fact that uptime during a kernel
64 		 * timeout handler reflects the time of the scheduled
65 		 * event and not real time to get some inexpensive
66 		 * protection against late interrupts.  If we're
67 		 * delayed for any reason, we still end up calculating
68 		 * the next expiration as a regular stride from where
69 		 * we "should" have run.  Requires absolute timeouts.
70 		 * (Note offset by one: we're nominally at the
71 		 * beginning of a tick, so need to defeat the "round
72 		 * down" behavior on timeout addition).
73 		 */
74 		next = K_TIMEOUT_ABS_TICKS(k_uptime_ticks() + 1 + next.ticks);
75 #endif
76 		z_add_timeout(&timer->timeout, z_timer_expiration_handler,
77 			      next);
78 	}
79 
80 	/* update timer's status */
81 	timer->status += 1U;
82 
83 	/* invoke timer expiry function */
84 	if (timer->expiry_fn != NULL) {
85 		/* Unlock for user handler. */
86 		k_spin_unlock(&lock, key);
87 		timer->expiry_fn(timer);
88 		key = k_spin_lock(&lock);
89 	}
90 
91 	if (!IS_ENABLED(CONFIG_MULTITHREADING)) {
92 		k_spin_unlock(&lock, key);
93 		return;
94 	}
95 
96 	thread = z_waitq_head(&timer->wait_q);
97 
98 	if (thread == NULL) {
99 		k_spin_unlock(&lock, key);
100 		return;
101 	}
102 
103 	z_unpend_thread_no_timeout(thread);
104 
105 	arch_thread_return_value_set(thread, 0);
106 
107 	k_spin_unlock(&lock, key);
108 
109 	z_ready_thread(thread);
110 }
111 
112 
k_timer_init(struct k_timer * timer,k_timer_expiry_t expiry_fn,k_timer_stop_t stop_fn)113 void k_timer_init(struct k_timer *timer,
114 			 k_timer_expiry_t expiry_fn,
115 			 k_timer_stop_t stop_fn)
116 {
117 	timer->expiry_fn = expiry_fn;
118 	timer->stop_fn = stop_fn;
119 	timer->status = 0U;
120 
121 	if (IS_ENABLED(CONFIG_MULTITHREADING)) {
122 		z_waitq_init(&timer->wait_q);
123 	}
124 
125 	z_init_timeout(&timer->timeout);
126 
127 	SYS_PORT_TRACING_OBJ_INIT(k_timer, timer);
128 
129 	timer->user_data = NULL;
130 
131 	z_object_init(timer);
132 
133 #ifdef CONFIG_OBJ_CORE_TIMER
134 	k_obj_core_init_and_link(K_OBJ_CORE(timer), &obj_type_timer);
135 #endif
136 }
137 
138 
z_impl_k_timer_start(struct k_timer * timer,k_timeout_t duration,k_timeout_t period)139 void z_impl_k_timer_start(struct k_timer *timer, k_timeout_t duration,
140 			  k_timeout_t period)
141 {
142 	SYS_PORT_TRACING_OBJ_FUNC(k_timer, start, timer, duration, period);
143 
144 	if (K_TIMEOUT_EQ(duration, K_FOREVER)) {
145 		return;
146 	}
147 
148 	/* z_add_timeout() always adds one to the incoming tick count
149 	 * to round up to the next tick (by convention it waits for
150 	 * "at least as long as the specified timeout"), but the
151 	 * period interval is always guaranteed to be reset from
152 	 * within the timer ISR, so no round up is desired and 1 is
153 	 * subtracted in there.
154 	 *
155 	 * Note that the duration (!) value gets the same treatment
156 	 * for backwards compatibility.  This is unfortunate
157 	 * (i.e. k_timer_start() doesn't treat its initial sleep
158 	 * argument the same way k_sleep() does), but historical.  The
159 	 * timer_api test relies on this behavior.
160 	 */
161 	if (Z_TICK_ABS(duration.ticks) < 0) {
162 		duration.ticks = MAX(duration.ticks - 1, 0);
163 	}
164 
165 	(void)z_abort_timeout(&timer->timeout);
166 	timer->period = period;
167 	timer->status = 0U;
168 
169 	z_add_timeout(&timer->timeout, z_timer_expiration_handler,
170 		     duration);
171 }
172 
173 #ifdef CONFIG_USERSPACE
z_vrfy_k_timer_start(struct k_timer * timer,k_timeout_t duration,k_timeout_t period)174 static inline void z_vrfy_k_timer_start(struct k_timer *timer,
175 					k_timeout_t duration,
176 					k_timeout_t period)
177 {
178 	Z_OOPS(Z_SYSCALL_OBJ(timer, K_OBJ_TIMER));
179 	z_impl_k_timer_start(timer, duration, period);
180 }
181 #include <syscalls/k_timer_start_mrsh.c>
182 #endif
183 
z_impl_k_timer_stop(struct k_timer * timer)184 void z_impl_k_timer_stop(struct k_timer *timer)
185 {
186 	SYS_PORT_TRACING_OBJ_FUNC(k_timer, stop, timer);
187 
188 	bool inactive = (z_abort_timeout(&timer->timeout) != 0);
189 
190 	if (inactive) {
191 		return;
192 	}
193 
194 	if (timer->stop_fn != NULL) {
195 		timer->stop_fn(timer);
196 	}
197 
198 	if (IS_ENABLED(CONFIG_MULTITHREADING)) {
199 		struct k_thread *pending_thread = z_unpend1_no_timeout(&timer->wait_q);
200 
201 		if (pending_thread != NULL) {
202 			z_ready_thread(pending_thread);
203 			z_reschedule_unlocked();
204 		}
205 	}
206 }
207 
208 #ifdef CONFIG_USERSPACE
z_vrfy_k_timer_stop(struct k_timer * timer)209 static inline void z_vrfy_k_timer_stop(struct k_timer *timer)
210 {
211 	Z_OOPS(Z_SYSCALL_OBJ(timer, K_OBJ_TIMER));
212 	z_impl_k_timer_stop(timer);
213 }
214 #include <syscalls/k_timer_stop_mrsh.c>
215 #endif
216 
z_impl_k_timer_status_get(struct k_timer * timer)217 uint32_t z_impl_k_timer_status_get(struct k_timer *timer)
218 {
219 	k_spinlock_key_t key = k_spin_lock(&lock);
220 	uint32_t result = timer->status;
221 
222 	timer->status = 0U;
223 	k_spin_unlock(&lock, key);
224 
225 	return result;
226 }
227 
228 #ifdef CONFIG_USERSPACE
z_vrfy_k_timer_status_get(struct k_timer * timer)229 static inline uint32_t z_vrfy_k_timer_status_get(struct k_timer *timer)
230 {
231 	Z_OOPS(Z_SYSCALL_OBJ(timer, K_OBJ_TIMER));
232 	return z_impl_k_timer_status_get(timer);
233 }
234 #include <syscalls/k_timer_status_get_mrsh.c>
235 #endif
236 
z_impl_k_timer_status_sync(struct k_timer * timer)237 uint32_t z_impl_k_timer_status_sync(struct k_timer *timer)
238 {
239 	__ASSERT(!arch_is_in_isr(), "");
240 	SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_timer, status_sync, timer);
241 
242 	if (!IS_ENABLED(CONFIG_MULTITHREADING)) {
243 		uint32_t result;
244 
245 		do {
246 			k_spinlock_key_t key = k_spin_lock(&lock);
247 
248 			if (!z_is_inactive_timeout(&timer->timeout)) {
249 				result = *(volatile uint32_t *)&timer->status;
250 				timer->status = 0U;
251 				k_spin_unlock(&lock, key);
252 				if (result > 0) {
253 					break;
254 				}
255 			} else {
256 				result = timer->status;
257 				k_spin_unlock(&lock, key);
258 				break;
259 			}
260 		} while (true);
261 
262 		return result;
263 	}
264 
265 	k_spinlock_key_t key = k_spin_lock(&lock);
266 	uint32_t result = timer->status;
267 
268 	if (result == 0U) {
269 		if (!z_is_inactive_timeout(&timer->timeout)) {
270 			SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_timer, status_sync, timer, K_FOREVER);
271 
272 			/* wait for timer to expire or stop */
273 			(void)z_pend_curr(&lock, key, &timer->wait_q, K_FOREVER);
274 
275 			/* get updated timer status */
276 			key = k_spin_lock(&lock);
277 			result = timer->status;
278 		} else {
279 			/* timer is already stopped */
280 		}
281 	} else {
282 		/* timer has already expired at least once */
283 	}
284 
285 	timer->status = 0U;
286 	k_spin_unlock(&lock, key);
287 
288 	/**
289 	 * @note	New tracing hook
290 	 */
291 	SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_timer, status_sync, timer, result);
292 
293 	return result;
294 }
295 
296 #ifdef CONFIG_USERSPACE
z_vrfy_k_timer_status_sync(struct k_timer * timer)297 static inline uint32_t z_vrfy_k_timer_status_sync(struct k_timer *timer)
298 {
299 	Z_OOPS(Z_SYSCALL_OBJ(timer, K_OBJ_TIMER));
300 	return z_impl_k_timer_status_sync(timer);
301 }
302 #include <syscalls/k_timer_status_sync_mrsh.c>
303 
z_vrfy_k_timer_remaining_ticks(const struct k_timer * timer)304 static inline k_ticks_t z_vrfy_k_timer_remaining_ticks(
305 						const struct k_timer *timer)
306 {
307 	Z_OOPS(Z_SYSCALL_OBJ(timer, K_OBJ_TIMER));
308 	return z_impl_k_timer_remaining_ticks(timer);
309 }
310 #include <syscalls/k_timer_remaining_ticks_mrsh.c>
311 
z_vrfy_k_timer_expires_ticks(const struct k_timer * timer)312 static inline k_ticks_t z_vrfy_k_timer_expires_ticks(
313 						const struct k_timer *timer)
314 {
315 	Z_OOPS(Z_SYSCALL_OBJ(timer, K_OBJ_TIMER));
316 	return z_impl_k_timer_expires_ticks(timer);
317 }
318 #include <syscalls/k_timer_expires_ticks_mrsh.c>
319 
z_vrfy_k_timer_user_data_get(const struct k_timer * timer)320 static inline void *z_vrfy_k_timer_user_data_get(const struct k_timer *timer)
321 {
322 	Z_OOPS(Z_SYSCALL_OBJ(timer, K_OBJ_TIMER));
323 	return z_impl_k_timer_user_data_get(timer);
324 }
325 #include <syscalls/k_timer_user_data_get_mrsh.c>
326 
z_vrfy_k_timer_user_data_set(struct k_timer * timer,void * user_data)327 static inline void z_vrfy_k_timer_user_data_set(struct k_timer *timer,
328 						void *user_data)
329 {
330 	Z_OOPS(Z_SYSCALL_OBJ(timer, K_OBJ_TIMER));
331 	z_impl_k_timer_user_data_set(timer, user_data);
332 }
333 #include <syscalls/k_timer_user_data_set_mrsh.c>
334 
335 #endif
336 
337 #ifdef CONFIG_OBJ_CORE_TIMER
init_timer_obj_core_list(void)338 static int init_timer_obj_core_list(void)
339 {
340 	/* Initialize timer object type */
341 
342 	z_obj_type_init(&obj_type_timer, K_OBJ_TYPE_TIMER_ID,
343 			offsetof(struct k_timer, obj_core));
344 
345 	/* Initialize and link statically defined timers */
346 
347 	STRUCT_SECTION_FOREACH(k_timer, timer) {
348 		k_obj_core_init_and_link(K_OBJ_CORE(timer), &obj_type_timer);
349 	}
350 
351 	return 0;
352 }
353 SYS_INIT(init_timer_obj_core_list, PRE_KERNEL_1,
354 	 CONFIG_KERNEL_INIT_PRIORITY_OBJECTS);
355 #endif
356