xref: /openbsd/usr.sbin/ntpd/util.c (revision 3d8817e4)
1 /*	$OpenBSD: util.c,v 1.13 2007/03/27 18:22:02 otto Exp $ */
2 
3 /*
4  * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/time.h>
20 #include <limits.h>
21 
22 #include "ntpd.h"
23 
24 double
25 gettime_corrected(void)
26 {
27 	return (gettime() + getoffset());
28 }
29 
30 double
31 getoffset(void)
32 {
33 	struct timeval	tv;
34 	if (adjtime(NULL, &tv) == -1)
35 		return (0.0);
36 	return (tv.tv_sec + 1.0e-6 * tv.tv_usec);
37 }
38 
39 double
40 gettime(void)
41 {
42 	struct timeval	tv;
43 
44 	if (gettimeofday(&tv, NULL) == -1)
45 		fatal("gettimeofday");
46 
47 	return (tv.tv_sec + JAN_1970 + 1.0e-6 * tv.tv_usec);
48 }
49 
50 time_t
51 getmonotime(void)
52 {
53 	struct timespec	ts;
54 
55 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
56 		fatal("clock_gettime");
57 
58 	return (ts.tv_sec);
59 }
60 
61 
62 void
63 d_to_tv(double d, struct timeval *tv)
64 {
65 	tv->tv_sec = (long)d;
66 	tv->tv_usec = (d - tv->tv_sec) * 1000000;
67 	while (tv->tv_usec < 0) {
68 		tv->tv_usec += 1000000;
69 		tv->tv_sec -= 1;
70 	}
71 }
72 
73 double
74 lfp_to_d(struct l_fixedpt lfp)
75 {
76 	double	ret;
77 
78 	lfp.int_partl = ntohl(lfp.int_partl);
79 	lfp.fractionl = ntohl(lfp.fractionl);
80 
81 	ret = (double)(lfp.int_partl) + ((double)lfp.fractionl / UINT_MAX);
82 
83 	return (ret);
84 }
85 
86 struct l_fixedpt
87 d_to_lfp(double d)
88 {
89 	struct l_fixedpt	lfp;
90 
91 	lfp.int_partl = htonl((u_int32_t)d);
92 	lfp.fractionl = htonl((u_int32_t)((d - (u_int32_t)d) * UINT_MAX));
93 
94 	return (lfp);
95 }
96 
97 double
98 sfp_to_d(struct s_fixedpt sfp)
99 {
100 	double	ret;
101 
102 	sfp.int_parts = ntohs(sfp.int_parts);
103 	sfp.fractions = ntohs(sfp.fractions);
104 
105 	ret = (double)(sfp.int_parts) + ((double)sfp.fractions / USHRT_MAX);
106 
107 	return (ret);
108 }
109 
110 struct s_fixedpt
111 d_to_sfp(double d)
112 {
113 	struct s_fixedpt	sfp;
114 
115 	sfp.int_parts = htons((u_int16_t)d);
116 	sfp.fractions = htons((u_int16_t)((d - (u_int16_t)d) * USHRT_MAX));
117 
118 	return (sfp);
119 }
120