On Sat, 7 May 2022 17:12:36 +0100 Quentin Armitage <quen...@armitage.org.uk> wrote:
> In pcap_tsc_to_ns(), delta * NSEC_PER_SEC will overflow approx 8 > seconds after pcap_init is called when using a TSC with a frequency > of 2.5GHz. > > To avoid the overflow, reread the time and TSC once > delta * NSEC_PER_SEC > (1 << 63). In order to ensure that there > is no overflow if there is a several second gap between calls to > pcapng_tsc_to_ns() the actual check to reread the clock is: > delta > ((1ULL << 63) / NSEC_PER_SEC) > > Fixes: 8d23ce8f5ee ("pcapng: add new library for writing pcapng files") > Cc: sta...@dpdk.org > > Signed-off-by: Quentin Armitage <quen...@armitage.org.uk> What about something like this instead. diff --git a/lib/pcapng/rte_pcapng.c b/lib/pcapng/rte_pcapng.c index 90b2f5bc6905..c5534301bf2c 100644 --- a/lib/pcapng/rte_pcapng.c +++ b/lib/pcapng/rte_pcapng.c @@ -19,6 +19,7 @@ #include <rte_ether.h> #include <rte_mbuf.h> #include <rte_pcapng.h> +#include <rte_reciprocal.h> #include <rte_time.h> #include "pcapng_proto.h" @@ -34,27 +35,39 @@ struct rte_pcapng { }; /* For converting TSC cycles to PCAPNG ns format */ -struct pcapng_time { +#define TICK_SCALE 16u +static struct { uint64_t ns; uint64_t cycles; + struct rte_reciprocal_u64 inverse; } pcapng_time; RTE_INIT(pcapng_init) { struct timespec ts; + uint64_t scale_tick_per_ns; pcapng_time.cycles = rte_get_tsc_cycles(); clock_gettime(CLOCK_REALTIME, &ts); pcapng_time.ns = rte_timespec_to_ns(&ts); + + scale_tick_per_ns = (rte_get_tsc_hz() * TICK_SCALE) / NSEC_PER_SEC; + pcapng_time.inverse = rte_reciprocal_value_u64(scale_tick_per_ns); } /* PCAPNG timestamps are in nanoseconds */ static uint64_t pcapng_tsc_to_ns(uint64_t cycles) { - uint64_t delta; + uint64_t delta, elapsed; delta = cycles - pcapng_time.cycles; - return pcapng_time.ns + (delta * NSEC_PER_SEC) / rte_get_tsc_hz(); + + /* Compute elapsed time in nanoseconds scaled by TICK_SCALE + * since the start of the capture. + * With scale of 4 this will roll over in 36 years. + */ + elapsed = rte_reciprocal_divide_u64(delta, &pcapng_time.inverse); + return pcapng_time.ns + elapsed / TICK_SCALE; } /* length of option including padding */