Branch data Line data Source code
1 : : /*
2 : : * Copyright (c) 2018 Intel Corporation
3 : : *
4 : : * SPDX-License-Identifier: Apache-2.0
5 : : */
6 : :
7 : : #include <zephyr/sys/minmax.h>
8 : : #include <zephyr/kernel.h>
9 : : #include <zephyr/spinlock.h>
10 : : #include <ksched.h>
11 : : #include <timeout_q.h>
12 : : #include <zephyr/internal/syscall_handler.h>
13 : : #include <zephyr/drivers/timer/system_timer.h>
14 : : #include <zephyr/sys/clock.h>
15 : : #include <zephyr/llext/symbol.h>
16 : :
17 : : #include <timeslicing.h>
18 : :
19 : : /* Absolute tick counter: ticks since boot. */
20 : : static uint64_t curr_tick;
21 : :
22 : : /*
23 : : * The timeout code shall take no locks other than its own (timeout_lock), nor
24 : : * shall it call any other subsystem while holding this lock. Code outside this
25 : : * file takes it through sys_clock_lock()/sys_clock_unlock().
26 : : */
27 : : static struct k_spinlock timeout_lock;
28 : :
29 : : /* Ticks left to process in the currently-executing sys_clock_announce() */
30 : : static uint32_t announce_remaining;
31 : :
32 : : /* CPU id currently inside sys_clock_announce_locked()'s firing loop, or -1
33 : : * when no CPU is. The SMP early-return below ensures at most one CPU is in
34 : : * the loop at a time, so a single int suffices. Used by code that needs to
35 : : * know whether *this* CPU is at a tick edge (announcing) versus somewhere
36 : : * within a tick (any other context, including running on a CPU while a
37 : : * different CPU is the announcer).
38 : : */
39 : : static int announcing_cpu = -1;
40 : :
41 : 188 : static inline bool this_cpu_announcing(void)
42 : : {
43 : 188 : return announcing_cpu == CPU_ID;
44 : : }
45 : :
46 : 63 : static inline bool any_cpu_announcing(void)
47 : : {
48 : 63 : return announcing_cpu != -1;
49 : : }
50 : :
51 : : /* Timeout whose handler is currently being dispatched, or NULL when no
52 : : * handler is in flight. The announcing CPU sets the pointer before
53 : : * calling the handler and clears it afterwards; any aborter may set the
54 : : * low "superseded" bit (struct _timeout is pointer-aligned so bit 0 is
55 : : * free). Accessors below mask the bit.
56 : : */
57 : : static struct _timeout *inflight_timeout;
58 : :
59 : : #define INFLIGHT_SUPERSEDED_BIT 1UL
60 : :
61 : 239 : static inline struct _timeout *inflight_ptr(void)
62 : : {
63 : 239 : return (struct _timeout *)((uintptr_t)inflight_timeout & ~INFLIGHT_SUPERSEDED_BIT);
64 : : }
65 : :
66 : 0 : static inline void inflight_mark_superseded(void)
67 : : {
68 : 0 : inflight_timeout = (struct _timeout *)((uintptr_t)inflight_timeout |
69 : : INFLIGHT_SUPERSEDED_BIT);
70 : 0 : }
71 : :
72 : 125 : static uint32_t elapsed(void)
73 : : {
74 : : /*
75 : : * While *this* CPU is executing sys_clock_announce_locked()'s firing
76 : : * loop, new relative timeouts scheduled from a callback (or from a
77 : : * higher-priority ISR that preempted one) are anchored to the currently
78 : : * firing tick (curr_tick), so we report 0.
79 : : *
80 : : * On any other CPU the picture is different: we are not at a tick edge,
81 : : * and curr_tick is partway through being advanced by the announcing
82 : : * CPU's loop. The invariant we want to preserve is
83 : : *
84 : : * T_real - curr_tick = announce_remaining + sys_clock_elapsed()
85 : : *
86 : : * because the driver bumped its internal announced-cycle baseline to
87 : : * (curr_tick_initial + N) * CYC_PER_TICK at ISR entry, while the kernel
88 : : * has only advanced curr_tick by the K ticks processed so far -- so
89 : : * announce_remaining (= N - K) is the residual that must be added to
90 : : * sys_clock_elapsed() to get the real-time delta from curr_tick. This
91 : : * keeps sys_clock_tick_get() monotonic across the announce window.
92 : : */
93 [ + - ]: 125 : if (this_cpu_announcing()) {
94 : : return 0U;
95 : : }
96 : 125 : return sys_clock_elapsed() +
97 : : (IS_ENABLED(CONFIG_SMP) ? announce_remaining : 0);
98 : : }
99 : :
100 : : /*
101 : : * Backend queue implementation. The selected backend's queue instance and its
102 : : * z_timeout_q_*() operations are private to this file: the backend is a header
103 : : * included only here, after the shared state above, so those operations can
104 : : * reach curr_tick / announce_remaining / inflight_timeout / timeout_lock
105 : : * directly. The per-node helpers (z_init_timeout / z_is_inactive_timeout) are
106 : : * tree-wide and live in timeout_q.h.
107 : : */
108 : : #if defined(CONFIG_TIMEOUT_BACKEND_MINHEAP)
109 : : #include "timeout/minheap.h"
110 : : #elif defined(CONFIG_TIMEOUT_BACKEND_WHEEL)
111 : : #include "timeout/wheel.h"
112 : : #elif defined(CONFIG_TIMEOUT_BACKEND_BUCKET)
113 : : #include "timeout/bucket.h"
114 : : #elif defined(CONFIG_TIMEOUT_BACKEND_SKIPLIST)
115 : : #include "timeout/skiplist.h"
116 : : #else /* CONFIG_TIMEOUT_BACKEND_DLIST */
117 : : #include "timeout/list.h"
118 : : #endif
119 : :
120 : : /*
121 : : * Ticks the driver may wait before the next sys_clock_announce(). The
122 : : * announce-range cap lives here, in the backend-independent front end, so no
123 : : * backend has to reproduce it: the backend only reports the delta to its
124 : : * earliest pending timeout via z_timeout_q_next_expiry().
125 : : */
126 : 125 : static uint32_t next_timeout(uint32_t ticks_elapsed)
127 : : {
128 : 125 : k_ticks_t next = z_timeout_q_next_expiry();
129 : 125 : uint32_t dticks;
130 : :
131 : : /*
132 : : * sys_clock_announce() reports the ticks elapsed since the previous
133 : : * announce, so the gap between two announces must not exceed
134 : : * SYS_CLOCK_MAX_WAIT for the announced count to fit. The budget left
135 : : * from now on is SYS_CLOCK_MAX_WAIT - ticks_elapsed; if it is already
136 : : * spent ask for an announce right away.
137 : : */
138 [ + - ]: 125 : if (ticks_elapsed >= SYS_CLOCK_MAX_WAIT) {
139 : : return 0;
140 : : }
141 : :
142 : : /*
143 : : * No deadline, or one further out than can be scheduled in a single
144 : : * step: wait the capped budget and re-evaluate at the next announce.
145 : : * Testing next (which may be 64-bit) against the cap keeps the
146 : : * remaining arithmetic in 32 bits. The empty case still returns the
147 : : * budget so a driver keeps waking to maintain uptime.
148 : : */
149 [ + + ]: 125 : if (next == K_TICKS_FOREVER || next >= SYS_CLOCK_MAX_WAIT) {
150 : 62 : return SYS_CLOCK_MAX_WAIT - ticks_elapsed;
151 : : }
152 : :
153 : : /* Otherwise wait until the timeout, relative to now (0 if due). */
154 : 63 : dticks = (uint32_t)next;
155 : :
156 [ + - ]: 63 : return (dticks > ticks_elapsed) ? (dticks - ticks_elapsed) : 0;
157 : : }
158 : :
159 : : /*
160 : : * Reprogram the timer for the next pending timeout, or, when nothing is
161 : : * pending and CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE tolerates a drifting uptime, tell
162 : : * the driver its clock is unused so it may stop. Only meaningful where the
163 : : * timeout queue may have just drained (abort, end of announce); the add path
164 : : * always has a pending timeout and calls sys_clock_set_timeout() directly.
165 : : */
166 : 62 : static void reprogram_next(uint32_t ticks_elapsed)
167 : : {
168 : 62 : if (IS_ENABLED(CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE) &&
169 : : z_timeout_q_next_expiry() == K_TICKS_FOREVER) {
170 : : sys_clock_no_timeout();
171 : : } else {
172 : 62 : sys_clock_set_timeout(next_timeout(ticks_elapsed), false);
173 : : }
174 : 62 : }
175 : :
176 : 123 : k_ticks_t z_add_timeout(struct _timeout *to, _timeout_func_t fn, k_timeout_t timeout)
177 : : {
178 : 123 : k_ticks_t ticks = 0;
179 : :
180 [ + + ]: 123 : if (K_TIMEOUT_EQ(timeout, K_FOREVER)) {
181 : : return 0;
182 : : }
183 : :
184 : : #ifdef CONFIG_KERNEL_COHERENCE
185 : : __ASSERT_NO_MSG(sys_cache_is_mem_coherent(to));
186 : : #endif /* CONFIG_KERNEL_COHERENCE */
187 : :
188 [ - + ]: 63 : __ASSERT(z_is_inactive_timeout(to), "");
189 : 63 : to->fn = fn;
190 : :
191 [ + + ]: 126 : K_SPINLOCK(&timeout_lock) {
192 : 63 : uint32_t ticks_elapsed = 0;
193 : 63 : bool has_elapsed = false;
194 : 63 : k_ticks_t dticks;
195 : :
196 [ + - ]: 63 : if (Z_IS_TIMEOUT_RELATIVE(timeout)) {
197 : 63 : ticks_elapsed = elapsed();
198 : 63 : has_elapsed = true;
199 : : /*
200 : : * In the general case, "now" may be anywhere within
201 : : * the current tick. Rounding up by one tick guarantees
202 : : * "at least N ticks" semantics -- otherwise a request
203 : : * made partway through a tick would fire on the next
204 : : * tick edge, yielding less than N full ticks.
205 : : *
206 : : * The one moment we know *this* CPU is at a tick edge
207 : : * is while it is processing timeouts inside its own
208 : : * sys_clock_announce_locked() loop. Periodic timers
209 : : * rely on this when rescheduling themselves from the
210 : : * timer ISR: the round-up would otherwise accumulate
211 : : * and make every period one tick late. The check is
212 : : * per-CPU: a thread on another CPU running while we
213 : : * announce is *not* at a tick edge and still needs
214 : : * the round-up.
215 : : */
216 : 63 : dticks = timeout.ticks + ticks_elapsed +
217 : 63 : (this_cpu_announcing() ? 0 : 1);
218 : 63 : ticks = curr_tick + dticks;
219 : : } else {
220 : 0 : dticks = Z_TICK_ABS(timeout.ticks) - curr_tick;
221 : 0 : dticks = max(1, dticks);
222 : : /* report the decoded absolute expiry, not the Z_TICK_ABS encoding */
223 : 0 : ticks = Z_TICK_ABS(timeout.ticks);
224 : : }
225 : :
226 [ + - + - ]: 63 : if (z_timeout_q_insert(to, dticks) && !any_cpu_announcing()) {
227 [ - + ]: 63 : if (!has_elapsed) {
228 : : /* In case of absolute timeout that is first to expire
229 : : * elapsed need to be read from the system clock.
230 : : */
231 : 0 : ticks_elapsed = elapsed();
232 : : }
233 : 63 : sys_clock_set_timeout(next_timeout(ticks_elapsed), false);
234 : : }
235 : : }
236 : :
237 : 63 : return ticks;
238 : : }
239 : :
240 : 239 : int z_try_abort_timeout(struct _timeout *to)
241 : : {
242 : 239 : int ret = -EINVAL;
243 : :
244 [ + + ]: 478 : K_SPINLOCK(&timeout_lock) {
245 [ + + ]: 239 : if (!z_is_inactive_timeout(to)) {
246 : 62 : bool was_first = z_timeout_q_remove(to);
247 : :
248 : 62 : ret = 0;
249 [ - + ]: 62 : if (was_first) {
250 : 62 : reprogram_next(elapsed());
251 : : }
252 : : }
253 : :
254 : 239 : if (IS_ENABLED(CONFIG_SMP) && inflight_ptr() == to &&
255 : : !this_cpu_announcing()) {
256 : : /* Handler in flight on another CPU, even if we just
257 : : * removed a copy it re-queued (periodic timer).
258 : : * Free-safety callers retry on -EAGAIN to wait it
259 : : * out; others rely on the superseded mark below.
260 : : */
261 : : ret = -EAGAIN;
262 : : }
263 : :
264 : : /* Record that the in-flight timeout has been aborted, so a
265 : : * handler that checks (z_timeout_inflight_superseded) can
266 : : * tell its dispatch was overtaken.
267 : : */
268 [ - + ]: 239 : if (inflight_ptr() == to) {
269 : 0 : inflight_mark_superseded();
270 : : }
271 : : }
272 : :
273 : 239 : if (IS_ENABLED(CONFIG_SMP) && ret == -EAGAIN) {
274 : : arch_spin_relax();
275 : : }
276 : :
277 : 239 : return ret;
278 : : }
279 : :
280 : 0 : bool z_timeout_inflight_superseded(const struct _timeout *to)
281 : : {
282 : 0 : bool superseded = false;
283 : :
284 [ # # ]: 0 : K_SPINLOCK(&timeout_lock) {
285 : 0 : superseded = inflight_timeout ==
286 : 0 : (struct _timeout *)((uintptr_t)to | INFLIGHT_SUPERSEDED_BIT);
287 : : }
288 : :
289 : 0 : return superseded;
290 : : }
291 : :
292 : 0 : k_ticks_t z_timeout_remaining(const struct _timeout *timeout)
293 : : {
294 : 0 : k_ticks_t ticks = 0;
295 : :
296 [ # # ]: 0 : K_SPINLOCK(&timeout_lock) {
297 [ # # ]: 0 : if (!z_is_inactive_timeout(timeout)) {
298 : 0 : k_ticks_t rem = z_timeout_q_remainder(timeout);
299 : 0 : uint32_t el = elapsed();
300 : :
301 : : /* elapsed() can exceed rem when announce is late. */
302 [ # # ]: 0 : ticks = (rem > el) ? (rem - el) : 0;
303 : : }
304 : : }
305 : :
306 : 0 : return ticks;
307 : : }
308 : : EXPORT_SYMBOL(z_timeout_remaining);
309 : :
310 : 0 : k_ticks_t z_timeout_expires(const struct _timeout *timeout)
311 : : {
312 : 0 : k_ticks_t ticks = 0;
313 : :
314 [ # # ]: 0 : K_SPINLOCK(&timeout_lock) {
315 : 0 : ticks = curr_tick;
316 [ # # ]: 0 : if (!z_is_inactive_timeout(timeout)) {
317 : 0 : ticks += z_timeout_q_remainder(timeout);
318 : : }
319 : : }
320 : :
321 : 0 : return ticks;
322 : : }
323 : : EXPORT_SYMBOL(z_timeout_expires);
324 : :
325 : 0 : uint32_t z_get_next_timeout_expiry(void)
326 : : {
327 : 0 : uint32_t ret = (uint32_t)K_TICKS_FOREVER;
328 : :
329 [ # # ]: 0 : K_SPINLOCK(&timeout_lock) {
330 : : /*
331 : : * Same decision as reprogram_next(). Sloppy idle lets the
332 : : * uptime drift, so an empty list means nothing to wake up for
333 : : * and that is reported as K_TICKS_FOREVER. Otherwise the
334 : : * answer is a wait: either a real deadline, or the synthetic
335 : : * one that keeps the announce range covered.
336 : : */
337 : 0 : if (IS_ENABLED(CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE) &&
338 : : z_timeout_q_next_expiry() == K_TICKS_FOREVER) {
339 : : ret = (uint32_t)K_TICKS_FOREVER;
340 : : } else {
341 : 0 : ret = next_timeout(elapsed());
342 : : }
343 : : }
344 : 0 : return ret;
345 : : }
346 : :
347 : 0 : void sys_clock_announce_locked(uint32_t ticks, k_spinlock_key_t key)
348 : : {
349 : : /* We release the lock around the callbacks below, so on SMP
350 : : * systems someone might be already running the loop. Don't
351 : : * race (which will cause parallel execution of "sequential"
352 : : * timeouts and confuse apps), just increment the tick count
353 : : * and return.
354 : : */
355 : 0 : if (IS_ENABLED(CONFIG_SMP) && any_cpu_announcing()) {
356 : : announce_remaining += ticks;
357 : : k_spin_unlock(&timeout_lock, key);
358 : : return;
359 : : }
360 : :
361 : 0 : announce_remaining = ticks;
362 : 0 : announcing_cpu = CPU_ID;
363 : :
364 : : #ifdef _TIMEOUT_BACKEND_OWNS_ANNOUNCE
365 : : /* The backend (timer wheel) runs the firing loop itself: its per-tick
366 : : * advance is a bitmap jump over empty ticks and its sift is a
367 : : * time-driven event with no single timeout to drive a generic loop.
368 : : * It advances curr_tick / announce_remaining and fires handlers via
369 : : * the same inflight_timeout dance as below.
370 : : */
371 : : key = z_timeout_q_announce(key);
372 : : #else
373 [ # # ]: 0 : while (announce_remaining > 0) {
374 : 0 : struct _timeout *t;
375 : 0 : int32_t dt = z_timeout_q_next_gap();
376 : :
377 [ # # ]: 0 : if ((uint32_t)dt > announce_remaining) {
378 : : /* Next event is past this announce window: advance the
379 : : * backend by the residual ticks without firing anything.
380 : : */
381 : 0 : dt = (int32_t)announce_remaining;
382 : : }
383 : :
384 : : /* Advance curr_tick and decrement announce_remaining together
385 : : * under the lock so non-announcing CPUs observe a consistent
386 : : * (curr_tick + announce_remaining + sys_clock_elapsed()) ==
387 : : * T_real even while we drop the lock around handlers. The "we
388 : : * are announcing" state is carried by announcing_cpu, so
389 : : * announce_remaining reaching 0 mid-loop is harmless: same-tick
390 : : * handlers' z_add_timeout() still anchors via
391 : : * this_cpu_announcing(), and another CPU's announce still folds
392 : : * into ours via any_cpu_announcing() in the SMP early-return.
393 : : */
394 : 0 : z_timeout_q_advance(dt);
395 : 0 : curr_tick += dt;
396 : 0 : announce_remaining -= dt;
397 : :
398 : : /* Drain everything due at the new curr_tick. */
399 [ # # ]: 0 : while ((t = z_timeout_q_pop_due()) != NULL) {
400 : 0 : _timeout_func_t handler = t->fn;
401 : :
402 : 0 : inflight_timeout = t;
403 : :
404 : 0 : k_spin_unlock(&timeout_lock, key);
405 : 0 : handler(t);
406 : 0 : key = k_spin_lock(&timeout_lock);
407 : 0 : inflight_timeout = NULL;
408 : : }
409 : : }
410 : : #endif /* _TIMEOUT_BACKEND_OWNS_ANNOUNCE */
411 : :
412 : 0 : announcing_cpu = -1;
413 : :
414 : 0 : reprogram_next(0);
415 : :
416 : 0 : k_spin_unlock(&timeout_lock, key);
417 : :
418 : : #ifdef CONFIG_TIMESLICING
419 : 0 : z_time_slice();
420 : : #endif /* CONFIG_TIMESLICING */
421 : : }
422 : :
423 : : #if defined(CONFIG_SMP) || defined(CONFIG_SPIN_VALIDATE)
424 : : k_spinlock_key_t sys_clock_lock(void)
425 : : {
426 : : return k_spin_lock(&timeout_lock);
427 : : }
428 : :
429 : : void sys_clock_unlock(k_spinlock_key_t key)
430 : : {
431 : : k_spin_unlock(&timeout_lock, key);
432 : : }
433 : : #endif
434 : :
435 : : #if defined(CONFIG_TEST) || defined(CONFIG_ASSERT)
436 : 250 : bool sys_clock_is_locked(void)
437 : : {
438 : 250 : return z_spin_is_locked(&timeout_lock);
439 : : }
440 : : #endif
441 : :
442 : 0 : int64_t sys_clock_tick_get(void)
443 : : {
444 : 0 : uint64_t t = 0U;
445 : :
446 [ # # ]: 0 : K_SPINLOCK(&timeout_lock) {
447 : 0 : t = curr_tick + elapsed();
448 : : }
449 : 0 : return t;
450 : : }
451 : :
452 : 0 : uint32_t sys_clock_tick_get_32(void)
453 : : {
454 : : #ifdef CONFIG_TICKLESS_KERNEL
455 : 0 : return (uint32_t)sys_clock_tick_get();
456 : : #else
457 : : return (uint32_t)curr_tick;
458 : : #endif /* CONFIG_TICKLESS_KERNEL */
459 : : }
460 : :
461 : 0 : int64_t z_impl_k_uptime_ticks(void)
462 : : {
463 : 0 : return sys_clock_tick_get();
464 : : }
465 : :
466 : : #ifdef CONFIG_USERSPACE
467 : : static inline int64_t z_vrfy_k_uptime_ticks(void)
468 : : {
469 : : return z_impl_k_uptime_ticks();
470 : : }
471 : : #include <zephyr/syscalls/k_uptime_ticks_mrsh.c>
472 : : #endif /* CONFIG_USERSPACE */
473 : :
474 : 0 : k_timepoint_t sys_timepoint_calc(k_timeout_t timeout)
475 : : {
476 : 0 : k_timepoint_t timepoint;
477 : :
478 [ # # ]: 0 : if (K_TIMEOUT_EQ(timeout, K_FOREVER)) {
479 : : timepoint.tick = UINT64_MAX;
480 [ # # ]: 0 : } else if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) {
481 : : timepoint.tick = 0;
482 : : } else {
483 : 0 : k_ticks_t dt = timeout.ticks;
484 : :
485 [ # # ]: 0 : if (Z_IS_TIMEOUT_RELATIVE(timeout)) {
486 : 0 : timepoint.tick = sys_clock_tick_get() + max(1, dt);
487 : : } else {
488 : 0 : timepoint.tick = Z_TICK_ABS(dt);
489 : : }
490 : : }
491 : :
492 : 0 : return timepoint;
493 : : }
494 : :
495 : 0 : k_timeout_t sys_timepoint_timeout(k_timepoint_t timepoint)
496 : : {
497 : 0 : uint64_t now, remaining;
498 : :
499 [ # # ]: 0 : if (timepoint.tick == UINT64_MAX) {
500 : 0 : return K_FOREVER;
501 : : }
502 [ # # ]: 0 : if (timepoint.tick == 0) {
503 : 0 : return K_NO_WAIT;
504 : : }
505 : :
506 : 0 : now = sys_clock_tick_get();
507 [ # # ]: 0 : remaining = (timepoint.tick > now) ? (timepoint.tick - now) : 0;
508 : 0 : return K_TICKS(remaining);
509 : : }
510 : :
511 : : #ifdef CONFIG_ZTEST
512 : 0 : void z_impl_sys_clock_tick_set(uint64_t tick)
513 : : {
514 : 0 : curr_tick = tick;
515 : 0 : }
516 : :
517 : 0 : void z_vrfy_sys_clock_tick_set(uint64_t tick)
518 : : {
519 : 0 : z_impl_sys_clock_tick_set(tick);
520 : 0 : }
521 : : #endif /* CONFIG_ZTEST */
|