1 /*
2  * Copyright (c) 2014-2015 Wind River Systems, Inc.
3  * Copyright (c) 2025 Tenstorrent AI ULC
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 /**
9  * @file
10  * @brief System clock APIs
11  *
12  * Declare variables used by both system timer device driver and kernel
13  * components that use timer functionality.
14  *
15  * APIs for getting, setting, and sleeping with respect to system clocks.
16  */
17 
18 #ifndef ZEPHYR_INCLUDE_SYS_CLOCK_H_
19 #define ZEPHYR_INCLUDE_SYS_CLOCK_H_
20 
21 #include <zephyr/sys/dlist.h>
22 #include <zephyr/sys/time_units.h>
23 #include <zephyr/sys/util.h>
24 #include <zephyr/toolchain.h>
25 #include <zephyr/types.h>
26 
27 #ifdef __cplusplus
28 extern "C" {
29 #endif
30 
31 /**
32  * @addtogroup clock_apis
33  * @{
34  */
35 
36 /**
37  * @brief Tick precision used in timeout APIs
38  *
39  * This type defines the word size of the timeout values used in
40  * k_timeout_t objects, and thus defines an upper bound on maximum
41  * timeout length (or equivalently minimum tick duration).  Note that
42  * this does not affect the size of the system uptime counter, which
43  * is always a 64 bit count of ticks.
44  */
45 #ifdef CONFIG_TIMEOUT_64BIT
46 typedef int64_t k_ticks_t;
47 #else
48 typedef uint32_t k_ticks_t;
49 #endif
50 
51 #define K_TICKS_FOREVER ((k_ticks_t)(-1))
52 
53 /**
54  * @brief Kernel timeout type
55  *
56  * Timeout arguments presented to kernel APIs are stored in this
57  * opaque type, which is capable of representing times in various
58  * formats and units.  It should be constructed from application data
59  * using one of the macros defined for this purpose (e.g. `K_MSEC()`,
60  * `K_TIMEOUT_ABS_TICKS()`, etc...), or be one of the two constants
61  * K_NO_WAIT or K_FOREVER.  Applications should not inspect the
62  * internal data once constructed.  Timeout values may be compared for
63  * equality with the `K_TIMEOUT_EQ()` macro.
64  */
65 typedef struct {
66 	k_ticks_t ticks;
67 } k_timeout_t;
68 
69 /**
70  * @brief Compare timeouts for equality
71  *
72  * The k_timeout_t object is an opaque struct that should not be
73  * inspected by application code.  This macro exists so that users can
74  * test timeout objects for equality with known constants
75  * (e.g. K_NO_WAIT and K_FOREVER) when implementing their own APIs in
76  * terms of Zephyr timeout constants.
77  *
78  * @return True if the timeout objects are identical
79  */
80 #define K_TIMEOUT_EQ(a, b) ((a).ticks == (b).ticks)
81 
82 /** number of nanoseconds per microsecond */
83 #define NSEC_PER_USEC 1000U
84 
85 /** number of nanoseconds per millisecond */
86 #define NSEC_PER_MSEC 1000000U
87 
88 /** number of microseconds per millisecond */
89 #define USEC_PER_MSEC 1000U
90 
91 /** number of milliseconds per second */
92 #define MSEC_PER_SEC 1000U
93 
94 /** number of seconds per minute */
95 #define SEC_PER_MIN 60U
96 
97 /** number of seconds per hour */
98 #define SEC_PER_HOUR 3600U
99 
100 /** number of seconds per day */
101 #define SEC_PER_DAY 86400U
102 
103 /** number of minutes per hour */
104 #define MIN_PER_HOUR 60U
105 
106 /** number of hours per day */
107 #define HOUR_PER_DAY 24U
108 
109 /** number of microseconds per second */
110 #define USEC_PER_SEC ((USEC_PER_MSEC) * (MSEC_PER_SEC))
111 
112 /** number of nanoseconds per second */
113 #define NSEC_PER_SEC ((NSEC_PER_USEC) * (USEC_PER_MSEC) * (MSEC_PER_SEC))
114 
115 /** @} */
116 
117 /** @cond INTERNAL_HIDDEN */
118 #define Z_TIMEOUT_NO_WAIT_INIT {0}
119 #define Z_TIMEOUT_NO_WAIT      ((k_timeout_t)Z_TIMEOUT_NO_WAIT_INIT)
120 #if defined(__cplusplus) && ((__cplusplus - 0) < 202002L)
121 #define Z_TIMEOUT_TICKS_INIT(t) {(t)}
122 #else
123 #define Z_TIMEOUT_TICKS_INIT(t) {.ticks = (t)}
124 #endif
125 #define Z_TIMEOUT_TICKS(t) ((k_timeout_t)Z_TIMEOUT_TICKS_INIT(t))
126 #define Z_FOREVER          Z_TIMEOUT_TICKS(K_TICKS_FOREVER)
127 
128 #ifdef CONFIG_TIMEOUT_64BIT
129 #define Z_TIMEOUT_MS(t)       Z_TIMEOUT_TICKS((k_ticks_t)k_ms_to_ticks_ceil64(MAX(t, 0)))
130 #define Z_TIMEOUT_US(t)       Z_TIMEOUT_TICKS((k_ticks_t)k_us_to_ticks_ceil64(MAX(t, 0)))
131 #define Z_TIMEOUT_NS(t)       Z_TIMEOUT_TICKS((k_ticks_t)k_ns_to_ticks_ceil64(MAX(t, 0)))
132 #define Z_TIMEOUT_CYC(t)      Z_TIMEOUT_TICKS((k_ticks_t)k_cyc_to_ticks_ceil64(MAX(t, 0)))
133 #define Z_TIMEOUT_MS_TICKS(t) ((k_ticks_t)k_ms_to_ticks_ceil64(MAX(t, 0)))
134 #else
135 #define Z_TIMEOUT_MS(t)       Z_TIMEOUT_TICKS((k_ticks_t)k_ms_to_ticks_ceil32(MAX(t, 0)))
136 #define Z_TIMEOUT_US(t)       Z_TIMEOUT_TICKS((k_ticks_t)k_us_to_ticks_ceil32(MAX(t, 0)))
137 #define Z_TIMEOUT_NS(t)       Z_TIMEOUT_TICKS((k_ticks_t)k_ns_to_ticks_ceil32(MAX(t, 0)))
138 #define Z_TIMEOUT_CYC(t)      Z_TIMEOUT_TICKS((k_ticks_t)k_cyc_to_ticks_ceil32(MAX(t, 0)))
139 #define Z_TIMEOUT_MS_TICKS(t) ((k_ticks_t)k_ms_to_ticks_ceil32(MAX(t, 0)))
140 #endif
141 
142 /* Converts between absolute timeout expiration values (packed into
143  * the negative space below K_TICKS_FOREVER) and (non-negative) delta
144  * timeout values.  If the result of Z_TICK_ABS(t) is >= 0, then the
145  * value was an absolute timeout with the returned expiration time.
146  * Note that this macro is bidirectional: Z_TICK_ABS(Z_TICK_ABS(t)) ==
147  * t for all inputs, and that the representation of K_TICKS_FOREVER is
148  * the same value in both spaces!  Clever, huh?
149  */
150 #define Z_TICK_ABS(t) (K_TICKS_FOREVER - 1 - (t))
151 
152 /* Test for relative timeout */
153 #if CONFIG_TIMEOUT_64BIT
154 /* Positive values are relative/delta timeouts and negative values are absolute
155  * timeouts, except -1 which is reserved for K_TIMEOUT_FOREVER. 0 is K_NO_WAIT,
156  * which is historically considered a relative timeout.
157  * K_TIMEOUT_FOREVER is not considered a relative timeout and neither is it
158  * considerd an absolute timeouts (so !Z_IS_TIMEOUT_RELATIVE() does not
159  * necessarily mean it is an absolute timeout if ticks == -1);
160  */
161 #define Z_IS_TIMEOUT_RELATIVE(timeout) (((timeout).ticks) >= 0)
162 #else
163 #define Z_IS_TIMEOUT_RELATIVE(timeout) true
164 #endif
165 
166 /* added tick needed to account for tick in progress */
167 #define _TICK_ALIGN 1
168 
169 /* The minimum duration in ticks strictly greater than that of K_NO_WAIT */
170 #define K_TICK_MIN ((k_ticks_t)1)
171 
172 /* The maximum duration in ticks strictly and semantically "less than" K_FOREVER */
173 #define K_TICK_MAX ((k_ticks_t)(IS_ENABLED(CONFIG_TIMEOUT_64BIT) ? INT64_MAX : UINT32_MAX - 1))
174 
175 /** @endcond */
176 
177 #ifndef CONFIG_TIMER_READS_ITS_FREQUENCY_AT_RUNTIME
178 #if defined(CONFIG_SYS_CLOCK_EXISTS)
179 #if CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC == 0
180 #error "SYS_CLOCK_HW_CYCLES_PER_SEC must be non-zero!"
181 #endif /* CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC == 0 */
182 #endif /* CONFIG_SYS_CLOCK_EXISTS */
183 #endif /* CONFIG_TIMER_READS_ITS_FREQUENCY_AT_RUNTIME */
184 
185 /* kernel clocks */
186 
187 /*
188  * We default to using 64-bit intermediates in timescale conversions,
189  * but if the HW timer cycles/sec, ticks/sec and ms/sec are all known
190  * to be nicely related, then we can cheat with 32 bits instead.
191  */
192 /**
193  * @addtogroup clock_apis
194  * @{
195  */
196 
197 #ifdef CONFIG_SYS_CLOCK_EXISTS
198 
199 #if defined(CONFIG_TIMER_READS_ITS_FREQUENCY_AT_RUNTIME) ||                                        \
200 	(MSEC_PER_SEC % CONFIG_SYS_CLOCK_TICKS_PER_SEC) ||                                         \
201 	(CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC % CONFIG_SYS_CLOCK_TICKS_PER_SEC)
202 #define _NEED_PRECISE_TICK_MS_CONVERSION
203 #endif
204 
205 #endif
206 
207 /**
208  * SYS_CLOCK_HW_CYCLES_TO_NS_AVG converts CPU clock cycles to nanoseconds
209  * and calculates the average cycle time
210  */
211 #define SYS_CLOCK_HW_CYCLES_TO_NS_AVG(X, NCYCLES) (uint32_t)(k_cyc_to_ns_floor64(X) / NCYCLES)
212 
213 /**
214  *
215  * @brief Return the lower part of the current system tick count
216  *
217  * @return the current system tick count
218  *
219  */
220 uint32_t sys_clock_tick_get_32(void);
221 
222 /**
223  *
224  * @brief Return the current system tick count
225  *
226  * @return the current system tick count
227  *
228  */
229 int64_t sys_clock_tick_get(void);
230 
231 #ifndef CONFIG_SYS_CLOCK_EXISTS
232 #define sys_clock_tick_get()    (0)
233 #define sys_clock_tick_get_32() (0)
234 #endif
235 
236 #ifdef CONFIG_SYS_CLOCK_EXISTS
237 
238 /**
239  * @brief Kernel timepoint type
240  *
241  * Absolute timepoints are stored in this opaque type.
242  * It is best not to inspect its content directly.
243  *
244  * @see sys_timepoint_calc()
245  * @see sys_timepoint_timeout()
246  * @see sys_timepoint_expired()
247  */
248 typedef struct {
249 	uint64_t tick;
250 } k_timepoint_t;
251 
252 /**
253  * @brief Calculate a timepoint value
254  *
255  * Returns a timepoint corresponding to the expiration (relative to an
256  * unlocked "now"!) of a timeout object.  When used correctly, this should
257  * be called once, synchronously with the user passing a new timeout value.
258  * It should not be used iteratively to adjust a timeout (see
259  * `sys_timepoint_timeout()` for that purpose).
260  *
261  * @param timeout Timeout value relative to current time (may also be
262  *                `K_FOREVER` or `K_NO_WAIT`).
263  * @return Timepoint value corresponding to given timeout
264  *
265  * @see sys_timepoint_timeout()
266  * @see sys_timepoint_expired()
267  */
268 k_timepoint_t sys_timepoint_calc(k_timeout_t timeout);
269 
270 /**
271  * @brief Remaining time to given timepoint
272  *
273  * Returns the timeout interval between current time and provided timepoint.
274  * If the timepoint is now in the past or if it was created with `K_NO_WAIT`
275  * then `K_NO_WAIT` is returned. If it was created with `K_FOREVER` then
276  * `K_FOREVER` is returned.
277  *
278  * @param timepoint Timepoint for which a timeout value is wanted.
279  * @return Corresponding timeout value.
280  *
281  * @see sys_timepoint_calc()
282  */
283 k_timeout_t sys_timepoint_timeout(k_timepoint_t timepoint);
284 
285 /**
286  * @brief Compare two timepoint values.
287  *
288  * This function is used to compare two timepoint values.
289  *
290  * @param a Timepoint to compare
291  * @param b Timepoint to compare against.
292  * @return zero if both timepoints are the same. Negative value if timepoint @a a is before
293  * timepoint @a b, positive otherwise.
294  */
sys_timepoint_cmp(k_timepoint_t a,k_timepoint_t b)295 static inline int sys_timepoint_cmp(k_timepoint_t a, k_timepoint_t b)
296 {
297 	if (a.tick == b.tick) {
298 		return 0;
299 	}
300 	return a.tick < b.tick ? -1 : 1;
301 }
302 
303 #else
304 
305 /*
306  * When timers are configured out, timepoints can't relate to anything.
307  * The best we can do is to preserve whether or not they are derived from
308  * K_NO_WAIT. Anything else will translate back to K_FOREVER.
309  */
310 typedef struct {
311 	bool wait;
312 } k_timepoint_t;
313 
sys_timepoint_calc(k_timeout_t timeout)314 static inline k_timepoint_t sys_timepoint_calc(k_timeout_t timeout)
315 {
316 	k_timepoint_t timepoint;
317 
318 	timepoint.wait = !K_TIMEOUT_EQ(timeout, Z_TIMEOUT_NO_WAIT);
319 	return timepoint;
320 }
321 
sys_timepoint_timeout(k_timepoint_t timepoint)322 static inline k_timeout_t sys_timepoint_timeout(k_timepoint_t timepoint)
323 {
324 	return timepoint.wait ? Z_FOREVER : Z_TIMEOUT_NO_WAIT;
325 }
326 
sys_timepoint_cmp(k_timepoint_t a,k_timepoint_t b)327 static inline int sys_timepoint_cmp(k_timepoint_t a, k_timepoint_t b)
328 {
329 	if (a.wait == b.wait) {
330 		return 0;
331 	}
332 	return b.wait ? -1 : 1;
333 }
334 
335 #endif
336 
337 /**
338  * @brief Indicates if timepoint is expired
339  *
340  * @param timepoint Timepoint to evaluate
341  * @retval true if the timepoint is in the past, false otherwise
342  *
343  * @see sys_timepoint_calc()
344  */
sys_timepoint_expired(k_timepoint_t timepoint)345 static inline bool sys_timepoint_expired(k_timepoint_t timepoint)
346 {
347 	return K_TIMEOUT_EQ(sys_timepoint_timeout(timepoint), Z_TIMEOUT_NO_WAIT);
348 }
349 
350 /** @} */
351 
352 /**
353  * @addtogroup clock_apis
354  * @{
355  */
356 
357 /**
358  * @brief The real-time clock (i.e. "wall clock")
359  *
360  * This clock is used to measure time since the epoch (1970-01-01 00:00:00 UTC).
361  *
362  * It is not a steady clock; i.e. it may be adjusted for a number of reasons from initialization
363  * of a hardware real-time-clock, to network-time synchronization, to manual adjustment from the
364  * application.
365  */
366 #define SYS_CLOCK_REALTIME 1
367 
368 /**
369  * @brief The monotonic clock
370  *
371  * This steady clock is used to measure time since the system booted. Time from this clock is
372  * always monotonically increasing.
373  */
374 #define SYS_CLOCK_MONOTONIC 4
375 
376 /**
377  * @brief The flag used for specifying absolute timeouts
378  *
379  * This flag may be passed to @ref sys_clock_nanosleep to indicate the requested timeout is an
380  * absolute time with respect to the specified clock.
381  */
382 #define SYS_TIMER_ABSTIME 4
383 
384 /** @cond INTERNAL_HIDDEN */
385 /* forward declaration as workaround for time.h */
386 struct timespec;
387 
388 /* Convert a POSIX clock (cast to int) to a sys_clock identifier */
389 int sys_clock_from_clockid(int clock_id);
390 /** INTERNAL_HIDDEN @endcond */
391 
392 /**
393  * @brief Get the offset @ref SYS_CLOCK_REALTIME with respect to @ref SYS_CLOCK_MONOTONIC
394  *
395  * The "wall clock" (i.e. @ref SYS_CLOCK_REALTIME) depends on a base time that is set by the
396  * system. The base time may be updated for a number of reasons, such as initialization of a
397  * hardware real-time-clock (RTC), network time protocol (NTP) synchronization, or manual
398  * adjustment by the application.
399  *
400  * This function retrieves the current time offset, as a `timespec` object, for
401  * @ref SYS_CLOCK_REALTIME, with respect to @ref SYS_CLOCK_MONOTONIC, and writes it to the
402  * provided memory location pointed-to by @a tp.
403  *
404  * @note This function may assert if @a tp is NULL.
405  *
406  * @param tp Pointer to memory where time will be written.
407  */
408 __syscall void sys_clock_getrtoffset(struct timespec *tp);
409 
410 /**
411  * @brief Get the current time from the specified clock
412  *
413  * @param clock_id The clock from which to query time.
414  * @param tp Pointer to memory where time will be written.
415  * @retval 0 on success.
416  * @retval -EINVAL when an invalid @a clock_id is specified.
417  */
418 int sys_clock_gettime(int clock_id, struct timespec *tp);
419 
420 /**
421  * @brief Set the current time for the specified clock
422  *
423  * @param clock_id The clock for which the time should be set.
424  * @param tp Pointer to memory specifying the desired time.
425  * @retval 0 on success.
426  * @retval -EINVAL when an invalid @a clock_id is specified or when @a tp contains nanoseconds
427  * outside of the range `[0, 999999999]`.
428  */
429 __syscall int sys_clock_settime(int clock_id, const struct timespec *tp);
430 
431 /**
432  * @brief Sleep for the specified amount of time with respect to the specified clock.
433  *
434  * This function will cause the calling thread to sleep either
435  * - until the absolute time specified by @a rqtp (if @a flags includes @ref SYS_TIMER_ABSTIME), or
436  * - until the relative time specified by @a rqtp (if @a flags does not include
437  *   @ref SYS_TIMER_ABSTIME).
438  *
439  * The accepted values for @a clock_id include
440  * - @ref SYS_CLOCK_REALTIME
441  * - @ref SYS_CLOCK_MONOTONIC
442  *
443  * If @a rmtp is not NULL, and the thread is awoken prior to the time specified by @a rqtp, then
444  * any remaining time will be written to @a rmtp. If the thread has slept for at least the time
445  * specified by @a rqtp, then @a rmtp will be set to zero.
446  *
447  * @param clock_id The clock to by which to sleep.
448  * @param flags Flags to modify the behavior of the sleep operation.
449  * @param rqtp Pointer to the requested time to sleep.
450  * @param rmtp Pointer to memory into which to copy the remaining time, if any.
451  *
452  * @retval 0 on success.
453  * @retval -EINVAL when an invalid @a clock_id, when @a rqtp contains nanoseconds outside of the
454  *         range `[0, 999999999]`, or when @a rqtp contains a negative value.
455  */
456 __syscall int sys_clock_nanosleep(int clock_id, int flags, const struct timespec *rqtp,
457 				  struct timespec *rmtp);
458 
459 /**
460  * @}
461  */
462 
463 #ifndef CONFIG_BOARD_UNIT_TESTING
464 #include <zephyr/syscalls/clock.h>
465 #endif
466 
467 #ifdef __cplusplus
468 }
469 #endif
470 
471 #endif /* ZEPHYR_INCLUDE_SYS_CLOCK_H_ */
472