MINOR: time: also provide a global, monotonic global_now_ms timer

The period-based freq counters need the global date in milliseconds,
so better calculate it and expose it rather than letting all call
places incorrectly retrieve it.

Here what we do is that we maintain a new globally monotonic timer,
global_now_ms, which ought to be very close to the global_now one,
but maintains the monotonic approach of now_ms between all threads
in that global_now_ms is always ahead of any now_ms.

This patch is made simple to ease backporting (it will be needed for
a subsequent fix), but it also opens the way to some simplifications
on the time handling: instead of computing the local time and trying
to force it to the global one, we should soon be able to proceed in
the opposite way, that is computing the new global time an making the
local one just the latest snapshot of it. This will bring the benefit
of making sure that the global time is always ahead of the local one.

(cherry picked from commit 6064b34be0e761de881a5bfca287d01f69122602)
Signed-off-by: Willy Tarreau <w@1wt.eu>
(cherry picked from commit 3a9bc55350e18a92538ffa7295a204420fdba683)
Signed-off-by: Willy Tarreau <w@1wt.eu>
(cherry picked from commit 29d0329b8af90af42d37007c8c89872203fba1a3)
Signed-off-by: Christopher Faulet <cfaulet@haproxy.com>
diff --git a/src/time.c b/src/time.c
index f5c5358..d1e356a 100644
--- a/src/time.c
+++ b/src/time.c
@@ -16,6 +16,7 @@
 
 #include <common/config.h>
 #include <common/standard.h>
+#include <common/ticks.h>
 #include <common/time.h>
 #include <common/hathreads.h>
 
@@ -31,6 +32,7 @@
 
 static THREAD_LOCAL struct timeval tv_offset;  /* per-thread time ofsset relative to global time */
 volatile unsigned long long global_now;      /* common date between all threads (32:32) */
+volatile unsigned int global_now_ms;         /* common date in milliseconds (may wrap) */
 
 /*
  * adds <ms> ms to <from>, set the result to <tv> and returns a pointer <tv>
@@ -176,6 +178,7 @@
 {
 	struct timeval adjusted, deadline, tmp_now, tmp_adj;
 	unsigned int   curr_sec_ms;     /* millisecond of current second (0..999) */
+	unsigned int old_now_ms, new_now_ms;
 	unsigned long long old_now;
 	unsigned long long new_now;
 
@@ -259,6 +262,15 @@
 	 */
 	ms_left_scaled = (999U - curr_sec_ms) * 4294967U;
 	now_ms = now.tv_sec * 1000 + curr_sec_ms;
+
+	/* update the global current millisecond */
+	old_now_ms = global_now_ms;
+	do {
+		new_now_ms = old_now_ms;
+		if (tick_is_lt(new_now_ms, now_ms))
+			new_now_ms = now_ms;
+	}  while (!_HA_ATOMIC_CAS(&global_now_ms, &old_now_ms, new_now_ms));
+
 	return;
 }