From 43b948f9a846109acdc6b3ba0f407c6570fe6a05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Cab=C3=A9?= Date: Mon, 8 Jul 2024 18:55:29 +0200 Subject: [PATCH] net: ptp: Properly handle second overflow/underflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes issues with net_ptp_time arithmetic where second overflow/underflow would not be handled properly. Signed-off-by: Benjamin CabĂ© Signed-off-by: Adam Wojasinski --- subsys/net/lib/ptp/clock.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/subsys/net/lib/ptp/clock.c b/subsys/net/lib/ptp/clock.c index 0c6e548a9eb00b..2db8d1366ad1c7 100644 --- a/subsys/net/lib/ptp/clock.c +++ b/subsys/net/lib/ptp/clock.c @@ -523,13 +523,24 @@ void ptp_clock_synchronize(uint64_t ingress, uint64_t egress) /* If diff is too big, ptp_clk needs to be set first. */ if ((offset > (int64_t)NSEC_PER_SEC) || (offset < -(int64_t)NSEC_PER_SEC)) { struct net_ptp_time current; + int32_t dest_nsec; LOG_WRN("Clock offset exceeds 1 second."); ptp_clock_get(ptp_clk.phc, ¤t); current.second -= (uint64_t)(offset / NSEC_PER_SEC); - current.nanosecond -= (uint32_t)(offset % NSEC_PER_SEC); + dest_nsec = (int32_t)(current.nanosecond - (uint32_t)(offset % NSEC_PER_SEC)); + + if (dest_nsec < 0) { + current.second--; + dest_nsec += NSEC_PER_SEC; + } else if (dest_nsec >= NSEC_PER_SEC) { + current.second++; + dest_nsec -= NSEC_PER_SEC; + } + + current.nanosecond = (uint32_t)dest_nsec; ptp_clock_set(ptp_clk.phc, ¤t); return;