1 /*
2 
3   Copyright (c) 2015 Martin Sustrik
4 
5   Permission is hereby granted, free of charge, to any person obtaining a copy
6   of this software and associated documentation files (the "Software"),
7   to deal in the Software without restriction, including without limitation
8   the rights to use, copy, modify, merge, publish, distribute, sublicense,
9   and/or sell copies of the Software, and to permit persons to whom
10   the Software is furnished to do so, subject to the following conditions:
11 
12   The above copyright notice and this permission notice shall be included
13   in all copies or substantial portions of the Software.
14 
15   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21   IN THE SOFTWARE.
22 
23 */
24 
25 #include <stdint.h>
26 #include <sys/time.h>
27 #include <time.h>
28 
29 #if defined __APPLE__
30 #include <mach/mach_time.h>
31 static mach_timebase_info_data_t mill_mtid = {0};
32 #endif
33 
34 #include "libmill.h"
35 #include "timer.h"
36 #include "utils.h"
37 
38 /* 1 millisecond expressed in CPU ticks. The value is chosen is such a way that
39    it works reasonably well for CPU frequencies above 500MHz. On significanly
40    slower machines you may wish to reconsider. */
41 #define MILL_CLOCK_PRECISION 1000000
42 
43 /* Returns current time by querying the operating system. */
mill_os_time(void)44 static int64_t mill_os_time(void) {
45 #if defined __APPLE__
46     if (mill_slow(!mill_mtid.denom))
47         mach_timebase_info(&mill_mtid);
48     uint64_t ticks = mach_absolute_time();
49     return (int64_t)(ticks * mill_mtid.numer / mill_mtid.denom / 1000000);
50 #elif defined CLOCK_MONOTONIC
51     struct timespec ts;
52     int rc = clock_gettime(CLOCK_MONOTONIC, &ts);
53     mill_assert (rc == 0);
54     return ((int64_t)ts.tv_sec) * 1000 + (((int64_t)ts.tv_nsec) / 1000000);
55 #else
56     struct timeval tv;
57     int rc = gettimeofday(&tv, NULL);
58     assert(rc == 0);
59     return ((int64_t)tv.tv_sec) * 1000 + (((int64_t)tv.tv_usec) / 1000);
60 #endif
61 }
62 
mill_now_(void)63 int64_t mill_now_(void) {
64 #if (defined __GNUC__ || defined __clang__) && \
65       (defined __i386__ || defined __x86_64__)
66     /* Get the timestamp counter. This is time since startup, expressed in CPU
67        cycles. Unlike gettimeofday() or similar function, it's extremely fast -
68        it takes only few CPU cycles to evaluate. */
69     uint32_t low;
70     uint32_t high;
71     __asm__ volatile("rdtsc" : "=a" (low), "=d" (high));
72     int64_t tsc = (int64_t)((uint64_t)high << 32 | low);
73     /* These global variables are used to hold the last seen timestamp counter
74        and last seen time measurement. We'll initilise them the first time
75        this function is called. */
76     static int64_t last_tsc = -1;
77     static int64_t last_now = -1;
78     if(mill_slow(last_tsc < 0)) {
79         last_tsc = tsc;
80         last_now = mill_os_time();
81     }
82     /* If TSC haven't jumped back or progressed more than 1/2 ms, we can use
83        the cached time value. */
84     if(mill_fast(tsc - last_tsc <= (MILL_CLOCK_PRECISION / 2) &&
85           tsc >= last_tsc))
86         return last_now;
87     /* It's more than 1/2 ms since we've last measured the time.
88        We'll do a new measurement now. */
89     last_tsc = tsc;
90     last_now = mill_os_time();
91     return last_now;
92 #else
93     return mill_os_time();
94 #endif
95 }
96 
97 /* Global linked list of all timers. The list is ordered.
98    First timer to be resume comes first and so on. */
99 static struct mill_list mill_timers = {0};
100 
mill_timer_add(struct mill_timer * timer,int64_t deadline,mill_timer_callback callback)101 void mill_timer_add(struct mill_timer *timer, int64_t deadline,
102       mill_timer_callback callback) {
103     mill_assert(deadline >= 0);
104     timer->expiry = deadline;
105     timer->callback = callback;
106     /* Move the timer into the right place in the ordered list
107        of existing timers. TODO: This is an O(n) operation! */
108     struct mill_list_item *it = mill_list_begin(&mill_timers);
109     while(it) {
110         struct mill_timer *tm = mill_cont(it, struct mill_timer, item);
111         /* If multiple timers expire at the same momemt they will be fired
112            in the order they were created in (> rather than >=). */
113         if(tm->expiry > timer->expiry)
114             break;
115         it = mill_list_next(it);
116     }
117     mill_list_insert(&mill_timers, &timer->item, it);
118 }
119 
mill_timer_rm(struct mill_timer * timer)120 void mill_timer_rm(struct mill_timer *timer) {
121     mill_assert(timer->expiry >= 0);
122     mill_list_erase(&mill_timers, &timer->item);
123     timer->expiry = -1;
124 }
125 
mill_timer_next(void)126 int mill_timer_next(void) {
127     if(mill_list_empty(&mill_timers))
128         return -1;
129     int64_t nw = now();
130     int64_t expiry = mill_cont(mill_list_begin(&mill_timers),
131         struct mill_timer, item)->expiry;
132     return (int) (nw >= expiry ? 0 : expiry - nw);
133 }
134 
mill_timer_fire(void)135 int mill_timer_fire(void) {
136     /* Avoid getting current time if there are no timers anyway. */
137     if(mill_list_empty(&mill_timers))
138         return 0;
139     int64_t nw = now();
140     int fired = 0;
141     while(!mill_list_empty(&mill_timers)) {
142         struct mill_timer *tm = mill_cont(
143             mill_list_begin(&mill_timers), struct mill_timer, item);
144         if(tm->expiry > nw)
145             break;
146         mill_list_erase(&mill_timers, mill_list_begin(&mill_timers));
147         tm->expiry = -1;
148         if(tm->callback)
149             tm->callback(tm);
150         fired = 1;
151     }
152     return fired;
153 }
154 
mill_timer_postfork(void)155 void mill_timer_postfork(void) {
156     mill_list_init(&mill_timers);
157 }
158 
159