From 5e7b5aab292db7220d6774f51c7937e0c3d5b329 Mon Sep 17 00:00:00 2001
From: Isaac Boukris <iboukris@gmail.com>
Date: Wed, 20 Sep 2023 10:32:01 +0300
Subject: [PATCH] WIP: rework pcapng_tsc_to_ns()

---
 lib/pcapng/rte_pcapng.c | 35 +++++++----------------------------
 1 file changed, 7 insertions(+), 28 deletions(-)

diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c
index 3c91fc7764..4a32d2a40a 100644
--- a/lib/pcapng/rte_pcapng.c
+++ b/lib/pcapng/rte_pcapng.c
@@ -112,45 +112,24 @@ pcapng_init(void)
        pcapng_time.cycles = (pcapng_time.cycles + rte_get_tsc_cycles()) / 2;
        pcapng_time.ns = rte_timespec_to_ns(&ts);

-       pcapng_time.tsc_hz = rte_get_tsc_hz();
+       pcapng_time.tsc_hz = rte_get_tsc_hz() / NSEC_PER_SEC;
+       if (pcapng_time.tsc_hz == 0) { /* ? */ }
        pcapng_time.tsc_hz_inverse = rte_reciprocal_value_u64(pcapng_time.tsc_hz);
 }

 /* PCAPNG timestamps are in nanoseconds */
 static uint64_t pcapng_tsc_to_ns(uint64_t cycles)
 {
-       uint64_t delta, secs;
+       uint64_t delta;

-       if (!pcapng_time.tsc_hz)
+       if (!pcapng_time.tsc_hz) {
                pcapng_init();
+               return pcapng_time.ns;
+       }

-       /* In essence the calculation is:
-        *   delta = (cycles - pcapng_time.cycles) * NSEC_PRE_SEC / rte_get_tsc_hz()
-        * but this overflows within 4 to 8 seconds depending on TSC frequency.
-        * Instead, if delta >= pcapng_time.tsc_hz:
-        *   Increase pcapng_time.ns and pcapng_time.cycles by the number of
-        *   whole seconds in delta and reduce delta accordingly.
-        * delta will therefore always lie in the interval [0, pcapng_time.tsc_hz),
-        * which will not overflow when multiplied by NSEC_PER_SEC provided the
-        * TSC frequency < approx 18.4GHz.
-        *
-        * Currently all TSCs operate below 5GHz.
-        */
        delta = cycles - pcapng_time.cycles;
-       if (unlikely(delta >= pcapng_time.tsc_hz)) {
-               if (likely(delta < pcapng_time.tsc_hz * 2)) {
-                       delta -= pcapng_time.tsc_hz;
-                       pcapng_time.cycles += pcapng_time.tsc_hz;
-                       pcapng_time.ns += NSEC_PER_SEC;
-               } else {
-                       secs = rte_reciprocal_divide_u64(delta, &pcapng_time.tsc_hz_inverse);
-                       delta -= secs * pcapng_time.tsc_hz;
-                       pcapng_time.cycles += secs * pcapng_time.tsc_hz;
-                       pcapng_time.ns += secs * NSEC_PER_SEC;
-               }
-       }

-       return pcapng_time.ns + rte_reciprocal_divide_u64(delta * NSEC_PER_SEC,
+       return pcapng_time.ns + rte_reciprocal_divide_u64(delta,
                                                          &pcapng_time.tsc_hz_inverse);
 }

--
2.39.3