1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2015 Anton Ivanov (aivanov@{brocade.com,kot-begemot.co.uk})
4 * Copyright (C) 2015 Thomas Meyer (thomas@m3y3r.de)
5 * Copyright (C) 2012-2014 Cisco Systems
6 * Copyright (C) 2000 - 2007 Jeff Dike (jdike{addtoit,linux.intel}.com)
15 #include <kern_util.h>
19 static timer_t event_high_res_timer = 0;
21 static inline long long timespec_to_ns(const struct timespec *ts)
23 return ((long long) ts->tv_sec * UM_NSEC_PER_SEC) + ts->tv_nsec;
26 long long os_persistent_clock_emulation(void)
28 struct timespec realtime_tp;
30 clock_gettime(CLOCK_REALTIME, &realtime_tp);
31 return timespec_to_ns(&realtime_tp);
35 * os_timer_create() - create an new posix (interval) timer
37 int os_timer_create(void)
39 timer_t *t = &event_high_res_timer;
41 if (timer_create(CLOCK_MONOTONIC, NULL, t) == -1)
47 int os_timer_set_interval(unsigned long long nsecs)
49 struct itimerspec its;
51 its.it_value.tv_sec = nsecs / UM_NSEC_PER_SEC;
52 its.it_value.tv_nsec = nsecs % UM_NSEC_PER_SEC;
54 its.it_interval.tv_sec = nsecs / UM_NSEC_PER_SEC;
55 its.it_interval.tv_nsec = nsecs % UM_NSEC_PER_SEC;
57 if (timer_settime(event_high_res_timer, 0, &its, NULL) == -1)
63 int os_timer_one_shot(unsigned long long nsecs)
65 struct itimerspec its = {
66 .it_value.tv_sec = nsecs / UM_NSEC_PER_SEC,
67 .it_value.tv_nsec = nsecs % UM_NSEC_PER_SEC,
69 .it_interval.tv_sec = 0,
70 .it_interval.tv_nsec = 0, // we cheat here
73 timer_settime(event_high_res_timer, 0, &its, NULL);
78 * os_timer_disable() - disable the posix (interval) timer
80 void os_timer_disable(void)
82 struct itimerspec its;
84 memset(&its, 0, sizeof(struct itimerspec));
85 timer_settime(event_high_res_timer, 0, &its, NULL);
88 long long os_nsecs(void)
92 clock_gettime(CLOCK_MONOTONIC,&ts);
93 return timespec_to_ns(&ts);
97 * os_idle_sleep() - sleep until interrupted
99 void os_idle_sleep(void)
101 struct itimerspec its;
104 /* block SIGALRM while we analyze the timer state */
106 sigaddset(&set, SIGALRM);
107 sigprocmask(SIG_BLOCK, &set, &old);
109 /* check the timer, and if it'll fire then wait for it */
110 timer_gettime(event_high_res_timer, &its);
111 if (its.it_value.tv_sec || its.it_value.tv_nsec)
113 /* either way, restore the signal mask */
114 sigprocmask(SIG_UNBLOCK, &set, NULL);