cwist
Modern C web framework with libttak runtime
Loading...
Searching...
No Matches
baremetal_time.c
Go to the documentation of this file.
1
17#include <cwist/sys/platform.h>
18
19#if defined(CWIST_BAREMETAL)
20
21#include <cwist/sys/port.h>
22
23#include <errno.h>
24#include <stdint.h>
25#include <sys/time.h>
26#include <time.h>
27
28int clock_gettime(clockid_t id, struct timespec *ts) {
29 if (id == CLOCK_REALTIME) {
30 struct timeval tv;
31 if (gettimeofday(&tv, NULL) != 0) return -1;
32 ts->tv_sec = tv.tv_sec;
33 ts->tv_nsec = (long)tv.tv_usec * 1000L;
34 return 0;
35 }
36 if (id != CLOCK_MONOTONIC) {
37 errno = EINVAL;
38 return -1;
39 }
41 ts->tv_sec = (time_t)(ns / 1000000000u);
42 ts->tv_nsec = (long)(ns % 1000000000u);
43 return 0;
44}
45
46int nanosleep(const struct timespec *req, struct timespec *rem) {
47 if (!req || req->tv_nsec < 0 || req->tv_nsec >= 1000000000L) {
48 errno = EINVAL;
49 return -1;
50 }
51 uint64_t until = cwist_port_monotonic_ns() + (uint64_t)req->tv_sec * 1000000000u +
52 (uint64_t)req->tv_nsec;
53 while (cwist_port_monotonic_ns() < until) {
54 }
55 if (rem) rem->tv_sec = 0, rem->tv_nsec = 0;
56 return 0;
57}
58
59/* Days from 1970-01-01 to y-m-d (proleptic Gregorian), Howard Hinnant's
60 * days_from_civil. */
61time_t timegm(struct tm *tm) {
62 long long y = (long long)tm->tm_year + 1900;
63 int m = tm->tm_mon + 1;
64 y -= m <= 2;
65 long long era = (y >= 0 ? y : y - 399) / 400;
66 unsigned yoe = (unsigned)(y - era * 400);
67 unsigned doy = (153u * (unsigned)(m > 2 ? m - 3 : m + 9) + 2u) / 5u + (unsigned)tm->tm_mday - 1u;
68 unsigned doe = yoe * 365u + yoe / 4u - yoe / 100u + doy;
69 long long days = era * 146097LL + (long long)doe - 719468LL;
70 return (time_t)(days * 86400LL + tm->tm_hour * 3600LL + tm->tm_min * 60LL + tm->tm_sec);
71}
72
73#endif /* CWIST_BAREMETAL */
size_t cap
Definition otel.c:56
Target capability macros shared by all CWIST sources.
Hooks a bare-metal firmware supplies to CWIST (issue #447).
uint64_t cwist_port_monotonic_ns(void)
Monotonic time since an arbitrary epoch (usually boot).