xref: /netbsd-src/external/bsd/ntp/dist/sntp/libevent/evutil_time.c (revision 413d532bcc3f62d122e56d92e13ac64825a40baf)
1 /*	$NetBSD: evutil_time.c,v 1.1.1.1 2013/12/27 23:31:15 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include "event2/event-config.h"
30 #include "evconfig-private.h"
31 
32 #ifdef _WIN32
33 #include <winsock2.h>
34 #define WIN32_LEAN_AND_MEAN
35 #include <windows.h>
36 #undef WIN32_LEAN_AND_MEAN
37 #endif
38 
39 #include <sys/types.h>
40 #ifdef EVENT__HAVE_STDLIB_H
41 #include <stdlib.h>
42 #endif
43 #include <errno.h>
44 #include <limits.h>
45 #ifndef EVENT__HAVE_GETTIMEOFDAY
46 #include <sys/timeb.h>
47 #endif
48 #if !defined(EVENT__HAVE_NANOSLEEP) && !defined(EVENT_HAVE_USLEEP) && \
49 	!defined(_WIN32)
50 #include <sys/select.h>
51 #endif
52 #include <time.h>
53 #include <sys/stat.h>
54 #include <string.h>
55 
56 #include "event2/util.h"
57 #include "util-internal.h"
58 #include "log-internal.h"
59 
60 #ifndef EVENT__HAVE_GETTIMEOFDAY
61 /* No gettimeofday; this must be windows. */
62 int
63 evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
64 {
65 #ifdef _MSC_VER
66 #define U64_LITERAL(n) n##ui64
67 #else
68 #define U64_LITERAL(n) n##llu
69 #endif
70 
71 	/* Conversion logic taken from Tor, which in turn took it
72 	 * from Perl.  GetSystemTimeAsFileTime returns its value as
73 	 * an unaligned (!) 64-bit value containing the number of
74 	 * 100-nanosecond intervals since 1 January 1601 UTC. */
75 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
76 #define UNITS_PER_SEC U64_LITERAL(10000000)
77 #define USEC_PER_SEC U64_LITERAL(1000000)
78 #define UNITS_PER_USEC U64_LITERAL(10)
79 	union {
80 		FILETIME ft_ft;
81 		ev_uint64_t ft_64;
82 	} ft;
83 
84 	if (tv == NULL)
85 		return -1;
86 
87 	GetSystemTimeAsFileTime(&ft.ft_ft);
88 
89 	if (EVUTIL_UNLIKELY(ft.ft_64 < EPOCH_BIAS)) {
90 		/* Time before the unix epoch. */
91 		return -1;
92 	}
93 	ft.ft_64 -= EPOCH_BIAS;
94 	tv->tv_sec = (long) (ft.ft_64 / UNITS_PER_SEC);
95 	tv->tv_usec = (long) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
96 	return 0;
97 }
98 #endif
99 
100 #define MAX_SECONDS_IN_MSEC_LONG \
101 	(((LONG_MAX) - 999) / 1000)
102 
103 long
104 evutil_tv_to_msec_(const struct timeval *tv)
105 {
106 	if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
107 		return -1;
108 
109 	return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
110 }
111 
112 /*
113   Replacement for usleep on platforms that don't have one.  Not guaranteed to
114   be any more finegrained than 1 msec.
115  */
116 void
117 evutil_usleep_(const struct timeval *tv)
118 {
119 	if (!tv)
120 		return;
121 #if defined(_WIN32)
122 	{
123 		long msec = evutil_tv_to_msec_(tv);
124 		Sleep((DWORD)msec);
125 	}
126 #elif defined(EVENT__HAVE_NANOSLEEP)
127 	{
128 		struct timespec ts;
129 		ts.tv_sec = tv->tv_sec;
130 		ts.tv_nsec = tv->tv_usec*1000;
131 		nanosleep(&ts, NULL);
132 	}
133 #elif defined(EVENT__HAVE_USLEEP)
134 	/* Some systems don't like to usleep more than 999999 usec */
135 	sleep(tv->tv_sec);
136 	usleep(tv->tv_usec);
137 #else
138 	select(0, NULL, NULL, NULL, tv);
139 #endif
140 }
141 
142 /*
143    This function assumes it's called repeatedly with a
144    not-actually-so-monotonic time source whose outputs are in 'tv'. It
145    implements a trivial ratcheting mechanism so that the values never go
146    backwards.
147  */
148 static void
149 adjust_monotonic_time(struct evutil_monotonic_timer *base,
150     struct timeval *tv)
151 {
152 	evutil_timeradd(tv, &base->adjust_monotonic_clock, tv);
153 
154 	if (evutil_timercmp(tv, &base->last_time, <)) {
155 		/* Guess it wasn't monotonic after all. */
156 		struct timeval adjust;
157 		evutil_timersub(&base->last_time, tv, &adjust);
158 		evutil_timeradd(&adjust, &base->adjust_monotonic_clock,
159 		    &base->adjust_monotonic_clock);
160 		*tv = base->last_time;
161 	}
162 	base->last_time = *tv;
163 }
164 
165 #if defined(HAVE_POSIX_MONOTONIC)
166 /* =====
167    The POSIX clock_gettime() interface provides a few ways to get at a
168    monotonic clock.  CLOCK_MONOTONIC is most widely supported.  Linux also
169    provides a CLOCK_MONOTONIC_COARSE with accuracy of about 1-4 msec.
170 
171    On all platforms I'm aware of, CLOCK_MONOTONIC really is monotonic.
172    Platforms don't agree about whether it should jump on a sleep/resume.
173  */
174 
175 int
176 evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
177     int flags)
178 {
179 	/* CLOCK_MONOTONIC exists on FreeBSD, Linux, and Solaris.  You need to
180 	 * check for it at runtime, because some older kernel versions won't
181 	 * have it working. */
182 #ifdef CLOCK_MONOTONIC_COARSE
183 	const int precise = flags & EV_MONOT_PRECISE;
184 #endif
185 	const int fallback = flags & EV_MONOT_FALLBACK;
186 	struct timespec	ts;
187 
188 #ifdef CLOCK_MONOTONIC_COARSE
189 	if (! precise && ! fallback) {
190 		if (clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) == 0) {
191 			base->monotonic_clock = CLOCK_MONOTONIC_COARSE;
192 			return 0;
193 		}
194 	}
195 #endif
196 	if (!fallback && clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
197 		base->monotonic_clock = CLOCK_MONOTONIC;
198 		return 0;
199 	}
200 
201 	base->monotonic_clock = -1;
202 	return 0;
203 }
204 
205 int
206 evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
207     struct timeval *tp)
208 {
209 	struct timespec ts;
210 
211 	if (base->monotonic_clock < 0) {
212 		if (evutil_gettimeofday(tp, NULL) < 0)
213 			return -1;
214 		adjust_monotonic_time(base, tp);
215 		return 0;
216 	}
217 
218 	if (clock_gettime(base->monotonic_clock, &ts) == -1)
219 		return -1;
220 	tp->tv_sec = ts.tv_sec;
221 	tp->tv_usec = ts.tv_nsec / 1000;
222 
223 	return 0;
224 }
225 #endif
226 
227 #if defined(HAVE_MACH_MONOTONIC)
228 /* ======
229    Apple is a little late to the POSIX party.  And why not?  Instead of
230    clock_gettime(), they provide mach_absolute_time().  Its units are not
231    fixed; we need to use mach_timebase_info() to get the right functions to
232    convert its units into nanoseconds.
233 
234    To all appearances, mach_absolute_time() seems to be honest-to-goodness
235    monotonic.  Whether it stops during sleep or not is unspecified in
236    principle, and dependent on CPU architecture in practice.
237  */
238 
239 int
240 evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
241     int flags)
242 {
243 	const int fallback = flags & EV_MONOT_FALLBACK;
244 	struct mach_timebase_info mi;
245 	memset(base, 0, sizeof(*base));
246 	/* OSX has mach_absolute_time() */
247 	if (!fallback &&
248 	    mach_timebase_info(&mi) == 0 &&
249 	    mach_absolute_time() != 0) {
250 		/* mach_timebase_info tells us how to convert
251 		 * mach_absolute_time() into nanoseconds, but we
252 		 * want to use microseconds instead. */
253 		mi.denom *= 1000;
254 		memcpy(&base->mach_timebase_units, &mi, sizeof(mi));
255 	} else {
256 		base->mach_timebase_units.numer = 0;
257 	}
258 	return 0;
259 }
260 
261 int
262 evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
263     struct timeval *tp)
264 {
265 	ev_uint64_t abstime, usec;
266 	if (base->mach_timebase_units.numer == 0) {
267 		if (evutil_gettimeofday(tp, NULL) < 0)
268 			return -1;
269 		adjust_monotonic_time(base, tp);
270 		return 0;
271 	}
272 
273 	abstime = mach_absolute_time();
274 	usec = (abstime * base->mach_timebase_units.numer)
275 	    / (base->mach_timebase_units.denom);
276 	tp->tv_sec = usec / 1000000;
277 	tp->tv_usec = usec % 1000000;
278 
279 	return 0;
280 }
281 #endif
282 
283 #if defined(HAVE_WIN32_MONOTONIC)
284 /* =====
285    Turn we now to Windows.  Want monontonic time on Windows?
286 
287    Windows has QueryPerformanceCounter(), which gives time most high-
288    resolution time.  It's a pity it's not so monotonic in practice; it's
289    also got some fun bugs, especially: with older Windowses, under
290    virtualizations, with funny hardware, on multiprocessor systems, and so
291    on.  PEP418 [1] has a nice roundup of the issues here.
292 
293    There's GetTickCount64() on Vista and later, which gives a number of 1-msec
294    ticks since startup.  The accuracy here might be as bad as 10-20 msec, I
295    hear.  There's an undocumented function (NtSetTimerResolution) that
296    allegedly increases the accuracy. Good luck!
297 
298    There's also GetTickCount(), which is only 32 bits, but seems to be
299    supported on pre-Vista versions of Windows.  Apparently, you can coax
300    another 14 bits out of it, giving you 2231 years before rollover.
301 
302    The less said about timeGetTime() the better.
303 
304    "We don't care.  We don't have to.  We're the Phone Company."
305             -- Lily Tomlin, SNL
306 
307    Our strategy, if precise timers are turned off, is to just use the best
308    GetTickCount equivalent available.  If we've been asked for precise timing,
309    then we mostly[2] assume that GetTickCount is monotonic, and correct
310    GetPerformanceCounter to approximate it.
311 
312    [1] http://www.python.org/dev/peps/pep-0418
313    [2] Of course, we feed the Windows stuff into adjust_monotonic_time()
314        anyway, just in case it isn't.
315 
316  */
317 /*
318     Parts of our logic in the win32 timer code here are closely based on
319     BitTorrent's libUTP library.  That code is subject to the following
320     license:
321 
322       Copyright (c) 2010 BitTorrent, Inc.
323 
324       Permission is hereby granted, free of charge, to any person obtaining a
325       copy of this software and associated documentation files (the
326       "Software"), to deal in the Software without restriction, including
327       without limitation the rights to use, copy, modify, merge, publish,
328       distribute, sublicense, and/or sell copies of the Software, and to
329       permit persons to whom the Software is furnished to do so, subject to
330       the following conditions:
331 
332       The above copyright notice and this permission notice shall be included
333       in all copies or substantial portions of the Software.
334 
335       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
336       OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
337       MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
338       NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
339       LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
340       OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
341       WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
342 */
343 
344 static ev_uint64_t
345 evutil_GetTickCount_(struct evutil_monotonic_timer *base)
346 {
347 	if (base->GetTickCount64_fn) {
348 		/* Let's just use GetTickCount64 if we can. */
349 		return base->GetTickCount64_fn();
350 	} else if (base->GetTickCount_fn) {
351 		/* Greg Hazel assures me that this works, that BitTorrent has
352 		 * done it for years, and this it won't turn around and
353 		 * bite us.  He says they found it on some game programmers'
354 		 * forum some time around 2007.
355 		 */
356 		ev_uint64_t v = base->GetTickCount_fn();
357 		return (DWORD)v | ((v >> 18) & 0xFFFFFFFF00000000);
358 	} else {
359 		/* Here's the fallback implementation. We have to use
360 		 * GetTickCount() with its given signature, so we only get
361 		 * 32 bits worth of milliseconds, which will roll ove every
362 		 * 49 days or so.  */
363 		DWORD ticks = GetTickCount();
364 		if (ticks < base->last_tick_count) {
365 			base->adjust_tick_count += ((ev_uint64_t)1) << 32;
366 		}
367 		base->last_tick_count = ticks;
368 		return ticks + base->adjust_tick_count;
369 	}
370 }
371 
372 int
373 evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
374     int flags)
375 {
376 	const int precise = flags & EV_MONOT_PRECISE;
377 	const int fallback = flags & EV_MONOT_FALLBACK;
378 	HANDLE h;
379 	memset(base, 0, sizeof(*base));
380 
381 	h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
382 	if (h != NULL && !fallback) {
383 		base->GetTickCount64_fn = (ev_GetTickCount_func)GetProcAddress(h, "GetTickCount64");
384 		base->GetTickCount_fn = (ev_GetTickCount_func)GetProcAddress(h, "GetTickCount");
385 	}
386 
387 	base->first_tick = base->last_tick_count = evutil_GetTickCount_(base);
388 	if (precise && !fallback) {
389 		LARGE_INTEGER freq;
390 		if (QueryPerformanceFrequency(&freq)) {
391 			LARGE_INTEGER counter;
392 			QueryPerformanceCounter(&counter);
393 			base->first_counter = counter.QuadPart;
394 			base->usec_per_count = 1.0e6 / freq.QuadPart;
395 			base->use_performance_counter = 1;
396 		}
397 	}
398 
399 	return 0;
400 }
401 
402 static inline ev_int64_t
403 abs64(ev_int64_t i)
404 {
405 	return i < 0 ? -i : i;
406 }
407 
408 
409 int
410 evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
411     struct timeval *tp)
412 {
413 	ev_uint64_t ticks = evutil_GetTickCount_(base);
414 	if (base->use_performance_counter) {
415 		/* Here's a trick we took from BitTorrent's libutp, at Greg
416 		 * Hazel's recommendation.  We use QueryPerformanceCounter for
417 		 * our high-resolution timer, but use GetTickCount*() to keep
418 		 * it sane, and adjust_monotonic_time() to keep it monotonic.
419 		 */
420 		LARGE_INTEGER counter;
421 		ev_int64_t counter_elapsed, counter_usec_elapsed, ticks_elapsed;
422 		QueryPerformanceCounter(&counter);
423 		counter_elapsed = (ev_int64_t)
424 		    (counter.QuadPart - base->first_counter);
425 		ticks_elapsed = ticks - base->first_tick;
426 		/* TODO: This may upset VC6. If you need this to work with
427 		 * VC6, please supply an appropriate patch. */
428 		counter_usec_elapsed = (ev_int64_t)
429 		    (counter_elapsed * base->usec_per_count);
430 
431 		if (abs64(ticks_elapsed*1000 - counter_usec_elapsed) > 1000000) {
432 			/* It appears that the QueryPerformanceCounter()
433 			 * result is more than 1 second away from
434 			 * GetTickCount() result. Let's adjust it to be as
435 			 * accurate as we can; adjust_monotnonic_time() below
436 			 * will keep it monotonic. */
437 			counter_usec_elapsed = ticks_elapsed * 1000;
438 			base->first_counter = counter.QuadPart - counter_usec_elapsed / base->usec_per_count;
439 		}
440 		tp->tv_sec = counter_usec_elapsed / 1000000;
441 		tp->tv_usec = counter_usec_elapsed % 1000000;
442 
443 	} else {
444 		/* We're just using GetTickCount(). */
445 		tp->tv_sec = ticks / 1000;
446 		tp->tv_usec = (ticks % 1000) * 1000;
447 	}
448 	adjust_monotonic_time(base, tp);
449 
450 	return 0;
451 }
452 #endif
453 
454 #if defined(HAVE_FALLBACK_MONOTONIC)
455 /* =====
456    And if none of the other options work, let's just use gettimeofday(), and
457    ratchet it forward so that it acts like a monotonic timer, whether it
458    wants to or not.
459  */
460 
461 int
462 evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
463     int precise)
464 {
465 	memset(base, 0, sizeof(*base));
466 	return 0;
467 }
468 
469 int
470 evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
471     struct timeval *tp)
472 {
473 	if (evutil_gettimeofday(tp, NULL) < 0)
474 		return -1;
475 	adjust_monotonic_time(base, tp);
476 	return 0;
477 
478 }
479 #endif
480