0001
0002
0003
0004
0005
0006
0007
0008
0009 #include <stddef.h>
0010 #include <unistd.h>
0011 #include <errno.h>
0012 #include <signal.h>
0013 #include <time.h>
0014 #include <sys/time.h>
0015 #include <kern_util.h>
0016 #include <os.h>
0017 #include <string.h>
0018
0019 static timer_t event_high_res_timer = 0;
0020
0021 static inline long long timespec_to_ns(const struct timespec *ts)
0022 {
0023 return ((long long) ts->tv_sec * UM_NSEC_PER_SEC) + ts->tv_nsec;
0024 }
0025
0026 long long os_persistent_clock_emulation(void)
0027 {
0028 struct timespec realtime_tp;
0029
0030 clock_gettime(CLOCK_REALTIME, &realtime_tp);
0031 return timespec_to_ns(&realtime_tp);
0032 }
0033
0034
0035
0036
0037 int os_timer_create(void)
0038 {
0039 timer_t *t = &event_high_res_timer;
0040
0041 if (timer_create(CLOCK_MONOTONIC, NULL, t) == -1)
0042 return -1;
0043
0044 return 0;
0045 }
0046
0047 int os_timer_set_interval(unsigned long long nsecs)
0048 {
0049 struct itimerspec its;
0050
0051 its.it_value.tv_sec = nsecs / UM_NSEC_PER_SEC;
0052 its.it_value.tv_nsec = nsecs % UM_NSEC_PER_SEC;
0053
0054 its.it_interval.tv_sec = nsecs / UM_NSEC_PER_SEC;
0055 its.it_interval.tv_nsec = nsecs % UM_NSEC_PER_SEC;
0056
0057 if (timer_settime(event_high_res_timer, 0, &its, NULL) == -1)
0058 return -errno;
0059
0060 return 0;
0061 }
0062
0063 int os_timer_one_shot(unsigned long long nsecs)
0064 {
0065 struct itimerspec its = {
0066 .it_value.tv_sec = nsecs / UM_NSEC_PER_SEC,
0067 .it_value.tv_nsec = nsecs % UM_NSEC_PER_SEC,
0068
0069 .it_interval.tv_sec = 0,
0070 .it_interval.tv_nsec = 0,
0071 };
0072
0073 timer_settime(event_high_res_timer, 0, &its, NULL);
0074 return 0;
0075 }
0076
0077
0078
0079
0080 void os_timer_disable(void)
0081 {
0082 struct itimerspec its;
0083
0084 memset(&its, 0, sizeof(struct itimerspec));
0085 timer_settime(event_high_res_timer, 0, &its, NULL);
0086 }
0087
0088 long long os_nsecs(void)
0089 {
0090 struct timespec ts;
0091
0092 clock_gettime(CLOCK_MONOTONIC,&ts);
0093 return timespec_to_ns(&ts);
0094 }
0095
0096
0097
0098
0099 void os_idle_sleep(void)
0100 {
0101 struct itimerspec its;
0102 sigset_t set, old;
0103
0104
0105 sigemptyset(&set);
0106 sigaddset(&set, SIGALRM);
0107 sigprocmask(SIG_BLOCK, &set, &old);
0108
0109
0110 timer_gettime(event_high_res_timer, &its);
0111 if (its.it_value.tv_sec || its.it_value.tv_nsec)
0112 sigsuspend(&old);
0113
0114 sigprocmask(SIG_UNBLOCK, &set, NULL);
0115 }