1 /*
2  * Time calculation functions.
3  *
4  * Copyright 2000-2011 Willy Tarreau <w@1wt.eu>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  *
11  */
12 
13 #include <unistd.h>
14 #include <sys/time.h>
15 
16 #include <haproxy/api.h>
17 #include <haproxy/time.h>
18 #include <haproxy/ticks.h>
19 #include <haproxy/tools.h>
20 
21 THREAD_LOCAL unsigned int   ms_left_scaled;  /* milliseconds left for current second (0..2^32-1) */
22 THREAD_LOCAL unsigned int   now_ms;          /* internal date in milliseconds (may wrap) */
23 THREAD_LOCAL unsigned int   samp_time;       /* total elapsed time over current sample */
24 THREAD_LOCAL unsigned int   idle_time;       /* total idle time over current sample */
25 THREAD_LOCAL struct timeval now;             /* internal date is a monotonic function of real clock */
26 THREAD_LOCAL struct timeval date;            /* the real current date */
27 struct timeval start_date;      /* the process's start date */
28 THREAD_LOCAL struct timeval before_poll;     /* system date before calling poll() */
29 THREAD_LOCAL struct timeval after_poll;      /* system date after leaving poll() */
30 
31 static THREAD_LOCAL struct timeval tv_offset;  /* per-thread time ofsset relative to global time */
32 volatile unsigned long long global_now;      /* common date between all threads (32:32) */
33 volatile unsigned int global_now_ms;         /* common date in milliseconds (may wrap) */
34 
35 static THREAD_LOCAL unsigned int iso_time_sec;     /* last iso time value for this thread */
36 static THREAD_LOCAL char         iso_time_str[34]; /* ISO time representation of gettimeofday() */
37 
38 /*
39  * adds <ms> ms to <from>, set the result to <tv> and returns a pointer <tv>
40  */
_tv_ms_add(struct timeval * tv,const struct timeval * from,int ms)41 struct timeval *_tv_ms_add(struct timeval *tv, const struct timeval *from, int ms)
42 {
43 	tv->tv_usec = from->tv_usec + (ms % 1000) * 1000;
44 	tv->tv_sec  = from->tv_sec  + (ms / 1000);
45 	while (tv->tv_usec >= 1000000) {
46 		tv->tv_usec -= 1000000;
47 		tv->tv_sec++;
48 	}
49 	return tv;
50 }
51 
52 /*
53  * compares <tv1> and <tv2> modulo 1ms: returns 0 if equal, -1 if tv1 < tv2, 1 if tv1 > tv2
54  * Must not be used when either argument is eternity. Use tv_ms_cmp2() for that.
55  */
_tv_ms_cmp(const struct timeval * tv1,const struct timeval * tv2)56 int _tv_ms_cmp(const struct timeval *tv1, const struct timeval *tv2)
57 {
58 	return __tv_ms_cmp(tv1, tv2);
59 }
60 
61 /*
62  * compares <tv1> and <tv2> modulo 1 ms: returns 0 if equal, -1 if tv1 < tv2, 1 if tv1 > tv2,
63  * assuming that TV_ETERNITY is greater than everything.
64  */
_tv_ms_cmp2(const struct timeval * tv1,const struct timeval * tv2)65 int _tv_ms_cmp2(const struct timeval *tv1, const struct timeval *tv2)
66 {
67 	return __tv_ms_cmp2(tv1, tv2);
68 }
69 
70 /*
71  * compares <tv1> and <tv2> modulo 1 ms: returns 1 if tv1 <= tv2, 0 if tv1 > tv2,
72  * assuming that TV_ETERNITY is greater than everything. Returns 0 if tv1 is
73  * TV_ETERNITY, and always assumes that tv2 != TV_ETERNITY. Designed to replace
74  * occurrences of (tv_ms_cmp2(tv,now) <= 0).
75  */
_tv_ms_le2(const struct timeval * tv1,const struct timeval * tv2)76 int _tv_ms_le2(const struct timeval *tv1, const struct timeval *tv2)
77 {
78 	return __tv_ms_le2(tv1, tv2);
79 }
80 
81 /*
82  * returns the remaining time between tv1=now and event=tv2
83  * if tv2 is passed, 0 is returned.
84  * Must not be used when either argument is eternity.
85  */
_tv_ms_remain(const struct timeval * tv1,const struct timeval * tv2)86 unsigned long _tv_ms_remain(const struct timeval *tv1, const struct timeval *tv2)
87 {
88 	return __tv_ms_remain(tv1, tv2);
89 }
90 
91 /*
92  * returns the remaining time between tv1=now and event=tv2
93  * if tv2 is passed, 0 is returned.
94  * Returns TIME_ETERNITY if tv2 is eternity.
95  */
_tv_ms_remain2(const struct timeval * tv1,const struct timeval * tv2)96 unsigned long _tv_ms_remain2(const struct timeval *tv1, const struct timeval *tv2)
97 {
98 	if (tv_iseternity(tv2))
99 		return TIME_ETERNITY;
100 
101 	return __tv_ms_remain(tv1, tv2);
102 }
103 
104 /*
105  * Returns the time in ms elapsed between tv1 and tv2, assuming that tv1<=tv2.
106  * Must not be used when either argument is eternity.
107  */
_tv_ms_elapsed(const struct timeval * tv1,const struct timeval * tv2)108 unsigned long _tv_ms_elapsed(const struct timeval *tv1, const struct timeval *tv2)
109 {
110 	return __tv_ms_elapsed(tv1, tv2);
111 }
112 
113 /*
114  * adds <inc> to <from>, set the result to <tv> and returns a pointer <tv>
115  */
_tv_add(struct timeval * tv,const struct timeval * from,const struct timeval * inc)116 struct timeval *_tv_add(struct timeval *tv, const struct timeval *from, const struct timeval *inc)
117 {
118 	return __tv_add(tv, from, inc);
119 }
120 
121 /*
122  * If <inc> is set, then add it to <from> and set the result to <tv>, then
123  * return 1, otherwise return 0. It is meant to be used in if conditions.
124  */
_tv_add_ifset(struct timeval * tv,const struct timeval * from,const struct timeval * inc)125 int _tv_add_ifset(struct timeval *tv, const struct timeval *from, const struct timeval *inc)
126 {
127 	return __tv_add_ifset(tv, from, inc);
128 }
129 
130 /*
131  * Computes the remaining time between tv1=now and event=tv2. if tv2 is passed,
132  * 0 is returned. The result is stored into tv.
133  */
_tv_remain(const struct timeval * tv1,const struct timeval * tv2,struct timeval * tv)134 struct timeval *_tv_remain(const struct timeval *tv1, const struct timeval *tv2, struct timeval *tv)
135 {
136 	return __tv_remain(tv1, tv2, tv);
137 }
138 
139 /*
140  * Computes the remaining time between tv1=now and event=tv2. if tv2 is passed,
141  * 0 is returned. The result is stored into tv. Returns ETERNITY if tv2 is
142  * eternity.
143  */
_tv_remain2(const struct timeval * tv1,const struct timeval * tv2,struct timeval * tv)144 struct timeval *_tv_remain2(const struct timeval *tv1, const struct timeval *tv2, struct timeval *tv)
145 {
146 	return __tv_remain2(tv1, tv2, tv);
147 }
148 
149 /* tv_isle: compares <tv1> and <tv2> : returns 1 if tv1 <= tv2, otherwise 0 */
_tv_isle(const struct timeval * tv1,const struct timeval * tv2)150 int _tv_isle(const struct timeval *tv1, const struct timeval *tv2)
151 {
152 	return __tv_isle(tv1, tv2);
153 }
154 
155 /* tv_isgt: compares <tv1> and <tv2> : returns 1 if tv1 > tv2, otherwise 0 */
_tv_isgt(const struct timeval * tv1,const struct timeval * tv2)156 int _tv_isgt(const struct timeval *tv1, const struct timeval *tv2)
157 {
158 	return __tv_isgt(tv1, tv2);
159 }
160 
161 /* tv_update_date: sets <date> to system time, and sets <now> to something as
162  * close as possible to real time, following a monotonic function. The main
163  * principle consists in detecting backwards and forwards time jumps and adjust
164  * an offset to correct them. This function should be called once after each
165  * poll, and never farther apart than MAX_DELAY_MS*2. The poll's timeout should
166  * be passed in <max_wait>, and the return value in <interrupted> (a non-zero
167  * value means that we have not expired the timeout). Calling it with (-1,*)
168  * sets both <date> and <now> to current date, and calling it with (0,1) simply
169  * updates the values.
170  *
171  * An offset is used to adjust the current time (date), to have a monotonic time
172  * (now). It must be global and thread-safe. But a timeval cannot be atomically
173  * updated. So instead, we store it in a 64-bits integer (offset) whose 32 MSB
174  * contain the signed seconds adjustment and the 32 LSB contain the unsigned
175  * microsecond adjustment. We cannot use a timeval for this since it's never
176  * clearly specified whether a timeval may hold negative values or not.
177  */
tv_update_date(int max_wait,int interrupted)178 void tv_update_date(int max_wait, int interrupted)
179 {
180 	struct timeval adjusted, deadline, tmp_now, tmp_adj;
181 	unsigned int   curr_sec_ms;     /* millisecond of current second (0..999) */
182 	unsigned int old_now_ms, new_now_ms;
183 	unsigned long long old_now;
184 	unsigned long long new_now;
185 
186 	gettimeofday(&date, NULL);
187 	if (unlikely(max_wait < 0)) {
188 		tv_zero(&tv_offset);
189 		adjusted = date;
190 		after_poll = date;
191 		samp_time = idle_time = 0;
192 		ti->idle_pct = 100;
193 		old_now = global_now;
194 		if (!old_now) { // never set
195 			new_now = (((unsigned long long)adjusted.tv_sec) << 32) + (unsigned int)adjusted.tv_usec;
196 			_HA_ATOMIC_CAS(&global_now, &old_now, new_now);
197 		}
198 		goto to_ms;
199 	}
200 
201 	__tv_add(&adjusted, &date, &tv_offset);
202 
203 	/* compute the minimum and maximum local date we may have reached based
204 	 * on our past date and the associated timeout.
205 	 */
206 	_tv_ms_add(&deadline, &now, max_wait + MAX_DELAY_MS);
207 
208 	if (unlikely(__tv_islt(&adjusted, &now) || __tv_islt(&deadline, &adjusted))) {
209 		/* Large jump. If the poll was interrupted, we consider that the
210 		 * date has not changed (immediate wake-up), otherwise we add
211 		 * the poll time-out to the previous date. The new offset is
212 		 * recomputed.
213 		 */
214 		_tv_ms_add(&adjusted, &now, interrupted ? 0 : max_wait);
215 	}
216 
217 	/* now that we have bounded the local time, let's check if it's
218 	 * realistic regarding the global date, which only moves forward,
219 	 * otherwise catch up.
220 	 */
221 	old_now = global_now;
222 
223 	do {
224 		tmp_now.tv_sec  = (unsigned int)(old_now >> 32);
225 		tmp_now.tv_usec = old_now & 0xFFFFFFFFU;
226 		tmp_adj = adjusted;
227 
228 		if (__tv_islt(&tmp_adj, &tmp_now))
229 			tmp_adj = tmp_now;
230 
231 		/* now <adjusted> is expected to be the most accurate date,
232 		 * equal to <global_now> or newer.
233 		 */
234 		new_now = (((unsigned long long)tmp_adj.tv_sec) << 32) + (unsigned int)tmp_adj.tv_usec;
235 
236 		/* let's try to update the global <now> or loop again */
237 	} while (!_HA_ATOMIC_CAS(&global_now, &old_now, new_now));
238 
239 	adjusted = tmp_adj;
240 
241 	/* the new global date when we looked was old_now, and the new one is
242 	 * new_now == adjusted. We can recompute our local offset.
243 	 */
244 	tv_offset.tv_sec  = adjusted.tv_sec  - date.tv_sec;
245 	tv_offset.tv_usec = adjusted.tv_usec - date.tv_usec;
246 	if (tv_offset.tv_usec < 0) {
247 		tv_offset.tv_usec += 1000000;
248 		tv_offset.tv_sec--;
249 	}
250 
251  to_ms:
252 	now = adjusted;
253 	curr_sec_ms = now.tv_usec / 1000;            /* ms of current second */
254 
255 	/* For frequency counters, we'll need to know the ratio of the previous
256 	 * value to add to current value depending on the current millisecond.
257 	 * The principle is that during the first millisecond, we use 999/1000
258 	 * of the past value and that during the last millisecond we use 0/1000
259 	 * of the past value. In summary, we only use the past value during the
260 	 * first 999 ms of a second, and the last ms is used to complete the
261 	 * current measure. The value is scaled to (2^32-1) so that a simple
262 	 * multiply followed by a shift gives us the final value.
263 	 */
264 	ms_left_scaled = (999U - curr_sec_ms) * 4294967U;
265 	now_ms = now.tv_sec * 1000 + curr_sec_ms;
266 
267 	/* update the global current millisecond */
268 	old_now_ms = global_now_ms;
269 	do {
270 		new_now_ms = old_now_ms;
271 		if (tick_is_lt(new_now_ms, now_ms) || !new_now_ms)
272 			new_now_ms = now_ms;
273 	}  while (!_HA_ATOMIC_CAS(&global_now_ms, &old_now_ms, new_now_ms));
274 
275 	return;
276 }
277 
278 /* returns the current date as returned by gettimeofday() in ISO+microsecond
279  * format. It uses a thread-local static variable that the reader can consume
280  * for as long as it wants until next call. Thus, do not call it from a signal
281  * handler. If <pad> is non-0, a trailing space will be added. It will always
282  * return exactly 32 or 33 characters (depending on padding) and will always be
283  * zero-terminated, thus it will always fit into a 34 bytes buffer.
284  * This also always include the local timezone (in +/-HH:mm format) .
285  */
timeofday_as_iso_us(int pad)286 char *timeofday_as_iso_us(int pad)
287 {
288 	struct timeval new_date;
289 	struct tm tm;
290 	const char *offset;
291 	char c;
292 	gettimeofday(&new_date, NULL);
293 	if (new_date.tv_sec != iso_time_sec || !new_date.tv_sec) {
294 		get_localtime(new_date.tv_sec, &tm);
295 		offset = get_gmt_offset(new_date.tv_sec, &tm);
296 		if (unlikely(strftime(iso_time_str, sizeof(iso_time_str), "%Y-%m-%dT%H:%M:%S.000000+00:00", &tm) != 32))
297 			strcpy(iso_time_str, "YYYY-mm-ddTHH:MM:SS.000000-00:00"); // make the failure visible but respect format.
298 		iso_time_str[26] = offset[0];
299 		iso_time_str[27] = offset[1];
300 		iso_time_str[28] = offset[2];
301 		iso_time_str[30] = offset[3];
302 		iso_time_str[31] = offset[4];
303 		iso_time_sec = new_date.tv_sec;
304 	}
305 	/* utoa_pad adds a trailing 0 so we save the char for restore */
306 	c = iso_time_str[26];
307 	utoa_pad(new_date.tv_usec, iso_time_str + 20, 7);
308 	iso_time_str[26] = c;
309 	if (pad) {
310 		iso_time_str[32] = ' ';
311 		iso_time_str[33] = 0;
312 	}
313 	return iso_time_str;
314 }
315 
316 /*
317  * Local variables:
318  *  c-indent-level: 8
319  *  c-basic-offset: 8
320  * End:
321  */
322