Skip to contentSkip to conversation

ntp/rtc: Fixes and cleanups

PATCH Applied Thomas Gleixner 13 participants 54 messages Dec 6, 2020 – Feb 11, 2021

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover ntp/rtc: Fixes and cleanups

Miroslav ran into a situation where the periodic RTC synchronization almost never was able to hit the time window for the update. That happens due the usage of delayed_work and the properties of the timer wheel.

While that particular problem is halfways simple to fix this started to unearth other problems with that code particularly with rtc_set_npt_time() but expanded into other things as well.

1) The update offset for rtc-cmos is off by a full second

2) The readout of MC146818 (rtc-cmos and arch code) is broken and can return garbage.

2) Alexandre questioned the approach in general and wants to get rid of it. Of course there are better methods to do that and it can be completely done in user space.

Unfortunately it's not that simple as this would be a user visible change, so making it at least halfways correct.

3) Alexandre requested to move that code into the NTP code as this is not really RTC functionality and just usage of the RTC API.

4) The update offset itself was questioned, but the time between the write and the next seconds increment in the RTC is fundamentaly a hardware property. The transport time, which is pretty irrelevant for direct accessible RTCs (rtc-cmos), but relevant for RTC behind i2c/SPI needs to be added on top.

It's undebated that this transport time cannot be correctly estimated, but right now it's 500ms which is far off. The correct transport time can be calibrated, a halfways correct value supplied via DT, but that's an orthogonal problem.

The following series addresses the above:

1) Fix the readout function of MC146818
2) Fix the rtc-cmos offset
3) Reduce the default transport time

4) Switch the NTP periodic sync code to a hrtimer/work combo

5) Move rtc_set_npt_time() to the ntp code
6) Make the update offset more intuitive
7) Simplify the whole machinery

Thanks,

tglx

---
 a/drivers/rtc/systohc.c        |   61 ----------
 drivers/rtc/Makefile           |    1 
 drivers/rtc/class.c            |    9 +
 drivers/rtc/rtc-cmos.c         |    3 
 drivers/rtc/rtc-mc146818-lib.c |   70 +++++++-----
 include/linux/rtc.h            |   69 +++++-------
 include/linux/timex.h          |    1 
 kernel/time/ntp.c              |  232 ++++++++++++++++++++++++-----------------
 kernel/time/ntp_internal.h     |    7 +
 9 files changed, 225 insertions(+), 228 deletions(-)
#1 lore raw

PATCH 1/8 rtc: mc146818: Prevent reading garbage

The MC146818 driver is prone to read garbage from the RTC. There are several issues all related to the update cycle of the MC146818. The chip increments seconds obviously once per second and indicates that by a bit in a register. The bit goes high 244us before the actual update starts. During the update the readout of the time values is undefined.

The code just checks whether the update in progress bit (UIP) is set before reading the clock. If it's set it waits arbitrary 20ms before retrying, which is ample because the maximum update time is ~2ms.

But this check does not guarantee that the UIP bit goes high and the actual update happens during the readout. So the following can happen

0.997 UIP = False
-> Interrupt/NMI/preemption
0.998 UIP -> True
0.999 Readout <- Undefined

To prevent this rework the code so it checks UIP before and after the readout and if set after the readout try again.

But that's not enough to cover the following:

0.997 UIP = False
Readout seconds
-> NMI (or vCPU scheduled out)
0.998 UIP -> True
update completes

	       UIP -> False

1.000 Readout minutes,....
UIP check succeeds

That can make the readout wrong up to 59 seconds.

To prevent this, read the seconds value before the first UIP check, validate it after checking UIP and after reading out the rest.

It's amazing that the original i386 code had this actually correct and the generic implementation of the MC146818 driver got it wrong in 2002 and it stayed that way until today.

---
 drivers/rtc/rtc-mc146818-lib.c |   64 ++++++++++++++++++++++++-----------------
 1 file changed, 39 insertions(+), 25 deletions(-)
drivers/rtc/rtc-mc146818-lib.c +39 -25
@@ -8,41 +8,41 @@
 #include <linux/acpi.h>
 #endif
 
-/*
- * Returns true if a clock update is in progress
- */
-static inline unsigned char mc146818_is_updating(void)
-{
-	unsigned char uip;
-	unsigned long flags;
-
-	spin_lock_irqsave(&rtc_lock, flags);
-	uip = (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
-	spin_unlock_irqrestore(&rtc_lock, flags);
-	return uip;
-}
-
 unsigned int mc146818_get_time(struct rtc_time *time)
 {
 	unsigned char ctrl;
 	unsigned long flags;
 	unsigned char century = 0;
+	bool retry;
 
 #ifdef CONFIG_MACH_DECSTATION
 	unsigned int real_year;
 #endif
 
+again:
+	spin_lock_irqsave(&rtc_lock, flags);
 	/*
-	 * read RTC once any update in progress is done. The update
-	 * can take just over 2ms. We wait 20ms. There is no need to
-	 * to poll-wait (up to 1s - eeccch) for the falling edge of RTC_UIP.
-	 * If you need to know *exactly* when a second has started, enable
-	 * periodic update complete interrupts, (via ioctl) and then
-	 * immediately read /dev/rtc which will block until you get the IRQ.
-	 * Once the read clears, read the RTC time (again via ioctl). Easy.
+	 * Check whether there is an update in progress during which the
+	 * readout is unspecified. The maximum update time is ~2ms. Poll
+	 * every msec for completion.
+	 *
+	 * Store the second value before checking UIP so a long lasting NMI
+	 * which happens to hit after the UIP check cannot make an update
+	 * cycle invisible.
 	 */
-	if (mc146818_is_updating())
-		mdelay(20);
+	time->tm_sec = CMOS_READ(RTC_SECONDS);
+
+	if (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		mdelay(1);
+		goto again;
+	}
+
+	/* Revalidate the above readout */
+	if (time->tm_sec != CMOS_READ(RTC_SECONDS)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		goto again;
+	}
 
 	/*
 	 * Only the values that we read from the RTC are set. We leave
@@ -50,8 +50,6 @@ unsigned int mc146818_get_time(struct rt
 	 * RTC has RTC_DAY_OF_WEEK, we ignore it, as it is only updated
 	 * by the RTC when initially set to a non-zero value.
 	 */
-	spin_lock_irqsave(&rtc_lock, flags);
-	time->tm_sec = CMOS_READ(RTC_SECONDS);
 	time->tm_min = CMOS_READ(RTC_MINUTES);
 	time->tm_hour = CMOS_READ(RTC_HOURS);
 	time->tm_mday = CMOS_READ(RTC_DAY_OF_MONTH);
@@ -66,8 +64,24 @@ unsigned int mc146818_get_time(struct rt
 		century = CMOS_READ(acpi_gbl_FADT.century);
 #endif
 	ctrl = CMOS_READ(RTC_CONTROL);
+	/*
+	 * Check for the UIP bit again. If it is set now then
+	 * the above values may contain garbage.
+	 */
+	retry = CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP;
+	/*
+	 * A NMI might have interrupted the above sequence so check whether
+	 * the seconds value has changed which indicates that the NMI took
+	 * longer than the UIP bit was set. Unlikely, but possible and
+	 * there is also virt...
+	 */
+	retry |= time->tm_sec != CMOS_READ(RTC_SECONDS);
+
 	spin_unlock_irqrestore(&rtc_lock, flags);
 
+	if (retry)
+		goto again;
+
 	if (!(ctrl & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
 	{
 		time->tm_sec = bcd2bin(time->tm_sec);
#2 lore raw

[tip: timers/core] rtc: mc146818: Prevent reading garbage

The following commit has been merged into the timers/core branch of tip:

The following commit has been merged into the timers/core branch of tip:

Commit-ID:     05a0302c35481e9b47fb90ba40922b0a4cae40d8
Gitweb:        https://git.kernel.org/tip/05a0302c35481e9b47fb90ba40922b0a4cae40d8
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Sun, 06 Dec 2020 22:46:14 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Fri, 11 Dec 2020 10:40:52 +01:00

rtc: mc146818: Prevent reading garbage

The MC146818 driver is prone to read garbage from the RTC. There are several issues all related to the update cycle of the MC146818. The chip increments seconds obviously once per second and indicates that by a bit in a register. The bit goes high 244us before the actual update starts. During the update the readout of the time values is undefined.

The code just checks whether the update in progress bit (UIP) is set before reading the clock. If it's set it waits arbitrary 20ms before retrying, which is ample because the maximum update time is ~2ms.

But this check does not guarantee that the UIP bit goes high and the actual update happens during the readout. So the following can happen

0.997 UIP = False
-> Interrupt/NMI/preemption
0.998 UIP -> True
0.999 Readout <- Undefined

To prevent this rework the code so it checks UIP before and after the readout and if set after the readout try again.

But that's not enough to cover the following:

0.997 UIP = False
Readout seconds
-> NMI (or vCPU scheduled out)
0.998 UIP -> True
update completes

	       UIP -> False

1.000 Readout minutes,....
UIP check succeeds

That can make the readout wrong up to 59 seconds.

To prevent this, read the seconds value before the first UIP check, validate it after checking UIP and after reading out the rest.

It's amazing that the original i386 code had this actually correct and the generic implementation of the MC146818 driver got it wrong in 2002 and it stayed that way until today.

---
 drivers/rtc/rtc-mc146818-lib.c | 64 ++++++++++++++++++++-------------
 1 file changed, 39 insertions(+), 25 deletions(-)
drivers/rtc/rtc-mc146818-lib.c +39 -25
index 2ecd875..98048bb 100644
@@ -8,41 +8,41 @@
 #include <linux/acpi.h>
 #endif
 
-/*
- * Returns true if a clock update is in progress
- */
-static inline unsigned char mc146818_is_updating(void)
-{
-	unsigned char uip;
-	unsigned long flags;
-
-	spin_lock_irqsave(&rtc_lock, flags);
-	uip = (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
-	spin_unlock_irqrestore(&rtc_lock, flags);
-	return uip;
-}
-
 unsigned int mc146818_get_time(struct rtc_time *time)
 {
 	unsigned char ctrl;
 	unsigned long flags;
 	unsigned char century = 0;
+	bool retry;
 
 #ifdef CONFIG_MACH_DECSTATION
 	unsigned int real_year;
 #endif
 
+again:
+	spin_lock_irqsave(&rtc_lock, flags);
 	/*
-	 * read RTC once any update in progress is done. The update
-	 * can take just over 2ms. We wait 20ms. There is no need to
-	 * to poll-wait (up to 1s - eeccch) for the falling edge of RTC_UIP.
-	 * If you need to know *exactly* when a second has started, enable
-	 * periodic update complete interrupts, (via ioctl) and then
-	 * immediately read /dev/rtc which will block until you get the IRQ.
-	 * Once the read clears, read the RTC time (again via ioctl). Easy.
+	 * Check whether there is an update in progress during which the
+	 * readout is unspecified. The maximum update time is ~2ms. Poll
+	 * every msec for completion.
+	 *
+	 * Store the second value before checking UIP so a long lasting NMI
+	 * which happens to hit after the UIP check cannot make an update
+	 * cycle invisible.
 	 */
-	if (mc146818_is_updating())
-		mdelay(20);
+	time->tm_sec = CMOS_READ(RTC_SECONDS);
+
+	if (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		mdelay(1);
+		goto again;
+	}
+
+	/* Revalidate the above readout */
+	if (time->tm_sec != CMOS_READ(RTC_SECONDS)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		goto again;
+	}
 
 	/*
 	 * Only the values that we read from the RTC are set. We leave
@@ -50,8 +50,6 @@ unsigned int mc146818_get_time(struct rtc_time *time)
 	 * RTC has RTC_DAY_OF_WEEK, we ignore it, as it is only updated
 	 * by the RTC when initially set to a non-zero value.
 	 */
-	spin_lock_irqsave(&rtc_lock, flags);
-	time->tm_sec = CMOS_READ(RTC_SECONDS);
 	time->tm_min = CMOS_READ(RTC_MINUTES);
 	time->tm_hour = CMOS_READ(RTC_HOURS);
 	time->tm_mday = CMOS_READ(RTC_DAY_OF_MONTH);
@@ -66,8 +64,24 @@ unsigned int mc146818_get_time(struct rtc_time *time)
 		century = CMOS_READ(acpi_gbl_FADT.century);
 #endif
 	ctrl = CMOS_READ(RTC_CONTROL);
+	/*
+	 * Check for the UIP bit again. If it is set now then
+	 * the above values may contain garbage.
+	 */
+	retry = CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP;
+	/*
+	 * A NMI might have interrupted the above sequence so check whether
+	 * the seconds value has changed which indicates that the NMI took
+	 * longer than the UIP bit was set. Unlikely, but possible and
+	 * there is also virt...
+	 */
+	retry |= time->tm_sec != CMOS_READ(RTC_SECONDS);
+
 	spin_unlock_irqrestore(&rtc_lock, flags);
 
+	if (retry)
+		goto again;
+
 	if (!(ctrl & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
 	{
 		time->tm_sec = bcd2bin(time->tm_sec);
#3 lore raw

Re: [patch 1/8] rtc: mc146818: Prevent reading garbage - bug

In reply to Thomas Gleixner

Hi,

After some bisecting, I found that commit 05a0302c3548 ("rtc: mc146818:
Prevent reading garbage", this patch, introduced since v5.11-rc1) makes my VM hang at boot. Before this commit, I got this (and didn't notice) at every boot:
rtc_cmos rtc_cmos: registered as rtc0
rtc_cmos rtc_cmos: hctosys: unable to read the hardware clock rtc_cmos rtc_cmos: alarms up to one day, 114 bytes nvram

I notice that this patch creates infinite loops, which my VM falls into (cf. below).

I didn't succeed to properly fix this without a revert. I tried to set a maximum number of jumps, but I got pvqspinlock warnings.

Regards,
Mickaël

Quoted 92 lines · Thomas Gleixner

The MC146818 driver is prone to read garbage from the RTC. There are several issues all related to the update cycle of the MC146818. The chip increments seconds obviously once per second and indicates that by a bit in a register. The bit goes high 244us before the actual update starts. During the update the readout of the time values is undefined.

The code just checks whether the update in progress bit (UIP) is set before reading the clock. If it's set it waits arbitrary 20ms before retrying, which is ample because the maximum update time is ~2ms.

But this check does not guarantee that the UIP bit goes high and the actual update happens during the readout. So the following can happen

0.997 UIP = False
-> Interrupt/NMI/preemption
0.998 UIP -> True
0.999 Readout <- Undefined

To prevent this rework the code so it checks UIP before and after the readout and if set after the readout try again.

But that's not enough to cover the following:

0.997 UIP = False

(quoted diff) +0 -0
 	       Readout seconds
   -> NMI (or vCPU scheduled out)
 0.998	       UIP -> True
 	       update completes
	       UIP -> False

1.000 Readout minutes,....
UIP check succeeds

That can make the readout wrong up to 59 seconds.

To prevent this, read the seconds value before the first UIP check, validate it after checking UIP and after reading out the rest.

It's amazing that the original i386 code had this actually correct and the generic implementation of the MC146818 driver got it wrong in 2002 and it stayed that way until today.

---
 drivers/rtc/rtc-mc146818-lib.c |   64 ++++++++++++++++++++++++-----------------
 1 file changed, 39 insertions(+), 25 deletions(-)
drivers/rtc/rtc-mc146818-lib.c +8 -21
@@ -8,41 +8,41 @@
 #include <linux/acpi.h>
 #endif
 
-/*
- * Returns true if a clock update is in progress
- */
-static inline unsigned char mc146818_is_updating(void)
-{
-	unsigned char uip;
-	unsigned long flags;
-
-	spin_lock_irqsave(&rtc_lock, flags);
-	uip = (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
-	spin_unlock_irqrestore(&rtc_lock, flags);
-	return uip;
-}
-
 unsigned int mc146818_get_time(struct rtc_time *time)
 {
 	unsigned char ctrl;
 	unsigned long flags;
 	unsigned char century = 0;
+	bool retry;
 
 #ifdef CONFIG_MACH_DECSTATION
 	unsigned int real_year;
 #endif
 
+again:
+	spin_lock_irqsave(&rtc_lock, flags);
 	/*
-	 * read RTC once any update in progress is done. The update
-	 * can take just over 2ms. We wait 20ms. There is no need to
-	 * to poll-wait (up to 1s - eeccch) for the falling edge of RTC_UIP.
-	 * If you need to know *exactly* when a second has started, enable
-	 * periodic update complete interrupts, (via ioctl) and then
-	 * immediately read /dev/rtc which will block until you get the IRQ.
-	 * Once the read clears, read the RTC time (again via ioctl). Easy.
+	 * Check whether there is an update in progress during which the
+	 * readout is unspecified. The maximum update time is ~2ms. Poll
+	 * every msec for completion.
+	 *
+	 * Store the second value before checking UIP so a long lasting NMI

drivers/rtc/rtc-mc146818-lib.c line 37

Quoted 10 lines
drivers/rtc/rtc-mc146818-lib.c +7 -2
+	 * which happens to hit after the UIP check cannot make an update
+	 * cycle invisible.
 	 */
-	if (mc146818_is_updating())
-		mdelay(20);
+	time->tm_sec = CMOS_READ(RTC_SECONDS);
+
+	if (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		mdelay(1);

My VM loops here.
time->tm_sec is always 255.

Quoted 47 lines
drivers/rtc/rtc-mc146818-lib.c +24 -2
+		goto again;
+	}
+
+	/* Revalidate the above readout */
+	if (time->tm_sec != CMOS_READ(RTC_SECONDS)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		goto again;
+	}
 
 	/*
 	 * Only the values that we read from the RTC are set. We leave
@@ -50,8 +50,6 @@ unsigned int mc146818_get_time(struct rt
 	 * RTC has RTC_DAY_OF_WEEK, we ignore it, as it is only updated
 	 * by the RTC when initially set to a non-zero value.
 	 */
-	spin_lock_irqsave(&rtc_lock, flags);
-	time->tm_sec = CMOS_READ(RTC_SECONDS);
 	time->tm_min = CMOS_READ(RTC_MINUTES);
 	time->tm_hour = CMOS_READ(RTC_HOURS);
 	time->tm_mday = CMOS_READ(RTC_DAY_OF_MONTH);
@@ -66,8 +64,24 @@ unsigned int mc146818_get_time(struct rt
 		century = CMOS_READ(acpi_gbl_FADT.century);
 #endif
 	ctrl = CMOS_READ(RTC_CONTROL);
+	/*
+	 * Check for the UIP bit again. If it is set now then
+	 * the above values may contain garbage.
+	 */
+	retry = CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP;
+	/*
+	 * A NMI might have interrupted the above sequence so check whether
+	 * the seconds value has changed which indicates that the NMI took
+	 * longer than the UIP bit was set. Unlikely, but possible and
+	 * there is also virt...
+	 */
+	retry |= time->tm_sec != CMOS_READ(RTC_SECONDS);
+
 	spin_unlock_irqrestore(&rtc_lock, flags);
 
+	if (retry)
+		goto again;
+
 	if (!(ctrl & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
 	{
 		time->tm_sec = bcd2bin(time->tm_sec);
#4 lore raw

Re: [patch 1/8] rtc: mc146818: Prevent reading garbage - bug

Quoted 10 lines · Mickaël Salaün

After some bisecting, I found that commit 05a0302c3548 ("rtc: mc146818:
Prevent reading garbage", this patch, introduced since v5.11-rc1) makes my VM hang at boot. Before this commit, I got this (and didn't notice) at every boot:
rtc_cmos rtc_cmos: registered as rtc0
rtc_cmos rtc_cmos: hctosys: unable to read the hardware clock rtc_cmos rtc_cmos: alarms up to one day, 114 bytes nvram

I notice that this patch creates infinite loops, which my VM falls into (cf. below).

Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+	time->tm_sec = CMOS_READ(RTC_SECONDS);
+
+	if (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		mdelay(1);

My VM loops here.
time->tm_sec is always 255.

That means there is no RTC and therefore the CMOS_READ($REG) returns 0xFF which makes the loop stuck because RTC_UIP is always set.

Yet another proof that VIRT creates more problems than it solves.

Fix below.

Thanks,

tglx
---
Subject: rtc: mc146818: Detect and handle broken RTCs
From: Thomas Gleixner <[email protected]>
Date: Tue, 26 Jan 2021 11:38:40 +0100

The recent fix for handling the UIP bit unearthed another issue in the RTC code. If the RTC is advertised but the readout is straight 0xFF because it's not available, the old code just proceeded with crappy values, but the new code hangs because it waits for the UIP bit to become low.

Add a sanity check in the RTC CMOS probe function which reads the RTC_VALID register (Register D) which should have bit 0-6 cleared. If that's not the case then fail to register the CMOS.

Add the same check to mc146818_get_time(), warn once when the condition is true and invalidate the rtc_time data.

---
 drivers/rtc/rtc-cmos.c         |    8 ++++++++
 drivers/rtc/rtc-mc146818-lib.c |    7 +++++++
 2 files changed, 15 insertions(+)
drivers/rtc/rtc-cmos.c +8 -0
@@ -805,6 +805,14 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+		spin_unlock_irq(&rtc_lock);
+		dev_warn(dev, "not accessible\n");
+		retval = -ENXIO;
+		goto cleanup1;
+	}
+
 	if (!(flags & CMOS_RTC_FLAGS_NOFREQ)) {
 		/* force periodic irq to CMOS reset default of 1024Hz;
 		 *
drivers/rtc/rtc-mc146818-lib.c +7 -0
@@ -21,6 +21,13 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(time));
+		return 0;
+	}
+
 	/*
 	 * Check whether there is an update in progress during which the
 	 * readout is unspecified. The maximum update time is ~2ms. Poll
#5 lore raw

Re: [patch 1/8] rtc: mc146818: Prevent reading garbage - bug

Thanks for the fix! It boots now with a new message:
rtc_cmos rtc_cmos: not accessible

I tested with rtc=on and rtc=off (which didn't make a difference before this fix) on a microvm:
https://github.com/qemu/qemu/blob/master/docs/system/i386/microvm.rst

There is one issue with the memset though:

Quoted 74 lines · Thomas Gleixner
Quoted 10 lines · Mickaël Salaün

After some bisecting, I found that commit 05a0302c3548 ("rtc: mc146818:
Prevent reading garbage", this patch, introduced since v5.11-rc1) makes my VM hang at boot. Before this commit, I got this (and didn't notice) at every boot:
rtc_cmos rtc_cmos: registered as rtc0
rtc_cmos rtc_cmos: hctosys: unable to read the hardware clock rtc_cmos rtc_cmos: alarms up to one day, 114 bytes nvram

I notice that this patch creates infinite loops, which my VM falls into (cf. below).

Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+	time->tm_sec = CMOS_READ(RTC_SECONDS);
+
+	if (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		mdelay(1);

My VM loops here.
time->tm_sec is always 255.

That means there is no RTC and therefore the CMOS_READ($REG) returns 0xFF which makes the loop stuck because RTC_UIP is always set.

Yet another proof that VIRT creates more problems than it solves.

Fix below.

Thanks,

tglx
---
Subject: rtc: mc146818: Detect and handle broken RTCs
From: Thomas Gleixner <[email protected]>
Date: Tue, 26 Jan 2021 11:38:40 +0100

The recent fix for handling the UIP bit unearthed another issue in the RTC code. If the RTC is advertised but the readout is straight 0xFF because it's not available, the old code just proceeded with crappy values, but the new code hangs because it waits for the UIP bit to become low.

Add a sanity check in the RTC CMOS probe function which reads the RTC_VALID register (Register D) which should have bit 0-6 cleared. If that's not the case then fail to register the CMOS.

Add the same check to mc146818_get_time(), warn once when the condition is true and invalidate the rtc_time data.

---
 drivers/rtc/rtc-cmos.c         |    8 ++++++++
 drivers/rtc/rtc-mc146818-lib.c |    7 +++++++
 2 files changed, 15 insertions(+)
drivers/rtc/rtc-cmos.c +8 -0
@@ -805,6 +805,14 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+		spin_unlock_irq(&rtc_lock);
+		dev_warn(dev, "not accessible\n");
+		retval = -ENXIO;
+		goto cleanup1;
+	}
+
 	if (!(flags & CMOS_RTC_FLAGS_NOFREQ)) {
 		/* force periodic irq to CMOS reset default of 1024Hz;
 		 *

drivers/rtc/rtc-mc146818-lib.c unsigned int mc146818_get_time(struct rt · line 27

Quoted 7 lines
drivers/rtc/rtc-mc146818-lib.c +4 -0
@@ -21,6 +21,13 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(time));

This should be: sizeof(*time)

drivers/rtc/rtc-mc146818-lib.c unsigned int mc146818_get_time(struct rt · line 33

Quoted 7 lines
drivers/rtc/rtc-mc146818-lib.c +3 -0
+		return 0;
+	}
+
 	/*
 	 * Check whether there is an update in progress during which the
 	 * readout is unspecified. The maximum update time is ~2ms. Poll
#6 lore raw

Re: [patch 1/8] rtc: mc146818: Prevent reading garbage - bug

Quoted 9 lines · Mickaël Salaün

Thanks for the fix! It boots now with a new message:
rtc_cmos rtc_cmos: not accessible

drivers/rtc/rtc-mc146818-lib.c unsigned int mc146818_get_time(struct rt · line 27

Quoted 5 lines
drivers/rtc/rtc-mc146818-lib.c +4 -0
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(time));

This should be: sizeof(*time)

Of course ....

Quoted 9 lines

drivers/rtc/rtc-mc146818-lib.c unsigned int mc146818_get_time(struct rt · line 33

Quoted 7 lines
drivers/rtc/rtc-mc146818-lib.c +3 -0
+		return 0;
+	}
+
 	/*
 	 * Check whether there is an update in progress during which the
 	 * readout is unspecified. The maximum update time is ~2ms. Poll
#7 lore raw

PATCH v2 1/1 rtc: mc146818: Detect and handle broken RTCs

The recent fix for handling the UIP bit unearthed another issue in the RTC code. If the RTC is advertised but the readout is straight 0xFF because it's not available, the old code just proceeded with crappy values, but the new code hangs because it waits for the UIP bit to become low.

Add a sanity check in the RTC CMOS probe function which reads the RTC_VALID register (Register D) which should have bit 0-6 cleared. If that's not the case then fail to register the CMOS.

Add the same check to mc146818_get_time(), warn once when the condition is true and invalidate the rtc_time data.

---
V2: Fixed the sizeof() as spotted by Mickaël

---
 drivers/rtc/rtc-cmos.c         |    8 ++++++++
 drivers/rtc/rtc-mc146818-lib.c |    7 +++++++
 2 files changed, 15 insertions(+)
drivers/rtc/rtc-cmos.c +8 -0
@@ -805,6 +805,14 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+		spin_unlock_irq(&rtc_lock);
+		dev_warn(dev, "not accessible\n");
+		retval = -ENXIO;
+		goto cleanup1;
+	}
+
 	if (!(flags & CMOS_RTC_FLAGS_NOFREQ)) {
 		/* force periodic irq to CMOS reset default of 1024Hz;
 		 *
drivers/rtc/rtc-mc146818-lib.c +7 -0
@@ -21,6 +21,13 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(*time));
+		return 0;
+	}
+
 	/*
 	 * Check whether there is an update in progress during which the
 	 * readout is unspecified. The maximum update time is ~2ms. Poll
maintainer Acked-by on v2 1/1
#8 lore raw

Re: [PATCH V2] rtc: mc146818: Detect and handle broken RTCs

Quoted 9 lines · Thomas Gleixner

The recent fix for handling the UIP bit unearthed another issue in the RTC code. If the RTC is advertised but the readout is straight 0xFF because it's not available, the old code just proceeded with crappy values, but the new code hangs because it waits for the UIP bit to become low.

Add a sanity check in the RTC CMOS probe function which reads the RTC_VALID register (Register D) which should have bit 0-6 cleared. If that's not the case then fail to register the CMOS.

Quoted 6 lines

Add the same check to mc146818_get_time(), warn once when the condition is true and invalidate the rtc_time data.

Quoted 40 lines

---
V2: Fixed the sizeof() as spotted by Mickaël

---
 drivers/rtc/rtc-cmos.c         |    8 ++++++++
 drivers/rtc/rtc-mc146818-lib.c |    7 +++++++
 2 files changed, 15 insertions(+)
drivers/rtc/rtc-cmos.c +8 -0
@@ -805,6 +805,14 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+		spin_unlock_irq(&rtc_lock);
+		dev_warn(dev, "not accessible\n");
+		retval = -ENXIO;
+		goto cleanup1;
+	}
+
 	if (!(flags & CMOS_RTC_FLAGS_NOFREQ)) {
 		/* force periodic irq to CMOS reset default of 1024Hz;
 		 *
drivers/rtc/rtc-mc146818-lib.c +7 -0
@@ -21,6 +21,13 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(*time));
+		return 0;
+	}
+
 	/*
 	 * Check whether there is an update in progress during which the
 	 * readout is unspecified. The maximum update time is ~2ms. Poll
Signature · 3 lines
Alexandre Belloni, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#9 lore raw

[tip: timers/urgent] rtc: mc146818: Detect and handle broken RTCs

In reply to Thomas Gleixner
The following commit has been merged into the timers/urgent branch of tip:

The following commit has been merged into the timers/urgent branch of tip:

Commit-ID:     211e5db19d15a721b2953ea54b8f26c2963720eb
Gitweb:        https://git.kernel.org/tip/211e5db19d15a721b2953ea54b8f26c2963720eb
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Tue, 26 Jan 2021 18:02:11 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Wed, 27 Jan 2021 09:36:22 +01:00

rtc: mc146818: Detect and handle broken RTCs

The recent fix for handling the UIP bit unearthed another issue in the RTC code. If the RTC is advertised but the readout is straight 0xFF because it's not available, the old code just proceeded with crappy values, but the new code hangs because it waits for the UIP bit to become low.

Add a sanity check in the RTC CMOS probe function which reads the RTC_VALID register (Register D) which should have bit 0-6 cleared. If that's not the case then fail to register the CMOS.

Add the same check to mc146818_get_time(), warn once when the condition is true and invalidate the rtc_time data.

---
 drivers/rtc/rtc-cmos.c         | 8 ++++++++
 drivers/rtc/rtc-mc146818-lib.c | 7 +++++++
 2 files changed, 15 insertions(+)
drivers/rtc/rtc-cmos.c +8 -0
index 51e80bc..68a9ac6 100644
@@ -805,6 +805,14 @@ cmos_do_probe(struct device *dev, struct resource *ports, int rtc_irq)
 
 	spin_lock_irq(&rtc_lock);
 
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+		spin_unlock_irq(&rtc_lock);
+		dev_warn(dev, "not accessible\n");
+		retval = -ENXIO;
+		goto cleanup1;
+	}
+
 	if (!(flags & CMOS_RTC_FLAGS_NOFREQ)) {
 		/* force periodic irq to CMOS reset default of 1024Hz;
 		 *
drivers/rtc/rtc-mc146818-lib.c +7 -0
index 972a5b9..f83c138 100644
@@ -21,6 +21,13 @@ unsigned int mc146818_get_time(struct rtc_time *time)
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(*time));
+		return 0;
+	}
+
 	/*
 	 * Check whether there is an update in progress during which the
 	 * readout is unspecified. The maximum update time is ~2ms. Poll
#10 lore raw

Re: [PATCH V2] rtc: mc146818: Detect and handle broken RTCs

In reply to Thomas Gleixner
Quoted 11 lines · Thomas Gleixner

The recent fix for handling the UIP bit unearthed another issue in the RTC code. If the RTC is advertised but the readout is straight 0xFF because it's not available, the old code just proceeded with crappy values, but the new code hangs because it waits for the UIP bit to become low.

Add a sanity check in the RTC CMOS probe function which reads the RTC_VALID register (Register D) which should have bit 0-6 cleared. If that's not the case then fail to register the CMOS.

Add the same check to mc146818_get_time(), warn once when the condition is true and invalidate the rtc_time data.

In case it is helpful: on my hardware this patch triggers a warning (attached below).

Without it the rtc messages look like this:

[    2.783386] rtc_cmos 00:01: RTC can wake from S4
[    2.784302] rtc_cmos 00:01: registered as rtc0
[    2.785036] rtc_cmos 00:01: setting system clock to 2021-01-31T10:13:40 UTC (1612088020)
[    2.785713] rtc_cmos 00:01: alarms up to one month, y3k, 114 bytes nvram, hpet irqs

Dirk

[    7.258410] ------------[ cut here ]------------
[    7.258414] WARNING: CPU: 2 PID: 0 at drivers/rtc/rtc-mc146818-lib.c:25 mc146818_get_time+0x2b/0x1e5
[    7.258420] Modules linked in: iwlmvm(+) mac80211 iwlwifi sdhci_pci amdgpu(+) drm_ttm_helper cfg80211 ttm cqhci gpu_sched sdhci ccp thinkpad_acpi(+) rng_core nvram tpm_tis(+) tpm_tis_core wmi tpm pinctrl_amd
[    7.258432] CPU: 2 PID: 0 Comm: swapper/2 Tainted: G        W         5.11.0-rc5-next-20210129-x86_64 #180
[    7.258434] Hardware name: LENOVO 20U50008GE/20U50008GE, BIOS R19ET26W (1.10 ) 06/22/2020
[    7.258435] RIP: 0010:mc146818_get_time+0x2b/0x1e5
[    7.258437] Code: 56 41 55 45 31 ed 41 54 55 53 48 89 fb 48 c7 c7 bc d9 eb 82 e8 26 d8 36 00 bf 0d 00 00 00 48 89 c5 e8 6d d1 8f ff a8 7f 74 24 <0f> 0b 48 c7 c7 bc d9 eb 82 48 89 ee e8 bc d6 36 00 b0 ff b9 24 00
[    7.258438] RSP: 0018:ffffc9000022cef0 EFLAGS: 00010002
[    7.258440] RAX: 0000000000000031 RBX: ffffc9000022cf24 RCX: 0000000000000000
[    7.258441] RDX: 0000000000000001 RSI: ffff888105607000 RDI: 000000000000000d
[    7.258441] RBP: 0000000000000046 R08: ffffc9000022cf24 R09: 0000000000000000
[    7.258442] R10: 0000000000000000 R11: 0000000000000000 R12: ffff888105607000
[    7.258443] R13: 0000000000000000 R14: ffffc9000022cfa4 R15: 0000000000000000
[    7.258444] FS:  0000000000000000(0000) GS:ffff88840ec80000(0000) knlGS:0000000000000000
[    7.258445] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[    7.258446] CR2: 00007f2ed26c4160 CR3: 000000000480a000 CR4: 0000000000350ee0
[    7.258447] Call Trace:
[    7.258449]  <IRQ>
[    7.258450]  hpet_rtc_interrupt+0xd3/0x1a3
[    7.258454]  __handle_irq_event_percpu+0x6b/0x12e
[    7.258457]  handle_irq_event_percpu+0x2c/0x6f
[    7.258459]  handle_irq_event+0x23/0x43
[    7.258461]  handle_edge_irq+0x9e/0xbb
[    7.258463]  asm_call_irq_on_stack+0x12/0x20
[    7.258467]  </IRQ>
[    7.258467]  common_interrupt+0x9a/0x123
[    7.258470]  asm_common_interrupt+0x1e/0x40
[    7.258472] RIP: 0010:cpuidle_enter_state+0x13e/0x1fe
[    7.258475] Code: 49 89 c4 e8 bd fd ff ff 31 ff e8 3e 80 92 ff 45 84 ff 74 12 9c 58 0f ba e0 09 73 03 0f 0b fa 31 ff e8 13 16 96 ff fb 45 85 f6 <0f> 88 97 00 00 00 49 63 d6 4c 2b 24 24 48 6b ca 68 48 6b c2 30 4c
[    7.258476] RSP: 0018:ffffc90000167eb0 EFLAGS: 00000206
[    7.258477] RAX: ffff88840eca8240 RBX: ffff888101e0d400 RCX: 00000001b0a24b16
[    7.258478] RDX: 0000000000000002 RSI: 0000000000000002 RDI: 0000000000000000
[    7.258478] RBP: 0000000000000003 R08: 00000000ffffffff R09: 0000000000000000
[    7.258479] R10: ffff88810083c4a8 R11: 0000000000000000 R12: 00000001b0a24b48
[    7.258480] R13: ffffffff8299cc60 R14: 0000000000000003 R15: 0000000000000000
[    7.258482]  cpuidle_enter+0x2b/0x37
[    7.258483]  do_idle+0x126/0x184
[    7.258485]  cpu_startup_entry+0x18/0x1a
[    7.258486]  secondary_startup_64_no_verify+0xb0/0xbb
[    7.258489] ---[ end trace 9da59c3696ed99d8 ]---
Quoted 43 lines

---
V2: Fixed the sizeof() as spotted by Mickaël

---
 drivers/rtc/rtc-cmos.c         |    8 ++++++++
 drivers/rtc/rtc-mc146818-lib.c |    7 +++++++
 2 files changed, 15 insertions(+)
drivers/rtc/rtc-cmos.c +8 -0
@@ -805,6 +805,14 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+		spin_unlock_irq(&rtc_lock);
+		dev_warn(dev, "not accessible\n");
+		retval = -ENXIO;
+		goto cleanup1;
+	}
+
 	if (!(flags & CMOS_RTC_FLAGS_NOFREQ)) {
 		/* force periodic irq to CMOS reset default of 1024Hz;
 		 *
drivers/rtc/rtc-mc146818-lib.c +7 -0
@@ -21,6 +21,13 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(*time));
+		return 0;
+	}
+
 	/*
 	 * Check whether there is an update in progress during which the
 	 * readout is unspecified. The maximum update time is ~2ms. Poll
#11 lore raw

Re: [PATCH V2] rtc: mc146818: Detect and handle broken RTCs

Hi! "Me too":

drivers/rtc/rtc-mc146818-lib.c unsigned int mc146818_get_time(struct rt · line 30

Quoted 13 lines
drivers/rtc/rtc-mc146818-lib.c +7 -0
@@ -21,6 +21,13 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(*time));
+		return 0;
+	}
+

... triggers here on a different box (Xiaomi mi notebook air 12.5):

[    3.524002] ------------[ cut here ]------------
[    3.528317] WARNING: CPU: 3 PID: 273 at drivers/rtc/rtc-mc146818-lib.c:25 mc146818_get_time+0x1b6/0x210
[    3.532558] CPU: 3 PID: 273 Comm: udevadm Not tainted 5.11.0-rc6 #760
[    3.536748] Hardware name: Timi TM1612/TM1612, BIOS A04 08/06/2016
[    3.540947] RIP: 0010:mc146818_get_time+0x1b6/0x210
[    3.545103] Code: 76 0b 0f b6 d0 83 ea 13 6b d2 64 01 d5 83 fd 45 89 6b 14 7f 06 83 c5 64 89 6b 14 41 83 ed 01 b8 02 00 00 00 44 89 6b 10 eb 39 <0f> 0b 48 c7 c7 b4 e0 9e 82 48 89 ee e8 29 6b 34 00 48 c7 03 ff ff
[    3.549883] RSP: 0000:ffffc900012efe30 EFLAGS: 00010002
[    3.554387] RAX: 0000000000000081 RBX: ffffc900012efe64 RCX: 000000000005b8d7
[    3.558867] RDX: 0000000000000001 RSI: ffff8881000aa000 RDI: 000000000000000d
[    3.563333] RBP: 0000000000000046 R08: 0000000000000004 R09: fffffffe5e075ac6
[    3.567748] iwlwifi 0000:02:00.0: Applying debug destination EXTERNAL_DRAM
[    3.567822] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000000
[    3.567827] R13: ffffc900012efedc R14: 0000000000000008 R15: ffff888100051200
[    3.577223] FS:  0000000000000000(0000) GS:ffff88816ad80000(0000) knlGS:0000000000000000
[    3.579870] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[    3.581947] CR2: 00007fface455e28 CR3: 0000000103244005 CR4: 00000000003706a0
[    3.583836] Call Trace:
[    3.585699]  hpet_rtc_interrupt+0x1af/0x220
[    3.587585]  __handle_irq_event_percpu+0x5a/0xc0
[    3.589230]  handle_irq_event_percpu+0x1b/0x50
[    3.590673]  handle_irq_event+0x22/0x40
[    3.592107]  handle_edge_irq+0x6b/0x190
[    3.593545]  common_interrupt+0x67/0x130
[    3.594983]  ? asm_common_interrupt+0x8/0x40
[    3.596432]  asm_common_interrupt+0x1e/0x40
[    3.597618] RIP: 0033:0x7ffaceac9b31
[    3.598794] Code: 48 83 fe 0a 0f 87 f5 fe ff ff be 41 ff ff 6f 48 29 d6 48 89 04 f1 e9 e4 fe ff ff 48 85 ff 74 79 49 8b 44 24 60 48 85 c0 74 04 <48> 01 78 08 49 8b 44 24 58 48 85 c0 74 04 48 01 78 08 49 8b 44 24
[    3.600048] RSP: 002b:00007ffc12303b00 EFLAGS: 00010202
[    3.601343] RAX: 00007fface455e20 RBX: 000000006ffffdff RCX: 00007fface80c040
[    3.602587] RDX: 0000000000000000 RSI: 0000000000000029 RDI: 00007fface451000
[    3.603809] RBP: 00007ffc12303c50 R08: 000000006fffffff R09: 00000000effffef5
[    3.605015] R10: 0000000070000022 R11: 0000000000000032 R12: 00007fface80c000
[    3.606223] R13: 000000006ffffeff R14: 000000006ffffe35 R15: 00007ffc12303ce0
[    3.607421] ---[ end trace 5922ddf43b0f7b83 ]---
[    3.608692] hpet: Lost 3 RTC interrupts
#12 lore raw

PATCH 1/1 rtc: mc146818: Dont test for bit 0-5 in Register D

The recent change to validate the RTC turned out to be overly tight.

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

Fixes 211e5db19d15 ("rtc: mc146818: Detect and handle broken RTCs")
---
 drivers/rtc/rtc-cmos.c         |    8 ++++++++
 drivers/rtc/rtc-mc146818-lib.c |    7 +++++++
 2 files changed, 15 insertions(+)
drivers/rtc/rtc-cmos.c +8 -0
@@ -805,6 +805,14 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x40) != 0) {
+		spin_unlock_irq(&rtc_lock);
+		dev_warn(dev, "not accessible\n");
+		retval = -ENXIO;
+		goto cleanup1;
+	}
+
 	if (!(flags & CMOS_RTC_FLAGS_NOFREQ)) {
 		/* force periodic irq to CMOS reset default of 1024Hz;
 		 *
drivers/rtc/rtc-mc146818-lib.c +7 -0
@@ -21,6 +21,13 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x40) != 0)) {
+		spin_unlock_irqrestore(&rtc_lock, flags);
+		memset(time, 0xff, sizeof(*time));
+		return 0;
+	}
+
 	/*
 	 * Check whether there is an update in progress during which the
 	 * readout is unspecified. The maximum update time is ~2ms. Poll
#13 lore raw

PATCH v2 1/1 rtc: mc146818: Dont test for bit 0-5 in Register D

The recent change to validate the RTC turned out to be overly tight.

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

Fixes 211e5db19d15 ("rtc: mc146818: Detect and handle broken RTCs")

---
V2: Provide the actual delta patch. Should have stayed away from
computers today....

---
 drivers/rtc/rtc-cmos.c         |    4 ++--
 drivers/rtc/rtc-mc146818-lib.c |    4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
drivers/rtc/rtc-cmos.c +2 -2
@@ -805,8 +805,8 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
-	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x40) != 0) {
 		spin_unlock_irq(&rtc_lock);
 		dev_warn(dev, "not accessible\n");
 		retval = -ENXIO;
drivers/rtc/rtc-mc146818-lib.c +2 -2
@@ -21,8 +21,8 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
-	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x40) != 0)) {
 		spin_unlock_irqrestore(&rtc_lock, flags);
 		memset(time, 0xff, sizeof(*time));
 		return 0;
#14 lore raw

Re: [PATCH V2] rtc: mc146818: Dont test for bit 0-5 in Register D

Quoted 4 lines · Thomas Gleixner

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

This looks fine, but it might also be worth it simply just checking for the only really special value: 0xff, and going "ok, that looks like missing hardware".

That's what a few other drivers historically do in their probing routines, so it's not unheard of (ie you can find drivers doing that kind of

        /* If we read 0xff from the LSR, there is no UART here. */
        if (inb(.. port ..) == 0xff)

in their init routines.

Not a big deal either way, I just think it would be more in like with what other places do in similar situations

Linus

#15 lore raw

Re: [PATCH V2] rtc: mc146818: Dont test for bit 0-5 in Register D

Quoted 14 lines · Linus Torvalds
Quoted 4 lines · Thomas Gleixner

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

This looks fine, but it might also be worth it simply just checking for the only really special value: 0xff, and going "ok, that looks like missing hardware".

That's what a few other drivers historically do in their probing routines, so it's not unheard of (ie you can find drivers doing that kind of

Quoted 7 lines
        /* If we read 0xff from the LSR, there is no UART here. */
        if (inb(.. port ..) == 0xff)

in their init routines.

Not a big deal either way, I just think it would be more in like with what other places do in similar situations

Yeah, we can do that as well. Either way is fine.

Thanks,

tglx

#16 lore raw

Re: [PATCH V2] rtc: mc146818: Dont test for bit 0-5 in Register D

Quoted 15 lines · Thomas Gleixner
Quoted 15 lines
Quoted 3 lines

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

This looks fine, but it might also be worth it simply just checking for the only really special value: 0xff, and going "ok, that looks like missing hardware".

That's what a few other drivers historically do in their probing routines, so it's not unheard of (ie you can find drivers doing that kind of

        /* If we read 0xff from the LSR, there is no UART here. */
        if (inb(.. port ..) == 0xff)
Quoted 6 lines
Quoted 4 lines

in their init routines.

Not a big deal either way, I just think it would be more in like with what other places do in similar situations

Yeah, we can do that as well. Either way is fine.

Given that evidently vendors appear to start playing with 146818 clones
it may be worth it to peek at the D and the C register and checking they are not 0xff both at a time for robustness before concluding no RTC is present. The C register is supposed to hold zeros in bits 3:0. A read of the C register will drop interrupt bits, but I guess it does not matter at the probe time.

FWIW,

Maciej

maintainer Acked-by on v2 1/1
#17 lore raw

Re: [PATCH V2] rtc: mc146818: Dont test for bit 0-5 in Register D

In reply to Thomas Gleixner
Quoted 10 lines · Thomas Gleixner

The recent change to validate the RTC turned out to be overly tight.

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

Fixes 211e5db19d15 ("rtc: mc146818: Detect and handle broken RTCs")

I'm still fine with that going through your tree.

Thanks for this work I do hope this will be the last issue...

Signature · 3 lines
Alexandre Belloni, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
Tested-by on v2 1/1
#18 lore raw

Re: [PATCH V2] rtc: mc146818: Dont test for bit 0-5 in Register D

In reply to Thomas Gleixner
Quoted 10 lines · Thomas Gleixner

The recent change to validate the RTC turned out to be overly tight.

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

Fixes 211e5db19d15 ("rtc: mc146818: Detect and handle broken RTCs")
Quoted 7 lines

---
V2: Provide the actual delta patch. Should have stayed away from
computers today....

---
 drivers/rtc/rtc-cmos.c         |    4 ++--
 drivers/rtc/rtc-mc146818-lib.c |    4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)

FWIW:

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#19 lore raw

Re: [PATCH V2] rtc: mc146818: Dont test for bit 0-5 in Register D

In reply to Thomas Gleixner
Quoted 6 lines · Thomas Gleixner

The recent change to validate the RTC turned out to be overly tight.

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

Quoted 7 lines
Fixes 211e5db19d15 ("rtc: mc146818: Detect and handle broken RTCs")

---
V2: Provide the actual delta patch. Should have stayed away from
computers today....

I tested V2 and it eliminates the warning, here.

Thank you,

Dirk

Quoted 31 lines
---
 drivers/rtc/rtc-cmos.c         |    4 ++--
 drivers/rtc/rtc-mc146818-lib.c |    4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
drivers/rtc/rtc-cmos.c +2 -2
@@ -805,8 +805,8 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
-	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x40) != 0) {
 		spin_unlock_irq(&rtc_lock);
 		dev_warn(dev, "not accessible\n");
 		retval = -ENXIO;
drivers/rtc/rtc-mc146818-lib.c +2 -2
@@ -21,8 +21,8 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
-	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x40) != 0)) {
 		spin_unlock_irqrestore(&rtc_lock, flags);
 		memset(time, 0xff, sizeof(*time));
 		return 0;
Tested-by on v2 1/1
#20 lore raw

Re: [PATCH V2] rtc: mc146818: Dont test for bit 0-5 in Register D

In reply to Thomas Gleixner

Thanks for the update, Thomas.

V1 prevented rc6 automated suspend/resume testing on all 13 of my local machines.
V2 applied, and they are back in business.

Quoted 45 lines · Thomas Gleixner

The recent change to validate the RTC turned out to be overly tight.

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

Fixes 211e5db19d15 ("rtc: mc146818: Detect and handle broken RTCs")

---
V2: Provide the actual delta patch. Should have stayed away from
computers today....

---
 drivers/rtc/rtc-cmos.c         |    4 ++--
 drivers/rtc/rtc-mc146818-lib.c |    4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
drivers/rtc/rtc-cmos.c +2 -2
@@ -805,8 +805,8 @@ cmos_do_probe(struct device *dev, struct
 
        spin_lock_irq(&rtc_lock);
 
-       /* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-       if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+       /* Ensure that the RTC is accessible. Bit 6 must be 0! */
+       if ((CMOS_READ(RTC_VALID) & 0x40) != 0) {
                spin_unlock_irq(&rtc_lock);
                dev_warn(dev, "not accessible\n");
                retval = -ENXIO;
drivers/rtc/rtc-mc146818-lib.c +2 -2
@@ -21,8 +21,8 @@ unsigned int mc146818_get_time(struct rt
 
 again:
        spin_lock_irqsave(&rtc_lock, flags);
-       /* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-       if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+       /* Ensure that the RTC is accessible. Bit 6 must be 0! */
+       if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x40) != 0)) {
                spin_unlock_irqrestore(&rtc_lock, flags);
                memset(time, 0xff, sizeof(*time));
                return 0;
Signature · 1 line
Len Brown, Intel Open Source Technology Center
#21 lore raw

[tip: timers/urgent] rtc: mc146818: Dont test for bit 0-5 in Register D

In reply to Thomas Gleixner
The following commit has been merged into the timers/urgent branch of tip:

The following commit has been merged into the timers/urgent branch of tip:

Commit-ID:     ebb22a05943666155e6da04407cc6e913974c78c
Gitweb:        https://git.kernel.org/tip/ebb22a05943666155e6da04407cc6e913974c78c
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Mon, 01 Feb 2021 20:24:17 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Tue, 02 Feb 2021 20:35:02 +01:00

rtc: mc146818: Dont test for bit 0-5 in Register D

The recent change to validate the RTC turned out to be overly tight.

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

---
 drivers/rtc/rtc-cmos.c         | 4 ++--
 drivers/rtc/rtc-mc146818-lib.c | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
drivers/rtc/rtc-cmos.c +2 -2
index 68a9ac6..a701dae 100644
@@ -805,8 +805,8 @@ cmos_do_probe(struct device *dev, struct resource *ports, int rtc_irq)
 
 	spin_lock_irq(&rtc_lock);
 
-	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x40) != 0) {
 		spin_unlock_irq(&rtc_lock);
 		dev_warn(dev, "not accessible\n");
 		retval = -ENXIO;
drivers/rtc/rtc-mc146818-lib.c +2 -2
index f83c138..dcfaf09 100644
@@ -21,8 +21,8 @@ unsigned int mc146818_get_time(struct rtc_time *time)
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
-	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x40) != 0)) {
 		spin_unlock_irqrestore(&rtc_lock, flags);
 		memset(time, 0xff, sizeof(*time));
 		return 0;
Tested-by on v2 1/1
#22 lore raw

Re: [PATCH V2] rtc: mc146818: Dont test for bit 0-5 in Register D

In reply to Thomas Gleixner

FWIW, it's still OK for me.

Quoted 45 lines · Thomas Gleixner

The recent change to validate the RTC turned out to be overly tight.

While it cures the problem on the reporters machine it breaks machines with Intel chipsets which use bit 0-5 of the D register. So check only for bit 6 being 0 which is the case on these Intel machines as well.

Fixes 211e5db19d15 ("rtc: mc146818: Detect and handle broken RTCs")

---
V2: Provide the actual delta patch. Should have stayed away from
computers today....

---
 drivers/rtc/rtc-cmos.c         |    4 ++--
 drivers/rtc/rtc-mc146818-lib.c |    4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
drivers/rtc/rtc-cmos.c +2 -2
@@ -805,8 +805,8 @@ cmos_do_probe(struct device *dev, struct
 
 	spin_lock_irq(&rtc_lock);
 
-	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-	if ((CMOS_READ(RTC_VALID) & 0x7f) != 0) {
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if ((CMOS_READ(RTC_VALID) & 0x40) != 0) {
 		spin_unlock_irq(&rtc_lock);
 		dev_warn(dev, "not accessible\n");
 		retval = -ENXIO;
drivers/rtc/rtc-mc146818-lib.c +2 -2
@@ -21,8 +21,8 @@ unsigned int mc146818_get_time(struct rt
 
 again:
 	spin_lock_irqsave(&rtc_lock, flags);
-	/* Ensure that the RTC is accessible. Bit 0-6 must be 0! */
-	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x7f) != 0)) {
+	/* Ensure that the RTC is accessible. Bit 6 must be 0! */
+	if (WARN_ON_ONCE((CMOS_READ(RTC_VALID) & 0x40) != 0)) {
 		spin_unlock_irqrestore(&rtc_lock, flags);
 		memset(time, 0xff, sizeof(*time));
 		return 0;
#23 lore raw

PATCH 2/8 rtc: mc146818: Reduce spinlock section in mc146818_set_time()

In reply to Thomas Gleixner

No need to hold the lock and disable interrupts for doing math.

---
 drivers/rtc/rtc-mc146818-lib.c |    6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/rtc/rtc-mc146818-lib.c +2 -4
@@ -135,7 +135,6 @@ int mc146818_set_time(struct rtc_time *t
 	if (yrs > 255)	/* They are unsigned */
 		return -EINVAL;
 
-	spin_lock_irqsave(&rtc_lock, flags);
 #ifdef CONFIG_MACH_DECSTATION
 	real_yrs = yrs;
 	leap_yr = ((!((yrs + 1900) % 4) && ((yrs + 1900) % 100)) ||
@@ -164,10 +163,8 @@ int mc146818_set_time(struct rtc_time *t
 	/* These limits and adjustments are independent of
 	 * whether the chip is in binary mode or not.
 	 */
-	if (yrs > 169) {
-		spin_unlock_irqrestore(&rtc_lock, flags);
+	if (yrs > 169)
 		return -EINVAL;
-	}
 
 	if (yrs >= 100)
 		yrs -= 100;
@@ -183,6 +180,7 @@ int mc146818_set_time(struct rtc_time *t
 		century = bin2bcd(century);
 	}
 
+	spin_lock_irqsave(&rtc_lock, flags);
 	save_control = CMOS_READ(RTC_CONTROL);
 	CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
 	save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
#24 lore raw

[tip: timers/core] rtc: mc146818: Reduce spinlock section in mc146818_set_time()

The following commit has been merged into the timers/core branch of tip:

The following commit has been merged into the timers/core branch of tip:

Commit-ID:     dcf257e92622ba0e25fdc4b6699683e7ae67e2a1
Gitweb:        https://git.kernel.org/tip/dcf257e92622ba0e25fdc4b6699683e7ae67e2a1
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Sun, 06 Dec 2020 22:46:15 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Fri, 11 Dec 2020 10:40:52 +01:00

rtc: mc146818: Reduce spinlock section in mc146818_set_time()

No need to hold the lock and disable interrupts for doing math.

---
 drivers/rtc/rtc-mc146818-lib.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/rtc/rtc-mc146818-lib.c +2 -4
index 98048bb..972a5b9 100644
@@ -135,7 +135,6 @@ int mc146818_set_time(struct rtc_time *time)
 	if (yrs > 255)	/* They are unsigned */
 		return -EINVAL;
 
-	spin_lock_irqsave(&rtc_lock, flags);
 #ifdef CONFIG_MACH_DECSTATION
 	real_yrs = yrs;
 	leap_yr = ((!((yrs + 1900) % 4) && ((yrs + 1900) % 100)) ||
@@ -164,10 +163,8 @@ int mc146818_set_time(struct rtc_time *time)
 	/* These limits and adjustments are independent of
 	 * whether the chip is in binary mode or not.
 	 */
-	if (yrs > 169) {
-		spin_unlock_irqrestore(&rtc_lock, flags);
+	if (yrs > 169)
 		return -EINVAL;
-	}
 
 	if (yrs >= 100)
 		yrs -= 100;
@@ -183,6 +180,7 @@ int mc146818_set_time(struct rtc_time *time)
 		century = bin2bcd(century);
 	}
 
+	spin_lock_irqsave(&rtc_lock, flags);
 	save_control = CMOS_READ(RTC_CONTROL);
 	CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
 	save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
#25 lore raw

PATCH 3/8 rtc: cmos: Make rtc_cmos sync offset correct

In reply to Thomas Gleixner

The offset for rtc_cmos must be -500ms to work correctly with the current implementation of rtc_set_ntp_time() due to the following:

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

twrite - tsched is the transport time for the write to hit the device, which is negligible for this chip because it's accessed directly.

t2 - twrite = 500ms according to the datasheet.

But rtc_set_ntp_time() calculation of tsched is:

    tsched = t2 - 1sec - (t2 - twrite)

The default for the sync offset is 500ms which means that the write happens at t2 - 1.5 seconds which is obviously off by a second for this device.

Make the offset -500ms so it works correct.

---
 drivers/rtc/rtc-cmos.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/rtc/rtc-cmos.c +3 -0
@@ -868,6 +868,9 @@ cmos_do_probe(struct device *dev, struct
 	if (retval)
 		goto cleanup2;
 
+	/* Set the sync offset for the periodic 11min update correct */
+	cmos_rtc.rtc->set_offset_nsec = -(NSEC_PER_SEC / 2);
+
 	/* export at least the first block of NVRAM */
 	nvmem_cfg.size = address_space - NVRAM_OFFSET;
 	if (rtc_nvmem_register(cmos_rtc.rtc, &nvmem_cfg))
Reviewed-by on v1 3/8
#26 lore raw

Re: [patch 3/8] rtc: cmos: Make rtc_cmos sync offset correct

Quoted 17 lines · Thomas Gleixner

The offset for rtc_cmos must be -500ms to work correctly with the current implementation of rtc_set_ntp_time() due to the following:

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

twrite - tsched is the transport time for the write to hit the device, which is negligible for this chip because it's accessed directly.

t2 - twrite = 500ms according to the datasheet.

But rtc_set_ntp_time() calculation of tsched is:

    tsched = t2 - 1sec - (t2 - twrite)

The default for the sync offset is 500ms which means that the write happens at t2 - 1.5 seconds which is obviously off by a second for this device.

Quoted 6 lines

Make the offset -500ms so it works correct.

---
 drivers/rtc/rtc-cmos.c |    3 +++
 1 file changed, 3 insertions(+)

Matches what sync_cmos_clock() does at least.

My recollection is this change was not supposed to change anything, so either I got things mixed up and this is wrong:

drivers/rtc/class.c: rtc->set_offset_nsec = NSEC_PER_SEC / 2;

Or it faithfully preserved some nonsense from before..

Jason

#27 lore raw

[tip: timers/core] rtc: cmos: Make rtc_cmos sync offset correct

In reply to Thomas Gleixner
The following commit has been merged into the timers/core branch of tip:

The following commit has been merged into the timers/core branch of tip:

Commit-ID:     b0ecd8e8c5ef376777277c4c2db7de92ac59f23f
Gitweb:        https://git.kernel.org/tip/b0ecd8e8c5ef376777277c4c2db7de92ac59f23f
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Sun, 06 Dec 2020 22:46:16 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Fri, 11 Dec 2020 10:40:52 +01:00

rtc: cmos: Make rtc_cmos sync offset correct

The offset for rtc_cmos must be -500ms to work correctly with the current implementation of rtc_set_ntp_time() due to the following:

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

twrite - tsched is the transport time for the write to hit the device, which is negligible for this chip because it's accessed directly.

t2 - twrite = 500ms according to the datasheet.

But rtc_set_ntp_time() calculation of tsched is:

    tsched = t2 - 1sec - (t2 - twrite)

The default for the sync offset is 500ms which means that the write happens at t2 - 1.5 seconds which is obviously off by a second for this device.

Make the offset -500ms so it works correct.

---
 drivers/rtc/rtc-cmos.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/rtc/rtc-cmos.c +3 -0
index c633319..7728fac 100644
@@ -868,6 +868,9 @@ cmos_do_probe(struct device *dev, struct resource *ports, int rtc_irq)
 	if (retval)
 		goto cleanup2;
 
+	/* Set the sync offset for the periodic 11min update correct */
+	cmos_rtc.rtc->set_offset_nsec = -(NSEC_PER_SEC / 2);
+
 	/* export at least the first block of NVRAM */
 	nvmem_cfg.size = address_space - NVRAM_OFFSET;
 	if (rtc_nvmem_register(cmos_rtc.rtc, &nvmem_cfg))
#28 lore raw

PATCH 4/8 rtc: core: Make the sync offset default more realistic

In reply to Thomas Gleixner

The offset which is used to steer the start of an RTC synchronization update via rtc_set_ntp_time() is huge. The math behind this is:

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

twrite - tsched is the transport time for the write to hit the device.

t2 - twrite depends on the chip and is for most chips one second.

The rtc_set_ntp_time() calculation of tsched is:

    tsched = t2 - 1sec - (t2 - twrite)

The default for the sync offset is 500ms which means that twrite - tsched is 500ms assumed that t2 - twrite is one second.

This is 0.5 seconds off for RTCs which are directly accessible by IO writes and probably for the majority of i2C/SPI based RTC off by an order of magnitude. Set it to 10ms which should bring it closer to reality.

The default can be adjusted by drivers (rtc_cmos does so) and could be adjusted further by a calibration method which is an orthogonal problem.

---
 drivers/rtc/class.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/rtc/class.c +1 -1
@@ -201,7 +201,7 @@ static struct rtc_device *rtc_allocate_d
 	device_initialize(&rtc->dev);
 
 	/* Drivers can revise this default after allocating the device. */
-	rtc->set_offset_nsec =  NSEC_PER_SEC / 2;
+	rtc->set_offset_nsec =  10 * NSEC_PER_MSEC;
 
 	rtc->irq_freq = 1;
 	rtc->max_user_freq = 64;
Reviewed-by on v1 4/8
#29 lore raw

Re: [patch 4/8] rtc: core: Make the sync offset default more realistic

Quoted 29 lines · Thomas Gleixner

The offset which is used to steer the start of an RTC synchronization update via rtc_set_ntp_time() is huge. The math behind this is:

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

twrite - tsched is the transport time for the write to hit the device.

t2 - twrite depends on the chip and is for most chips one second.

The rtc_set_ntp_time() calculation of tsched is:

    tsched = t2 - 1sec - (t2 - twrite)

The default for the sync offset is 500ms which means that twrite - tsched is 500ms assumed that t2 - twrite is one second.

This is 0.5 seconds off for RTCs which are directly accessible by IO writes and probably for the majority of i2C/SPI based RTC off by an order of magnitude. Set it to 10ms which should bring it closer to reality.

The default can be adjusted by drivers (rtc_cmos does so) and could be adjusted further by a calibration method which is an orthogonal problem.

 drivers/rtc/class.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

+++ b/drivers/rtc/class.c

drivers/rtc/class.c static struct rtc_device *rtc_allocate_d · line 204

Quoted 5 lines
drivers/rtc/class.c +1 -1
@@ -201,7 +201,7 @@ static struct rtc_device *rtc_allocate_d
 	device_initialize(&rtc->dev);
 
 	/* Drivers can revise this default after allocating the device. */
-	rtc->set_offset_nsec =  NSEC_PER_SEC / 2;
+	rtc->set_offset_nsec =  10 * NSEC_PER_MSEC;

So the old value is clearly wrong for CMOS, and I have a strong feeling this was an error and it should have been -NSEC_PER_SEC/2

I have no idea if CMOS behavior or 0s behavior is more common in the rtclib drivers, but it seems since nobody noticed the huge offset mistake in 3 years it doesn't actually really matter.

Jason

maintainer Acked-by on v1 4/8
#30 lore raw

Re: [patch 4/8] rtc: core: Make the sync offset default more realistic

In reply to Thomas Gleixner

Hi,

Quoted 31 lines · Thomas Gleixner

The offset which is used to steer the start of an RTC synchronization update via rtc_set_ntp_time() is huge. The math behind this is:

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

twrite - tsched is the transport time for the write to hit the device.

t2 - twrite depends on the chip and is for most chips one second.

The rtc_set_ntp_time() calculation of tsched is:

    tsched = t2 - 1sec - (t2 - twrite)

The default for the sync offset is 500ms which means that twrite - tsched is 500ms assumed that t2 - twrite is one second.

This is 0.5 seconds off for RTCs which are directly accessible by IO writes and probably for the majority of i2C/SPI based RTC off by an order of magnitude. Set it to 10ms which should bring it closer to reality.

The default can be adjusted by drivers (rtc_cmos does so) and could be adjusted further by a calibration method which is an orthogonal problem.

---
 drivers/rtc/class.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

drivers/rtc/class.c static struct rtc_device *rtc_allocate_d · line 204

Quoted 5 lines
drivers/rtc/class.c +1 -1
@@ -201,7 +201,7 @@ static struct rtc_device *rtc_allocate_d
 	device_initialize(&rtc->dev);
 
 	/* Drivers can revise this default after allocating the device. */
-	rtc->set_offset_nsec =  NSEC_PER_SEC / 2;
+	rtc->set_offset_nsec =  10 * NSEC_PER_MSEC;

I did retest, on a slow 100kHz i2c bus, with a fairly inconvenient RTC, The maximum offset to set the RTC was 4845533ns so I'd say 10ms is too large. Should we make that 5ms ?

Apart from that, on the series, you can add my

Signature · 3 lines
Alexandre Belloni, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#31 lore raw

Re: [patch 4/8] rtc: core: Make the sync offset default more realistic

Alexandre,

Quoted 8 lines · Alexandre Belloni

drivers/rtc/class.c static struct rtc_device *rtc_allocate_d · line 204

Quoted 3 lines · Thomas Gleixner
drivers/rtc/class.c +1 -1
 	/* Drivers can revise this default after allocating the device. */
-	rtc->set_offset_nsec =  NSEC_PER_SEC / 2;
+	rtc->set_offset_nsec =  10 * NSEC_PER_MSEC;

I did retest, on a slow 100kHz i2c bus, with a fairly inconvenient RTC, The maximum offset to set the RTC was 4845533ns so I'd say 10ms is too large. Should we make that 5ms ?

Sure. As I said I pulled the 10 out of thin air.

Quoted 2 lines

Apart from that, on the series, you can add my

I'll amend the s/10/5/ throughout the series while queueing the whole pile in the timers/core branch unless you want it to be handled differently.

Thanks,

tglx

#32 lore raw

Re: [patch 4/8] rtc: core: Make the sync offset default more realistic

Quoted 12 lines · Thomas Gleixner

Alexandre,

Quoted 8 lines · Alexandre Belloni

drivers/rtc/class.c static struct rtc_device *rtc_allocate_d · line 204

Quoted 3 lines · Thomas Gleixner
drivers/rtc/class.c +1 -1
 	/* Drivers can revise this default after allocating the device. */
-	rtc->set_offset_nsec =  NSEC_PER_SEC / 2;
+	rtc->set_offset_nsec =  10 * NSEC_PER_MSEC;

I did retest, on a slow 100kHz i2c bus, with a fairly inconvenient RTC, The maximum offset to set the RTC was 4845533ns so I'd say 10ms is too large. Should we make that 5ms ?

Quoted 9 lines

Sure. As I said I pulled the 10 out of thin air.

Quoted 2 lines

Apart from that, on the series, you can add my

I'll amend the s/10/5/ throughout the series while queueing the whole pile in the timers/core branch unless you want it to be handled differently.

That's fine for me.

Signature · 3 lines
Alexandre Belloni, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#33 lore raw

[tip: timers/core] rtc: core: Make the sync offset default more realistic

In reply to Thomas Gleixner
The following commit has been merged into the timers/core branch of tip:

The following commit has been merged into the timers/core branch of tip:

Commit-ID:     354c796b9270eb4780e59e3bdb83a3ae4930a832
Gitweb:        https://git.kernel.org/tip/354c796b9270eb4780e59e3bdb83a3ae4930a832
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Sun, 06 Dec 2020 22:46:17 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Fri, 11 Dec 2020 10:40:52 +01:00

rtc: core: Make the sync offset default more realistic

The offset which is used to steer the start of an RTC synchronization update via rtc_set_ntp_time() is huge. The math behind this is:

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

twrite - tsched is the transport time for the write to hit the device.

t2 - twrite depends on the chip and is for most chips one second.

The rtc_set_ntp_time() calculation of tsched is:

    tsched = t2 - 1sec - (t2 - twrite)

The default for the sync offset is 500ms which means that twrite - tsched is 500ms assumed that t2 - twrite is one second.

This is 0.5 seconds off for RTCs which are directly accessible by IO writes and probably for the majority of i2C/SPI based RTC off by an order of magnitude. Set it to 5ms which should bring it closer to reality.

The default can be adjusted by drivers (rtc_cmos does so) and could be adjusted further by a calibration method which is an orthogonal problem.

---
 drivers/rtc/class.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/rtc/class.c +1 -1
index 7c88d19..d795737 100644
@@ -201,7 +201,7 @@ static struct rtc_device *rtc_allocate_device(void)
 	device_initialize(&rtc->dev);
 
 	/* Drivers can revise this default after allocating the device. */
-	rtc->set_offset_nsec =  NSEC_PER_SEC / 2;
+	rtc->set_offset_nsec =  5 * NSEC_PER_MSEC;
 
 	rtc->irq_freq = 1;
 	rtc->max_user_freq = 64;
#34 lore raw

PATCH 5/8 ntp: Make the RTC synchronization more reliable

In reply to Thomas Gleixner

Miroslav reported that the periodic RTC synchronization in the NTP code fails more often than not to hit the specified update window.

The reason is that the code uses delayed_work to schedule the update which needs to be in thread context as the underlying RTC might be connected via a slow bus, e.g. I2C. In the update function it verifies whether the current time is correct vs. the requirements of the underlying RTC.

But delayed_work is using the timer wheel for scheduling which is inaccurate by design. Depending on the distance to the expiry the wheel gets less granular to allow batching and to avoid the cascading of the original timer wheel. See 500462a9de65 ("timers: Switch to a non-cascading wheel") and the code for further details.

The code already deals with this by splitting the 660 seconds period into a long 659 seconds timer and then retrying with a smaller delta.

But looking at the actual granularities of the timer wheel (which depend on the HZ configuration) the 659 seconds timer ends up in an outer wheel level and is affected by a worst case granularity of:

HZ          Granularity
1000        32s
 250        16s
 100        40s

So the initial timer can be already off by max 12.5% which is not a big issue as the period of the sync is defined as ~11 minutes.

The fine grained second attempt schedules to the desired update point with a timer expiring less than a second from now. Depending on the actual delta and the HZ setting even the second attempt can end up in outer wheel levels which have a large enough granularity to make the correctness check fail.

As this is a fundamental property of the timer wheel there is no way to make this more accurate short of iterating in one jiffies steps towards the update point.

Switch it to an hrtimer instead which schedules the actual update work. The hrtimer will expire precisely (max 1 jiffie delay when high resolution timers are not available). The actual scheduling delay of the work is the same as before.

The update is triggered from do_adjtimex() which is a bit racy but not much more racy than it was before:

     if (ntp_synced())
     	queue_delayed_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the work is currently executed and has not managed to reschedule itself.

This becomes now:

     if (ntp_synced() && !hrtimer_is_queued(&sync_hrtimer))
     	queue_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the hrtimer has expired and the work is currently executed and has not yet managed to rearm the hrtimer.

Not a big problem as it just schedules work for nothing.

The new implementation has a safe guard in place to catch the case where the hrtimer is queued on entry to the work function and avoids an extra update attempt of the RTC that way.

Cc John Stultz <[email protected]>
Cc Prarit Bhargava <[email protected]>
Cc Jason Gunthorpe <[email protected]>
---
 include/linux/timex.h      |    1 
 kernel/time/ntp.c          |   90 ++++++++++++++++++++++++---------------------
 kernel/time/ntp_internal.h |    7 +++
 3 files changed, 55 insertions(+), 43 deletions(-)
include/linux/timex.h +0 -1
@@ -157,7 +157,6 @@ extern int do_clock_adjtime(const clocki
 extern void hardpps(const struct timespec64 *, const struct timespec64 *);
 
 int read_current_timer(unsigned long *timer_val);
-void ntp_notify_cmos_timer(void);
 
 /* The clock frequency of the i8253/i8254 PIT */
 #define PIT_TICK_RATE 1193182ul
kernel/time/ntp.c +48 -42

144 lines not on this page · raw message

kernel/time/ntp_internal.h +7 -0
@@ -12,4 +12,11 @@ extern int __do_adjtimex(struct __kernel
 			 const struct timespec64 *ts,
 			 s32 *time_tai, struct audit_ntp_data *ad);
 extern void __hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts);
+
+#if defined(CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC)
+extern void ntp_notify_cmos_timer(void);
+#else
+static inline void ntp_notify_cmos_timer(void) { }
+#endif
+
 #endif /* _LINUX_NTP_INTERNAL_H */
reviewer Tested-by on v1 5/8
#35 lore raw

Re: [patch 5/8] ntp: Make the RTC synchronization more reliable

Quoted 4 lines · Thomas Gleixner

Switch it to an hrtimer instead which schedules the actual update work. The hrtimer will expire precisely (max 1 jiffie delay when high resolution timers are not available). The actual scheduling delay of the work is the same as before.

It works well in my tests.

Quoted 9 lines

This becomes now:

     if (ntp_synced() && !hrtimer_is_queued(&sync_hrtimer))
     	queue_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the hrtimer has expired and the work is currently executed and has not yet managed to rearm the hrtimer.

Not a big problem as it just schedules work for nothing.

No more unexpected updates of the RTC observed.

Thanks,

Signature · 1 line
Miroslav Lichvar
Reviewed-by on v1 5/8
#36 lore raw

Re: [patch 5/8] ntp: Make the RTC synchronization more reliable

In reply to Thomas Gleixner
Quoted 71 lines · Thomas Gleixner

Miroslav reported that the periodic RTC synchronization in the NTP code fails more often than not to hit the specified update window.

The reason is that the code uses delayed_work to schedule the update which needs to be in thread context as the underlying RTC might be connected via a slow bus, e.g. I2C. In the update function it verifies whether the current time is correct vs. the requirements of the underlying RTC.

But delayed_work is using the timer wheel for scheduling which is inaccurate by design. Depending on the distance to the expiry the wheel gets less granular to allow batching and to avoid the cascading of the original timer wheel. See 500462a9de65 ("timers: Switch to a non-cascading wheel") and the code for further details.

The code already deals with this by splitting the 660 seconds period into a long 659 seconds timer and then retrying with a smaller delta.

But looking at the actual granularities of the timer wheel (which depend on the HZ configuration) the 659 seconds timer ends up in an outer wheel level and is affected by a worst case granularity of:

HZ          Granularity
1000        32s
 250        16s
 100        40s

So the initial timer can be already off by max 12.5% which is not a big issue as the period of the sync is defined as ~11 minutes.

The fine grained second attempt schedules to the desired update point with a timer expiring less than a second from now. Depending on the actual delta and the HZ setting even the second attempt can end up in outer wheel levels which have a large enough granularity to make the correctness check fail.

As this is a fundamental property of the timer wheel there is no way to make this more accurate short of iterating in one jiffies steps towards the update point.

Switch it to an hrtimer instead which schedules the actual update work. The hrtimer will expire precisely (max 1 jiffie delay when high resolution timers are not available). The actual scheduling delay of the work is the same as before.

The update is triggered from do_adjtimex() which is a bit racy but not much more racy than it was before:

     if (ntp_synced())
     	queue_delayed_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the work is currently executed and has not managed to reschedule itself.

This becomes now:

     if (ntp_synced() && !hrtimer_is_queued(&sync_hrtimer))
     	queue_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the hrtimer has expired and the work is currently executed and has not yet managed to rearm the hrtimer.

Not a big problem as it just schedules work for nothing.

The new implementation has a safe guard in place to catch the case where the hrtimer is queued on entry to the work function and avoids an extra update attempt of the RTC that way.

Cc John Stultz <[email protected]>
Cc Prarit Bhargava <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Quoted 5 lines
---
 include/linux/timex.h      |    1 
 kernel/time/ntp.c          |   90 ++++++++++++++++++++++++---------------------
 kernel/time/ntp_internal.h |    7 +++
 3 files changed, 55 insertions(+), 43 deletions(-)

Jason

#37 lore raw

[tip: timers/core] ntp: Make the RTC synchronization more reliable

In reply to Thomas Gleixner
The following commit has been merged into the timers/core branch of tip:

The following commit has been merged into the timers/core branch of tip:

Commit-ID:     c9e6189fb03123a7dfb93589280347b46f30b161
Gitweb:        https://git.kernel.org/tip/c9e6189fb03123a7dfb93589280347b46f30b161
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Sun, 06 Dec 2020 22:46:18 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Fri, 11 Dec 2020 10:40:52 +01:00

ntp: Make the RTC synchronization more reliable

Miroslav reported that the periodic RTC synchronization in the NTP code fails more often than not to hit the specified update window.

The reason is that the code uses delayed_work to schedule the update which needs to be in thread context as the underlying RTC might be connected via a slow bus, e.g. I2C. In the update function it verifies whether the current time is correct vs. the requirements of the underlying RTC.

But delayed_work is using the timer wheel for scheduling which is inaccurate by design. Depending on the distance to the expiry the wheel gets less granular to allow batching and to avoid the cascading of the original timer wheel. See 500462a9de65 ("timers: Switch to a non-cascading wheel") and the code for further details.

The code already deals with this by splitting the 660 seconds period into a long 659 seconds timer and then retrying with a smaller delta.

But looking at the actual granularities of the timer wheel (which depend on the HZ configuration) the 659 seconds timer ends up in an outer wheel level and is affected by a worst case granularity of:

HZ          Granularity
1000        32s
 250        16s
 100        40s

So the initial timer can be already off by max 12.5% which is not a big issue as the period of the sync is defined as ~11 minutes.

The fine grained second attempt schedules to the desired update point with a timer expiring less than a second from now. Depending on the actual delta and the HZ setting even the second attempt can end up in outer wheel levels which have a large enough granularity to make the correctness check fail.

As this is a fundamental property of the timer wheel there is no way to make this more accurate short of iterating in one jiffies steps towards the update point.

Switch it to an hrtimer instead which schedules the actual update work. The hrtimer will expire precisely (max 1 jiffie delay when high resolution timers are not available). The actual scheduling delay of the work is the same as before.

The update is triggered from do_adjtimex() which is a bit racy but not much more racy than it was before:

     if (ntp_synced())
     	queue_delayed_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the work is currently executed and has not managed to reschedule itself.

This becomes now:

     if (ntp_synced() && !hrtimer_is_queued(&sync_hrtimer))
     	queue_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the hrtimer has expired and the work is currently executed and has not yet managed to rearm the hrtimer.

Not a big problem as it just schedules work for nothing.

The new implementation has a safe guard in place to catch the case where the hrtimer is queued on entry to the work function and avoids an extra update attempt of the RTC that way.

---
 include/linux/timex.h      |  1 +-
 kernel/time/ntp.c          | 90 +++++++++++++++++++------------------
 kernel/time/ntp_internal.h |  7 +++-
 3 files changed, 55 insertions(+), 43 deletions(-)
include/linux/timex.h +0 -1
index ce08597..9c2e54f 100644
@@ -157,7 +157,6 @@ extern int do_clock_adjtime(const clockid_t which_clock, struct __kernel_timex *
 extern void hardpps(const struct timespec64 *, const struct timespec64 *);
 
 int read_current_timer(unsigned long *timer_val);
-void ntp_notify_cmos_timer(void);
 
 /* The clock frequency of the i8253/i8254 PIT */
 #define PIT_TICK_RATE 1193182ul
kernel/time/ntp.c +48 -42

144 lines not on this page · raw message

kernel/time/ntp_internal.h +7 -0
index 908ecaa..23d1b74 100644
@@ -12,4 +12,11 @@ extern int __do_adjtimex(struct __kernel_timex *txc,
 			 const struct timespec64 *ts,
 			 s32 *time_tai, struct audit_ntp_data *ad);
 extern void __hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts);
+
+#if defined(CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC)
+extern void ntp_notify_cmos_timer(void);
+#else
+static inline void ntp_notify_cmos_timer(void) { }
+#endif
+
 #endif /* _LINUX_NTP_INTERNAL_H */
#38 lore raw

Re: [patch 5/8] ntp: Make the RTC synchronization more reliable

In reply to Thomas Gleixner

Hi Thomas,

Quoted 60 lines · Thomas Gleixner

Miroslav reported that the periodic RTC synchronization in the NTP code fails more often than not to hit the specified update window.

The reason is that the code uses delayed_work to schedule the update which needs to be in thread context as the underlying RTC might be connected via a slow bus, e.g. I2C. In the update function it verifies whether the current time is correct vs. the requirements of the underlying RTC.

But delayed_work is using the timer wheel for scheduling which is inaccurate by design. Depending on the distance to the expiry the wheel gets less granular to allow batching and to avoid the cascading of the original timer wheel. See 500462a9de65 ("timers: Switch to a non-cascading wheel") and the code for further details.

The code already deals with this by splitting the 660 seconds period into a long 659 seconds timer and then retrying with a smaller delta.

But looking at the actual granularities of the timer wheel (which depend on the HZ configuration) the 659 seconds timer ends up in an outer wheel level and is affected by a worst case granularity of:

HZ          Granularity
1000        32s
 250        16s
 100        40s

So the initial timer can be already off by max 12.5% which is not a big issue as the period of the sync is defined as ~11 minutes.

The fine grained second attempt schedules to the desired update point with a timer expiring less than a second from now. Depending on the actual delta and the HZ setting even the second attempt can end up in outer wheel levels which have a large enough granularity to make the correctness check fail.

As this is a fundamental property of the timer wheel there is no way to make this more accurate short of iterating in one jiffies steps towards the update point.

Switch it to an hrtimer instead which schedules the actual update work. The hrtimer will expire precisely (max 1 jiffie delay when high resolution timers are not available). The actual scheduling delay of the work is the same as before.

The update is triggered from do_adjtimex() which is a bit racy but not much more racy than it was before:

     if (ntp_synced())
        queue_delayed_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the work is currently executed and has not managed to reschedule itself.

This becomes now:

     if (ntp_synced() && !hrtimer_is_queued(&sync_hrtimer))
        queue_work(system_power_efficient_wq, &sync_work, 0);

which is racy when the hrtimer has expired and the work is currently executed and has not yet managed to rearm the hrtimer.

Quoted 8 lines

Not a big problem as it just schedules work for nothing.

The new implementation has a safe guard in place to catch the case where the hrtimer is queued on entry to the work function and avoids an extra update attempt of the RTC that way.

Thanks for your patch, which is now commit c9e6189fb03123a7 ("ntp: Make the RTC synchronization more reliable").

Since this commit, the I2C RTC on the R-Car M2-W Koelsch development board is accessed every two seconds. Sticking a WARN() in the I2C activation path gives e.g.

    Modules linked in:
    CPU: 0 PID: 12 Comm: kworker/0:1 Not tainted
5.10.0-rc1-koelsch-00038-gc9e6189fb031-dirty #1021
    Hardware name: Generic R-Car Gen2 (Flattened Device Tree)
    Workqueue: events rtc_timer_do_work
    [<c020ea7c>] (unwind_backtrace) from [<c020a4dc>] (show_stack+0x10/0x14)
    [<c020a4dc>] (show_stack) from [<c090e314>] (dump_stack+0xa0/0xc8)
    [<c090e314>] (dump_stack) from [<c02228a8>] (__warn+0xbc/0xfc)
    [<c02228a8>] (__warn) from [<c090b434>] (warn_slowpath_fmt+0x78/0xb0)
    [<c090b434>] (warn_slowpath_fmt) from [<c058f184>]
(cpg_mstp_clock_endisable+0x94/0x1f4)
    [<c058f184>] (cpg_mstp_clock_endisable) from [<c05881c8>]
(clk_core_enable+0x194/0x29c)
    [<c05881c8>] (clk_core_enable) from [<c05882e8>]
(clk_core_enable_lock+0x18/0x2c)
    [<c05882e8>] (clk_core_enable_lock) from [<c063b5c4>]
(pm_clk_resume+0x68/0xa0)
    [<c063b5c4>] (pm_clk_resume) from [<c063a738>]
(genpd_runtime_resume+0xc8/0x174)
    [<c063a738>] (genpd_runtime_resume) from [<c063236c>]
(__rpm_callback+0x30/0xe0)
    [<c063236c>] (__rpm_callback) from [<c063248c>] (rpm_callback+0x70/0x80)
    [<c063248c>] (rpm_callback) from [<c063216c>] (rpm_resume+0x438/0x4dc)
    [<c063216c>] (rpm_resume) from [<c0632274>] (__pm_runtime_resume+0x64/0x80)
    [<c0632274>] (__pm_runtime_resume) from [<c0731ab4>]
(sh_mobile_i2c_xfer+0x38/0x554)
    [<c0731ab4>] (sh_mobile_i2c_xfer) from [<c072a6c4>]
(__i2c_transfer+0x4e4/0x680)
    [<c072a6c4>] (__i2c_transfer) from [<c072a8b8>] (i2c_transfer+0x58/0xf8)
    [<c072a8b8>] (i2c_transfer) from [<c0645688>] (regmap_i2c_read+0x58/0x94)
    [<c0645688>] (regmap_i2c_read) from [<c0641490>]
(_regmap_raw_read+0x19c/0x2f4)
    [<c0641490>] (_regmap_raw_read) from [<c064162c>]
(_regmap_bus_read+0x44/0x68)
    [<c064162c>] (_regmap_bus_read) from [<c0640308>] (_regmap_read+0x84/0x1a4)
    [<c0640308>] (_regmap_read) from [<c0640984>]
(_regmap_update_bits+0xa8/0xf4)
    [<c0640984>] (_regmap_update_bits) from [<c0641b5c>]
(regmap_update_bits_base+0x4c/0x70)
    [<c0641b5c>] (regmap_update_bits_base) from [<c0728244>]
(regmap_update_bits+0x18/0x20)
    [<c0728244>] (regmap_update_bits) from [<c072491c>]
(rtc_alarm_disable+0x28/0x38)
    [<c072491c>] (rtc_alarm_disable) from [<c0726408>]
(rtc_timer_do_work+0x88/0x294)
    [<c0726408>] (rtc_timer_do_work) from [<c023e27c>]
(process_one_work+0x308/0x524)
    [<c023e27c>] (process_one_work) from [<c023ec80>]
(worker_thread+0x22c/0x2ec)
    [<c023ec80>] (worker_thread) from [<c024417c>] (kthread+0x128/0x138)
    [<c024417c>] (kthread) from [<c020010c>] (ret_from_fork+0x14/0x28)
    Exception stack(0xc220ffb0 to 0xc220fff8)
    ffa0:                                     00000000 00000000
00000000 00000000
    ffc0: 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000
    ffe0: 00000000 00000000 00000000 00000000 00000013 00000000
    irq event stamp: 74448
    hardirqs last  enabled at (74447): [<c02a5f90>]
seqcount_lockdep_reader_access.constprop.0+0x58/0x68
    hardirqs last disabled at (74448): [<c0919a68>]
_raw_spin_lock_irqsave+0x20/0x70
    softirqs last  enabled at (74360): [<c02012b0>] __do_softirq+0x1b8/0x468
    softirqs last disabled at (74353): [<c0228f24>] __irq_exit_rcu+0x110/0x17c
    ---[ end trace 8c279400e5758606 ]---

Before, the synchronization happened only every 696s.

Worse, this synchronization may also happen while the system is partly suspended, sometimes triggering a WARNING during resume from s2ram:

Disabling non-boot CPUs ...
Enabling non-boot CPUs ...
+------------[ cut here ]------------ +WARNING: CPU: 0 PID: 21 at drivers/i2c/i2c-core.h:54

__i2c_transfer+0x464/0x4a0
    +i2c i2c-6: Transfer while suspended
    +CPU: 0 PID: 21 Comm: kworker/0:1 Not tainted
5.11.0-rc1-shmobile-00107-gcf9760aa181f #829
    +Hardware name: Generic R-Car Gen2 (Flattened Device Tree)
    +Workqueue: events_power_efficient sync_hw_clock
    +[<c010dba4>] (unwind_backtrace) from [<c0109b28>] (show_stack+0x10/0x14)
    +[<c0109b28>] (show_stack) from [<c07a120c>] (dump_stack+0x8c/0xa8)
    +[<c07a120c>] (dump_stack) from [<c011c538>] (__warn+0xc0/0xec)
    +[<c011c538>] (__warn) from [<c079a7bc>] (warn_slowpath_fmt+0x78/0xb0)
    +[<c079a7bc>] (warn_slowpath_fmt) from [<c0566574>]
(__i2c_transfer+0x464/0x4a0)
    +[<c0566574>] (__i2c_transfer) from [<c0566608>] (i2c_transfer+0x58/0xf8)
    +[<c0566608>] (i2c_transfer) from [<c0489f80>] (regmap_i2c_read+0x58/0x94)
    +[<c0489f80>] (regmap_i2c_read) from [<c0485e00>]
(_regmap_raw_read+0x108/0x1bc)
    +[<c0485e00>] (_regmap_raw_read) from [<c0485ef8>]
(_regmap_bus_read+0x44/0x68)
    +[<c0485ef8>] (_regmap_bus_read) from [<c0484018>] (_regmap_read+0x84/0x100)
    +[<c0484018>] (_regmap_read) from [<c0485444>]
(_regmap_update_bits+0xa8/0xf4)
    +[<c0485444>] (_regmap_update_bits) from [<c0485574>]
    (_regmap_select_page+0xe4/0x100)
    +[<c0485574>] (_regmap_select_page) from [<c0485664>]
    (_regmap_raw_write_impl+0xd4/0x608)
    +[<c0485664>] (_regmap_raw_write_impl) from [<c04863f4>]
    (_regmap_raw_write+0xd8/0x114)
    +[<c04863f4>] (_regmap_raw_write) from [<c0486488>]
(regmap_raw_write+0x58/0x7c)
    +[<c0486488>] (regmap_raw_write) from [<c04866cc>]
    (regmap_bulk_write+0x118/0x13c)
    +[<c04866cc>] (regmap_bulk_write) from [<c05605b4>]
    (da9063_rtc_set_time+0x44/0x8c)
    +[<c05605b4>] (da9063_rtc_set_time) from [<c055e428>]
(rtc_set_time+0x8c/0x15c)
    +[<c055e428>] (rtc_set_time) from [<c01872cc>] (sync_hw_clock+0x12c/0x210)
    +[<c01872cc>] (sync_hw_clock) from [<c01337d0>]
(process_one_work+0x1bc/0x2ac)
    +[<c01337d0>] (process_one_work) from [<c0133b18>]
(worker_thread+0x22c/0x2d0)
    +[<c0133b18>] (worker_thread) from [<c01388a8>] (kthread+0x100/0x10c)
    +[<c01388a8>] (kthread) from [<c0100150>] (ret_from_fork+0x14/0x24)
    +Exception stack(0xc1195fb0 to 0xc1195ff8)
    +5fa0:                                     00000000 00000000
00000000 00000000
    +5fc0: 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000
    +5fe0: 00000000 00000000 00000000 00000000 00000013 00000000
    +---[ end trace 5d3a7a10ee0cec3d ]---
    +da9063-rtc da9063-rtc: Failed to set RTC time data: -108
    +da9063-rtc da9063-rtc: Failed to read RTC time data: -108
     CPU1 is up

The latter is probably a pre-existing issue, just more likely to trigger now the sync interval is 2s.

Gr{oetje,eeting}s,

Geert

Signature · 5 lines
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But
when I'm talking to journalists I just say "programmer" or something like that.
                                -- Linus Torvalds
#39 lore raw

Re: [patch 5/8] ntp: Make the RTC synchronization more reliable

Quoted 10 lines · Geert Uytterhoeven

Hi Thomas,

Quoted 2 lines

Thanks for your patch, which is now commit c9e6189fb03123a7 ("ntp: Make the RTC synchronization more reliable").

Since this commit, the I2C RTC on the R-Car M2-W Koelsch development board is accessed every two seconds. Sticking a WARN() in the I2C activation path gives e.g.

Huch? Every two seconds? The timer is armed with 11 * 60 * NSEC_PER_SEC, which is 11 minutes. Confused....

Thanks,

tglx

#40 lore raw

Re: [patch 5/8] ntp: Make the RTC synchronization more reliable

Hi Thomas,

Quoted 7 lines · Thomas Gleixner
Quoted 6 lines · Geert Uytterhoeven
Quoted 2 lines

Thanks for your patch, which is now commit c9e6189fb03123a7 ("ntp: Make the RTC synchronization more reliable").

Quoted 6 lines
Quoted 3 lines

Since this commit, the I2C RTC on the R-Car M2-W Koelsch development board is accessed every two seconds. Sticking a WARN() in the I2C activation path gives e.g.

Huch? Every two seconds? The timer is armed with 11 * 60 * NSEC_PER_SEC, which is 11 minutes. Confused....

Thanks for the hint:

    #define SYNC_PERIOD_NS (11UL * 60 * NSEC_PER_SEC)

is truncated on 32-bit platforms.

Patch sent.

Gr{oetje,eeting}s,

Geert

--
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But when I'm talking to journalists I just say "programmer" or something like that.
-- Linus Torvalds

#41 lore raw

PATCH 6/8 ntp, rtc: Move rtc_set_ntp_time() to ntp code

In reply to Thomas Gleixner

rtc_set_ntp_time() is not really RTC functionality as the code is just a user of RTC. Move it into the NTP code which allows further cleanups.

---
 drivers/rtc/Makefile  |    1 
 drivers/rtc/systohc.c |   61 ----------------------------------
 include/linux/rtc.h   |   34 -------------------
 kernel/time/ntp.c     |   88 ++++++++++++++++++++++++++++++++++++++++++++++++--
 4 files changed, 85 insertions(+), 99 deletions(-)
drivers/rtc/Makefile +0 -1
@@ -6,7 +6,6 @@
 ccflags-$(CONFIG_RTC_DEBUG)	:= -DDEBUG
 
 obj-$(CONFIG_RTC_LIB)		+= lib.o
-obj-$(CONFIG_RTC_SYSTOHC)	+= systohc.o
 obj-$(CONFIG_RTC_CLASS)		+= rtc-core.o
 obj-$(CONFIG_RTC_MC146818_LIB)	+= rtc-mc146818-lib.o
 rtc-core-y			:= class.o interface.o
drivers/rtc/systohc.c deleted +0 -61

61 lines not on this page · raw message

include/linux/rtc.h +0 -34
@@ -165,7 +165,6 @@ int __rtc_register_device(struct module
 
 extern int rtc_read_time(struct rtc_device *rtc, struct rtc_time *tm);
 extern int rtc_set_time(struct rtc_device *rtc, struct rtc_time *tm);
-extern int rtc_set_ntp_time(struct timespec64 now, unsigned long *target_nsec);
 int __rtc_read_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm);
 extern int rtc_read_alarm(struct rtc_device *rtc,
 			struct rtc_wkalrm *alrm);
@@ -205,39 +204,6 @@ static inline bool is_leap_year(unsigned
 	return (!(year % 4) && (year % 100)) || !(year % 400);
 }
 
-/* Determine if we can call to driver to set the time. Drivers can only be
- * called to set a second aligned time value, and the field set_offset_nsec
- * specifies how far away from the second aligned time to call the driver.
- *
- * This also computes 'to_set' which is the time we are trying to set, and has
- * a zero in tv_nsecs, such that:
- *    to_set - set_delay_nsec == now +/- FUZZ
- *
- */
-static inline bool rtc_tv_nsec_ok(s64 set_offset_nsec,
-				  struct timespec64 *to_set,
-				  const struct timespec64 *now)
-{
-	/* Allowed error in tv_nsec, arbitarily set to 5 jiffies in ns. */
-	const unsigned long TIME_SET_NSEC_FUZZ = TICK_NSEC * 5;
-	struct timespec64 delay = {.tv_sec = 0,
-				   .tv_nsec = set_offset_nsec};
-
-	*to_set = timespec64_add(*now, delay);
-
-	if (to_set->tv_nsec < TIME_SET_NSEC_FUZZ) {
-		to_set->tv_nsec = 0;
-		return true;
-	}
-
-	if (to_set->tv_nsec > NSEC_PER_SEC - TIME_SET_NSEC_FUZZ) {
-		to_set->tv_sec++;
-		to_set->tv_nsec = 0;
-		return true;
-	}
-	return false;
-}
-
 #define rtc_register_device(device) \
 	__rtc_register_device(THIS_MODULE, device)
 
kernel/time/ntp.c +85 -3

106 lines not on this page · raw message

Reviewed-by on v1 6/8
#42 lore raw

Re: [patch 6/8] ntp, rtc: Move rtc_set_ntp_time() to ntp code

Quoted 11 lines · Thomas Gleixner

rtc_set_ntp_time() is not really RTC functionality as the code is just a user of RTC. Move it into the NTP code which allows further cleanups.

---
 drivers/rtc/Makefile  |    1 
 drivers/rtc/systohc.c |   61 ----------------------------------
 include/linux/rtc.h   |   34 -------------------
 kernel/time/ntp.c     |   88 ++++++++++++++++++++++++++++++++++++++++++++++++--
 4 files changed, 85 insertions(+), 99 deletions(-)

Fair enough, it is asymmetric with how HCTOSYS works, but not a big deal

Jason

#43 lore raw

Re: [patch 6/8] ntp, rtc: Move rtc_set_ntp_time() to ntp code

Quoted 13 lines · Jason Gunthorpe
Quoted 11 lines · Thomas Gleixner

rtc_set_ntp_time() is not really RTC functionality as the code is just a user of RTC. Move it into the NTP code which allows further cleanups.

---
 drivers/rtc/Makefile  |    1 
 drivers/rtc/systohc.c |   61 ----------------------------------
 include/linux/rtc.h   |   34 -------------------
 kernel/time/ntp.c     |   88 ++++++++++++++++++++++++++++++++++++++++++++++++--
 4 files changed, 85 insertions(+), 99 deletions(-)
Quoted 3 lines

Fair enough, it is asymmetric with how HCTOSYS works, but not a big deal

It is already asymmetric as hctosys will always happen as soon as the rtc driver is loaded but systohc will only actually be called only if ntp is enabled.

I must admit I did consider moving it ou of the rtc subsystem instead of having it moved in class.c to solve the issue with rtc drivers compiled as modules but I still carry the nasty BITS_PER_LONG check to keep systemd happy on a 32bit userspace.

Signature · 3 lines
Alexandre Belloni, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#44 lore raw

[tip: timers/core] ntp, rtc: Move rtc_set_ntp_time() to ntp code

In reply to Thomas Gleixner
The following commit has been merged into the timers/core branch of tip:

The following commit has been merged into the timers/core branch of tip:

Commit-ID:     33e62e832384c8cb523044e0e9d99d7133f98e93
Gitweb:        https://git.kernel.org/tip/33e62e832384c8cb523044e0e9d99d7133f98e93
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Sun, 06 Dec 2020 22:46:19 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Fri, 11 Dec 2020 10:40:52 +01:00

ntp, rtc: Move rtc_set_ntp_time() to ntp code

rtc_set_ntp_time() is not really RTC functionality as the code is just a user of RTC. Move it into the NTP code which allows further cleanups.

---
 drivers/rtc/Makefile  |  1 +-
 drivers/rtc/systohc.c | 61 +-----------------------------
 include/linux/rtc.h   | 34 +----------------
 kernel/time/ntp.c     | 88 ++++++++++++++++++++++++++++++++++++++++--
 4 files changed, 85 insertions(+), 99 deletions(-)
 delete mode 100644 drivers/rtc/systohc.c
drivers/rtc/Makefile +0 -1
index bfb5746..bb8f319 100644
@@ -6,7 +6,6 @@
 ccflags-$(CONFIG_RTC_DEBUG)	:= -DDEBUG
 
 obj-$(CONFIG_RTC_LIB)		+= lib.o
-obj-$(CONFIG_RTC_SYSTOHC)	+= systohc.o
 obj-$(CONFIG_RTC_CLASS)		+= rtc-core.o
 obj-$(CONFIG_RTC_MC146818_LIB)	+= rtc-mc146818-lib.o
 rtc-core-y			:= class.o interface.o
drivers/rtc/systohc.c deleted +0 -61

61 lines not on this page · raw message

include/linux/rtc.h +0 -34
index 22d1575..ff62680 100644
@@ -165,7 +165,6 @@ int __rtc_register_device(struct module *owner, struct rtc_device *rtc);
 
 extern int rtc_read_time(struct rtc_device *rtc, struct rtc_time *tm);
 extern int rtc_set_time(struct rtc_device *rtc, struct rtc_time *tm);
-extern int rtc_set_ntp_time(struct timespec64 now, unsigned long *target_nsec);
 int __rtc_read_alarm(struct rtc_device *rtc, struct rtc_wkalrm *alarm);
 extern int rtc_read_alarm(struct rtc_device *rtc,
 			struct rtc_wkalrm *alrm);
@@ -205,39 +204,6 @@ static inline bool is_leap_year(unsigned int year)
 	return (!(year % 4) && (year % 100)) || !(year % 400);
 }
 
-/* Determine if we can call to driver to set the time. Drivers can only be
- * called to set a second aligned time value, and the field set_offset_nsec
- * specifies how far away from the second aligned time to call the driver.
- *
- * This also computes 'to_set' which is the time we are trying to set, and has
- * a zero in tv_nsecs, such that:
- *    to_set - set_delay_nsec == now +/- FUZZ
- *
- */
-static inline bool rtc_tv_nsec_ok(s64 set_offset_nsec,
-				  struct timespec64 *to_set,
-				  const struct timespec64 *now)
-{
-	/* Allowed error in tv_nsec, arbitarily set to 5 jiffies in ns. */
-	const unsigned long TIME_SET_NSEC_FUZZ = TICK_NSEC * 5;
-	struct timespec64 delay = {.tv_sec = 0,
-				   .tv_nsec = set_offset_nsec};
-
-	*to_set = timespec64_add(*now, delay);
-
-	if (to_set->tv_nsec < TIME_SET_NSEC_FUZZ) {
-		to_set->tv_nsec = 0;
-		return true;
-	}
-
-	if (to_set->tv_nsec > NSEC_PER_SEC - TIME_SET_NSEC_FUZZ) {
-		to_set->tv_sec++;
-		to_set->tv_nsec = 0;
-		return true;
-	}
-	return false;
-}
-
 #define rtc_register_device(device) \
 	__rtc_register_device(THIS_MODULE, device)
 
kernel/time/ntp.c +85 -3

106 lines not on this page · raw message

#45 lore raw

PATCH 7/8 ntp: Make the RTC sync offset less obscure

In reply to Thomas Gleixner

The current RTC set_offset_nsec value is not really intuitive to understand.

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

The offset is calculated from twrite based on the assumption that t2 - twrite == 1s. That means for the MC146818 RTC the offset needs to be negative so that the write happens 500ms before t2.

It's easier to understand when the whole calculation is based on t2. That avoids negative offsets and the meaning is obvious:

t2 - twrite: The time defined by the chip when seconds increment
after the write.

twrite - tsched: The time for the transport to the point where the chip
is updated.

==> set_offset_nsec =  t2 - tsched
    ttransport      =  twrite - tsched
    tRTCinc         =  t2 - twrite
==> set_offset_nsec =  ttransport + tRTCinc

tRTCinc is a chip property and can be obtained from the data sheet.

ttransport depends on how the RTC is connected. It is close to 0 for directly accessible RTCs. For RTCs behind a slow bus, e.g. i2c, it's the time required to send the update over the bus. This can be estimated or even calibrated, but that's a different problem.

Adjust the implementation and update comments accordingly.

---
 drivers/rtc/class.c    |    9 +++++++--
 drivers/rtc/rtc-cmos.c |    2 +-
 include/linux/rtc.h    |   35 +++++++++++++++++++++++++++++------
 kernel/time/ntp.c      |   49 +++++++++++++++++++++++++------------------------
 4 files changed, 62 insertions(+), 33 deletions(-)
drivers/rtc/class.c +7 -2
@@ -200,8 +200,13 @@ static struct rtc_device *rtc_allocate_d
 
 	device_initialize(&rtc->dev);
 
-	/* Drivers can revise this default after allocating the device. */
-	rtc->set_offset_nsec =  10 * NSEC_PER_MSEC;
+	/*
+	 * Drivers can revise this default after allocating the device.
+	 * The default is what most RTCs do: Increment seconds exactly one
+	 * second after the write happened. This adds a default transport
+	 * time of 10ms which is at least halfways close to reality.
+	 */
+	rtc->set_offset_nsec = NSEC_PER_SEC + 10 * NSEC_PER_MSEC;
 
 	rtc->irq_freq = 1;
 	rtc->max_user_freq = 64;
drivers/rtc/rtc-cmos.c +1 -1
@@ -869,7 +869,7 @@ cmos_do_probe(struct device *dev, struct
 		goto cleanup2;
 
 	/* Set the sync offset for the periodic 11min update correct */
-	cmos_rtc.rtc->set_offset_nsec = -(NSEC_PER_SEC / 2);
+	cmos_rtc.rtc->set_offset_nsec = NSEC_PER_SEC / 2;
 
 	/* export at least the first block of NVRAM */
 	nvmem_cfg.size = address_space - NVRAM_OFFSET;
include/linux/rtc.h +29 -6
@@ -110,13 +110,36 @@ struct rtc_device {
 	/* Some hardware can't support UIE mode */
 	int uie_unsupported;
 
-	/* Number of nsec it takes to set the RTC clock. This influences when
-	 * the set ops are called. An offset:
-	 *   - of 0.5 s will call RTC set for wall clock time 10.0 s at 9.5 s
-	 *   - of 1.5 s will call RTC set for wall clock time 10.0 s at 8.5 s
-	 *   - of -0.5 s will call RTC set for wall clock time 10.0 s at 10.5 s
+	/*
+	 * This offset specifies the update timing of the RTC.
+	 *
+	 * tsched     t1 write(t2.tv_sec - 1sec))  t2 RTC increments seconds
+	 *
+	 * The offset defines how tsched is computed so that the write to
+	 * the RTC (t2.tv_sec - 1sec) is correct versus the time required
+	 * for the transport of the write and the time which the RTC needs
+	 * to increment seconds the first time after the write (t2).
+	 *
+	 * For direct accessible RTCs tsched ~= t1 because the write time
+	 * is negligible. For RTCs behind slow busses the transport time is
+	 * significant and has to be taken into account.
+	 *
+	 * The time between the write (t1) and the first increment after
+	 * the write (t2) is RTC specific. For a MC146818 RTC it's 500ms,
+	 * for many others it's exactly 1 second. Consult the datasheet.
+	 *
+	 * The value of this offset is also used to calculate the to be
+	 * written value (t2.tv_sec - 1sec) at tsched.
+	 *
+	 * The default value for this is NSEC_PER_SEC + 10 msec default
+	 * transport time. The offset can be adjusted by drivers so the
+	 * calculation for the to be written value at tsched becomes
+	 * correct:
+	 *
+	 *	newval = tsched + set_offset_nsec - NSEC_PER_SEC
+	 * and  (tsched + set_offset_nsec) % NSEC_PER_SEC == 0
 	 */
-	long set_offset_nsec;
+	unsigned long set_offset_nsec;
 
 	bool registered;
 
kernel/time/ntp.c +25 -24

84 lines not on this page · raw message

#46 lore raw

[tip: timers/core] ntp: Make the RTC sync offset less obscure

The following commit has been merged into the timers/core branch of tip:

The following commit has been merged into the timers/core branch of tip:

Commit-ID:     69eca258c85000564577642ba28335eb4e1df8f0
Gitweb:        https://git.kernel.org/tip/69eca258c85000564577642ba28335eb4e1df8f0
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Sun, 06 Dec 2020 22:46:20 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Fri, 11 Dec 2020 10:40:53 +01:00

ntp: Make the RTC sync offset less obscure

The current RTC set_offset_nsec value is not really intuitive to understand.

tsched twrite(t2.tv_sec - 1) t2 (seconds increment)

The offset is calculated from twrite based on the assumption that t2 - twrite == 1s. That means for the MC146818 RTC the offset needs to be negative so that the write happens 500ms before t2.

It's easier to understand when the whole calculation is based on t2. That avoids negative offsets and the meaning is obvious:

t2 - twrite: The time defined by the chip when seconds increment
after the write.

twrite - tsched: The time for the transport to the point where the chip
is updated.

==> set_offset_nsec =  t2 - tsched
    ttransport      =  twrite - tsched
    tRTCinc         =  t2 - twrite
==> set_offset_nsec =  ttransport + tRTCinc

tRTCinc is a chip property and can be obtained from the data sheet.

ttransport depends on how the RTC is connected. It is close to 0 for directly accessible RTCs. For RTCs behind a slow bus, e.g. i2c, it's the time required to send the update over the bus. This can be estimated or even calibrated, but that's a different problem.

Adjust the implementation and update comments accordingly.

---
 drivers/rtc/class.c    |  9 ++++++--
 drivers/rtc/rtc-cmos.c |  2 +-
 include/linux/rtc.h    | 35 +++++++++++++++++++++++++------
 kernel/time/ntp.c      | 47 ++++++++++++++++++++---------------------
 4 files changed, 61 insertions(+), 32 deletions(-)
drivers/rtc/class.c +7 -2
index d795737..5855aa2 100644
@@ -200,8 +200,13 @@ static struct rtc_device *rtc_allocate_device(void)
 
 	device_initialize(&rtc->dev);
 
-	/* Drivers can revise this default after allocating the device. */
-	rtc->set_offset_nsec =  5 * NSEC_PER_MSEC;
+	/*
+	 * Drivers can revise this default after allocating the device.
+	 * The default is what most RTCs do: Increment seconds exactly one
+	 * second after the write happened. This adds a default transport
+	 * time of 5ms which is at least halfways close to reality.
+	 */
+	rtc->set_offset_nsec = NSEC_PER_SEC + 5 * NSEC_PER_MSEC;
 
 	rtc->irq_freq = 1;
 	rtc->max_user_freq = 64;
drivers/rtc/rtc-cmos.c +1 -1
index 7728fac..c5bcd2a 100644
@@ -869,7 +869,7 @@ cmos_do_probe(struct device *dev, struct resource *ports, int rtc_irq)
 		goto cleanup2;
 
 	/* Set the sync offset for the periodic 11min update correct */
-	cmos_rtc.rtc->set_offset_nsec = -(NSEC_PER_SEC / 2);
+	cmos_rtc.rtc->set_offset_nsec = NSEC_PER_SEC / 2;
 
 	/* export at least the first block of NVRAM */
 	nvmem_cfg.size = address_space - NVRAM_OFFSET;
include/linux/rtc.h +29 -6
index ff62680..b829382 100644
@@ -110,13 +110,36 @@ struct rtc_device {
 	/* Some hardware can't support UIE mode */
 	int uie_unsupported;
 
-	/* Number of nsec it takes to set the RTC clock. This influences when
-	 * the set ops are called. An offset:
-	 *   - of 0.5 s will call RTC set for wall clock time 10.0 s at 9.5 s
-	 *   - of 1.5 s will call RTC set for wall clock time 10.0 s at 8.5 s
-	 *   - of -0.5 s will call RTC set for wall clock time 10.0 s at 10.5 s
+	/*
+	 * This offset specifies the update timing of the RTC.
+	 *
+	 * tsched     t1 write(t2.tv_sec - 1sec))  t2 RTC increments seconds
+	 *
+	 * The offset defines how tsched is computed so that the write to
+	 * the RTC (t2.tv_sec - 1sec) is correct versus the time required
+	 * for the transport of the write and the time which the RTC needs
+	 * to increment seconds the first time after the write (t2).
+	 *
+	 * For direct accessible RTCs tsched ~= t1 because the write time
+	 * is negligible. For RTCs behind slow busses the transport time is
+	 * significant and has to be taken into account.
+	 *
+	 * The time between the write (t1) and the first increment after
+	 * the write (t2) is RTC specific. For a MC146818 RTC it's 500ms,
+	 * for many others it's exactly 1 second. Consult the datasheet.
+	 *
+	 * The value of this offset is also used to calculate the to be
+	 * written value (t2.tv_sec - 1sec) at tsched.
+	 *
+	 * The default value for this is NSEC_PER_SEC + 10 msec default
+	 * transport time. The offset can be adjusted by drivers so the
+	 * calculation for the to be written value at tsched becomes
+	 * correct:
+	 *
+	 *	newval = tsched + set_offset_nsec - NSEC_PER_SEC
+	 * and  (tsched + set_offset_nsec) % NSEC_PER_SEC == 0
 	 */
-	long set_offset_nsec;
+	unsigned long set_offset_nsec;
 
 	bool registered;
 
kernel/time/ntp.c +24 -23

83 lines not on this page · raw message

#47 lore raw

PATCH 8/8 ntp: Consolidate the RTC update implementation

In reply to Thomas Gleixner

The code for the legacy RTC and the RTC class based update are pretty much the same. Consolidate the common parts into one function and just invoke the actual setter functions.

For RTC class based devices the update code checks whether the offset is valid for the device, which is usually not the case for the first invocation. If it's not the same it stores the correct offset and lets the caller try again. That's not much different from the previous approach where the first invocation had a pretty low probability to actually hit the allowed window.

---
 kernel/time/ntp.c |  139 ++++++++++++++++++------------------------------------
 1 file changed, 47 insertions(+), 92 deletions(-)
kernel/time/ntp.c +47 -92
@@ -564,118 +564,53 @@ static inline bool rtc_tv_nsec_ok(unsign
 	return false;
 }
 
+#ifdef CONFIG_GENERIC_CMOS_UPDATE
+int __weak update_persistent_clock64(struct timespec64 now64)
+{
+	return -ENODEV;
+}
+#else
+static inline int update_persistent_clock64(struct timespec64 now64)
+{
+	return -ENODEV;
+}
+#endif
+
 #ifdef CONFIG_RTC_SYSTOHC
-/*
- * rtc_set_ntp_time - Save NTP synchronized time to the RTC
- */
-static int rtc_set_ntp_time(struct timespec64 now, unsigned long *offset_nsec)
+/* Save NTP synchronized time to the RTC */
+static int update_rtc(struct timespec64 *to_set, unsigned long *offset_nsec)
 {
-	struct timespec64 to_set;
 	struct rtc_device *rtc;
 	struct rtc_time tm;
 	int err = -ENODEV;
-	bool ok;
 
 	rtc = rtc_class_open(CONFIG_RTC_SYSTOHC_DEVICE);
 	if (!rtc)
-		goto out_err;
+		return -ENODEV;
 
 	if (!rtc->ops || !rtc->ops->set_time)
 		goto out_close;
 
-	/* Store the update offset for this RTC */
-	*offset_nsec = rtc->set_offset_nsec;
-
-	ok = rtc_tv_nsec_ok(rtc->set_offset_nsec, &to_set, &now);
-	if (!ok) {
-		err = -EPROTO;
-		goto out_close;
+	/* First call might not have the correct offset */
+	if (*offset_nsec == rtc->set_offset_nsec) {
+		rtc_time64_to_tm(to_set->tv_sec, &tm);
+		err = rtc_set_time(rtc, &tm);
+	} else {
+		/* Store the update offset and let the caller try again */
+		*offset_nsec = rtc->set_offset_nsec;
+		err = -EAGAIN;
 	}
-
-	rtc_time64_to_tm(to_set.tv_sec, &tm);
-
-	err = rtc_set_time(rtc, &tm);
-
 out_close:
 	rtc_class_close(rtc);
-out_err:
 	return err;
 }
-
-static void sync_rtc_clock(void)
-{
-	unsigned long offset_nsec;
-	struct timespec64 adjust;
-	int rc;
-
-	ktime_get_real_ts64(&adjust);
-
-	if (persistent_clock_is_local)
-		adjust.tv_sec -= (sys_tz.tz_minuteswest * 60);
-
-	/*
-	 * The current RTC in use will provide the nanoseconds offset prior
-	 * to a full second it wants to be called at, and invokes
-	 * rtc_tv_nsec_ok() internally.
-	 */
-	rc = rtc_set_ntp_time(adjust, &offset_nsec);
-	if (rc == -ENODEV)
-		return;
-
-	sched_sync_hw_clock(offset_nsec, rc != 0);
-}
 #else
-static inline void sync_rtc_clock(void) { }
-#endif
-
-#ifdef CONFIG_GENERIC_CMOS_UPDATE
-int __weak update_persistent_clock64(struct timespec64 now64)
+static inline int update_rtc(struct timespec64 *to_set, unsigned long *offset_nsec)
 {
 	return -ENODEV;
 }
 #endif
 
-static bool sync_cmos_clock(void)
-{
-	static bool no_cmos;
-	struct timespec64 now;
-	struct timespec64 adjust;
-	int rc = -EPROTO;
-	long target_nsec = NSEC_PER_SEC / 2;
-
-	if (!IS_ENABLED(CONFIG_GENERIC_CMOS_UPDATE))
-		return false;
-
-	if (no_cmos)
-		return false;
-
-	/*
-	 * Historically update_persistent_clock64() has followed x86
-	 * semantics, which match the MC146818A/etc RTC. This RTC will store
-	 * 'adjust' and then in .5s it will advance once second.
-	 *
-	 * Architectures are strongly encouraged to use rtclib and not
-	 * implement this legacy API.
-	 */
-	ktime_get_real_ts64(&now);
-	if (rtc_tv_nsec_ok(target_nsec, &adjust, &now)) {
-		if (persistent_clock_is_local)
-			adjust.tv_sec -= (sys_tz.tz_minuteswest * 60);
-		rc = update_persistent_clock64(adjust);
-		/*
-		 * The machine does not support update_persistent_clock64 even
-		 * though it defines CONFIG_GENERIC_CMOS_UPDATE.
-		 */
-		if (rc == -ENODEV) {
-			no_cmos = true;
-			return false;
-		}
-	}
-
-	sched_sync_hw_clock(target_nsec, rc != 0);
-	return true;
-}
-
 /*
  * If we have an externally synchronized Linux clock, then update RTC clock
  * accordingly every ~11 minutes. Generally RTCs can only store second
@@ -686,6 +621,10 @@ static bool sync_cmos_clock(void)
  */
 static void sync_hw_clock(struct work_struct *work)
 {
+	static unsigned long offset_nsec = NSEC_PER_SEC / 2;
+	struct timespec64 now, to_set;
+	int res = -EAGAIN;
+
 	/*
 	 * Don't update if STA_UNSYNC is set and if ntp_notify_cmos_timer()
 	 * managed to schedule the work between the timer firing and the
@@ -694,10 +633,26 @@ static void sync_hw_clock(struct work_st
 	if (!ntp_synced() || hrtimer_is_queued(&sync_hrtimer))
 		return;
 
-	if (sync_cmos_clock())
-		return;
+	ktime_get_real_ts64(&now);
+	/* If @now is not in the allowed window, try again */
+	if (!rtc_tv_nsec_ok(offset_nsec, &to_set, &now))
+		goto rearm;
 
-	sync_rtc_clock();
+	/* Take timezone adjusted RTCs into account */
+	if (persistent_clock_is_local)
+		to_set.tv_sec -= (sys_tz.tz_minuteswest * 60);
+
+	/* Try the legacy RTC first */
+	res = update_persistent_clock64(to_set);
+	if (res != -ENODEV)
+		goto rearm;
+
+	/* Try the RTC class */
+	res = update_rtc(&to_set, &offset_nsec);
+	if (res == -ENODEV)
+		return;
+rearm:
+	sched_sync_hw_clock(offset_nsec, res != 0);
 }
 
 void ntp_notify_cmos_timer(void)
Reviewed-by on v1 8/8
#48 lore raw

Re: [patch 8/8] ntp: Consolidate the RTC update implementation

kernel/time/ntp.c static bool sync_cmos_clock(void) · line 624

Quoted 8 lines · Thomas Gleixner

/*
* If we have an externally synchronized Linux clock, then update RTC clock
* accordingly every ~11 minutes. Generally RTCs can only store second

kernel/time/ntp.c +1 -0
@@ -686,6 +621,10 @@ static bool sync_cmos_clock(void)
  */
 static void sync_hw_clock(struct work_struct *work)
 {
+	static unsigned long offset_nsec = NSEC_PER_SEC / 2;

A comment here explaining this is the default: because the platform is assumed to use CMOS, and by the way, this whole thing is obsolete don't use it, seems appropriate..

The time split is clearer if you think of it from a bus/datasheet perspective, less clear if you try to measure the system directly, eg from an alarm. But, I think this has a better chance of some rtclib driver authors to fill in the datasheet value at least.

Jason

#49 lore raw

Re: [patch 8/8] ntp: Consolidate the RTC update implementation

Quoted 8 lines · Jason Gunthorpe

kernel/time/ntp.c static bool sync_cmos_clock(void) · line 624

Quoted 3 lines · Thomas Gleixner

static void sync_hw_clock(struct work_struct *work) {

kernel/time/ntp.c +1 -0
+	static unsigned long offset_nsec = NSEC_PER_SEC / 2;

A comment here explaining this is the default: because the platform is assumed to use CMOS, and by the way, this whole thing is obsolete don't use it, seems appropriate..

Will add something like that.

Quoted 4 lines

The time split is clearer if you think of it from a bus/datasheet perspective, less clear if you try to measure the system directly, eg from an alarm. But, I think this has a better chance of some rtclib driver authors to fill in the datasheet value at least.

That's the hope. You know hope dies last...

Thanks,

tglx

#50 lore raw

[tip: timers/core] ntp: Consolidate the RTC update implementation

In reply to Thomas Gleixner
The following commit has been merged into the timers/core branch of tip:

The following commit has been merged into the timers/core branch of tip:

Commit-ID:     76e87d96b30b5fee91b381fbc444a3eabcd9469a
Gitweb:        https://git.kernel.org/tip/76e87d96b30b5fee91b381fbc444a3eabcd9469a
Author:        Thomas Gleixner <[email protected]>
AuthorDate:    Sun, 06 Dec 2020 22:46:21 +01:00
Committer:     Thomas Gleixner <[email protected]>
CommitterDate: Fri, 11 Dec 2020 10:40:53 +01:00

ntp: Consolidate the RTC update implementation

The code for the legacy RTC and the RTC class based update are pretty much the same. Consolidate the common parts into one function and just invoke the actual setter functions.

For RTC class based devices the update code checks whether the offset is valid for the device, which is usually not the case for the first invocation. If it's not the same it stores the correct offset and lets the caller try again. That's not much different from the previous approach where the first invocation had a pretty low probability to actually hit the allowed window.

---
 kernel/time/ntp.c | 144 ++++++++++++++++-----------------------------
 1 file changed, 52 insertions(+), 92 deletions(-)
kernel/time/ntp.c +52 -92
index a34ac06..7404d38 100644
@@ -564,118 +564,53 @@ static inline bool rtc_tv_nsec_ok(unsigned long set_offset_nsec,
 	return false;
 }
 
+#ifdef CONFIG_GENERIC_CMOS_UPDATE
+int __weak update_persistent_clock64(struct timespec64 now64)
+{
+	return -ENODEV;
+}
+#else
+static inline int update_persistent_clock64(struct timespec64 now64)
+{
+	return -ENODEV;
+}
+#endif
+
 #ifdef CONFIG_RTC_SYSTOHC
-/*
- * rtc_set_ntp_time - Save NTP synchronized time to the RTC
- */
-static int rtc_set_ntp_time(struct timespec64 now, unsigned long *offset_nsec)
+/* Save NTP synchronized time to the RTC */
+static int update_rtc(struct timespec64 *to_set, unsigned long *offset_nsec)
 {
-	struct timespec64 to_set;
 	struct rtc_device *rtc;
 	struct rtc_time tm;
 	int err = -ENODEV;
-	bool ok;
 
 	rtc = rtc_class_open(CONFIG_RTC_SYSTOHC_DEVICE);
 	if (!rtc)
-		goto out_err;
+		return -ENODEV;
 
 	if (!rtc->ops || !rtc->ops->set_time)
 		goto out_close;
 
-	/* Store the update offset for this RTC */
-	*offset_nsec = rtc->set_offset_nsec;
-
-	ok = rtc_tv_nsec_ok(rtc->set_offset_nsec, &to_set, &now);
-	if (!ok) {
-		err = -EPROTO;
-		goto out_close;
+	/* First call might not have the correct offset */
+	if (*offset_nsec == rtc->set_offset_nsec) {
+		rtc_time64_to_tm(to_set->tv_sec, &tm);
+		err = rtc_set_time(rtc, &tm);
+	} else {
+		/* Store the update offset and let the caller try again */
+		*offset_nsec = rtc->set_offset_nsec;
+		err = -EAGAIN;
 	}
-
-	rtc_time64_to_tm(to_set.tv_sec, &tm);
-
-	err = rtc_set_time(rtc, &tm);
-
 out_close:
 	rtc_class_close(rtc);
-out_err:
 	return err;
 }
-
-static void sync_rtc_clock(void)
-{
-	unsigned long offset_nsec;
-	struct timespec64 adjust;
-	int rc;
-
-	ktime_get_real_ts64(&adjust);
-
-	if (persistent_clock_is_local)
-		adjust.tv_sec -= (sys_tz.tz_minuteswest * 60);
-
-	/*
-	 * The current RTC in use will provide the nanoseconds offset prior
-	 * to a full second it wants to be called at, and invokes
-	 * rtc_tv_nsec_ok() internally.
-	 */
-	rc = rtc_set_ntp_time(adjust, &offset_nsec);
-	if (rc == -ENODEV)
-		return;
-
-	sched_sync_hw_clock(offset_nsec, rc != 0);
-}
 #else
-static inline void sync_rtc_clock(void) { }
-#endif
-
-#ifdef CONFIG_GENERIC_CMOS_UPDATE
-int __weak update_persistent_clock64(struct timespec64 now64)
+static inline int update_rtc(struct timespec64 *to_set, unsigned long *offset_nsec)
 {
 	return -ENODEV;
 }
 #endif
 
-static bool sync_cmos_clock(void)
-{
-	static bool no_cmos;
-	struct timespec64 now;
-	struct timespec64 adjust;
-	int rc = -EPROTO;
-	long target_nsec = NSEC_PER_SEC / 2;
-
-	if (!IS_ENABLED(CONFIG_GENERIC_CMOS_UPDATE))
-		return false;
-
-	if (no_cmos)
-		return false;
-
-	/*
-	 * Historically update_persistent_clock64() has followed x86
-	 * semantics, which match the MC146818A/etc RTC. This RTC will store
-	 * 'adjust' and then in .5s it will advance once second.
-	 *
-	 * Architectures are strongly encouraged to use rtclib and not
-	 * implement this legacy API.
-	 */
-	ktime_get_real_ts64(&now);
-	if (rtc_tv_nsec_ok(target_nsec, &adjust, &now)) {
-		if (persistent_clock_is_local)
-			adjust.tv_sec -= (sys_tz.tz_minuteswest * 60);
-		rc = update_persistent_clock64(adjust);
-		/*
-		 * The machine does not support update_persistent_clock64 even
-		 * though it defines CONFIG_GENERIC_CMOS_UPDATE.
-		 */
-		if (rc == -ENODEV) {
-			no_cmos = true;
-			return false;
-		}
-	}
-
-	sched_sync_hw_clock(target_nsec, rc != 0);
-	return true;
-}
-
 /*
  * If we have an externally synchronized Linux clock, then update RTC clock
  * accordingly every ~11 minutes. Generally RTCs can only store second
@@ -687,6 +622,15 @@ static bool sync_cmos_clock(void)
 static void sync_hw_clock(struct work_struct *work)
 {
 	/*
+	 * The default synchronization offset is 500ms for the deprecated
+	 * update_persistent_clock64() under the assumption that it uses
+	 * the infamous CMOS clock (MC146818).
+	 */
+	static unsigned long offset_nsec = NSEC_PER_SEC / 2;
+	struct timespec64 now, to_set;
+	int res = -EAGAIN;
+
+	/*
 	 * Don't update if STA_UNSYNC is set and if ntp_notify_cmos_timer()
 	 * managed to schedule the work between the timer firing and the
 	 * work being able to rearm the timer. Wait for the timer to expire.
@@ -694,10 +638,26 @@ static void sync_hw_clock(struct work_struct *work)
 	if (!ntp_synced() || hrtimer_is_queued(&sync_hrtimer))
 		return;
 
-	if (sync_cmos_clock())
-		return;
+	ktime_get_real_ts64(&now);
+	/* If @now is not in the allowed window, try again */
+	if (!rtc_tv_nsec_ok(offset_nsec, &to_set, &now))
+		goto rearm;
 
-	sync_rtc_clock();
+	/* Take timezone adjusted RTCs into account */
+	if (persistent_clock_is_local)
+		to_set.tv_sec -= (sys_tz.tz_minuteswest * 60);
+
+	/* Try the legacy RTC first. */
+	res = update_persistent_clock64(to_set);
+	if (res != -ENODEV)
+		goto rearm;
+
+	/* Try the RTC class */
+	res = update_rtc(&to_set, &offset_nsec);
+	if (res == -ENODEV)
+		return;
+rearm:
+	sched_sync_hw_clock(offset_nsec, res != 0);
 }
 
 void ntp_notify_cmos_timer(void)
#51 lore raw
In reply to Thomas Gleixner

Alexandre,

Quoted 40 lines · Thomas Gleixner

Miroslav ran into a situation where the periodic RTC synchronization almost never was able to hit the time window for the update. That happens due the usage of delayed_work and the properties of the timer wheel.

While that particular problem is halfways simple to fix this started to unearth other problems with that code particularly with rtc_set_npt_time() but expanded into other things as well.

1) The update offset for rtc-cmos is off by a full second

2) The readout of MC146818 (rtc-cmos and arch code) is broken and can return garbage.

2) Alexandre questioned the approach in general and wants to get rid of it. Of course there are better methods to do that and it can be completely done in user space.

Unfortunately it's not that simple as this would be a user visible change, so making it at least halfways correct.

3) Alexandre requested to move that code into the NTP code as this is not really RTC functionality and just usage of the RTC API.

4) The update offset itself was questioned, but the time between the write and the next seconds increment in the RTC is fundamentaly a hardware property. The transport time, which is pretty irrelevant for direct accessible RTCs (rtc-cmos), but relevant for RTC behind i2c/SPI needs to be added on top.

It's undebated that this transport time cannot be correctly estimated, but right now it's 500ms which is far off. The correct transport time can be calibrated, a halfways correct value supplied via DT, but that's an orthogonal problem.

The following series addresses the above:

1) Fix the readout function of MC146818
2) Fix the rtc-cmos offset
3) Reduce the default transport time

Quoted 5 lines

4) Switch the NTP periodic sync code to a hrtimer/work combo

5) Move rtc_set_npt_time() to the ntp code
6) Make the update offset more intuitive
7) Simplify the whole machinery

any opinion on this?

Thanks,

tglx

#52 lore raw
Quoted 43 lines · Thomas Gleixner

Alexandre,

Quoted 40 lines · Thomas Gleixner

Miroslav ran into a situation where the periodic RTC synchronization almost never was able to hit the time window for the update. That happens due the usage of delayed_work and the properties of the timer wheel.

While that particular problem is halfways simple to fix this started to unearth other problems with that code particularly with rtc_set_npt_time() but expanded into other things as well.

1) The update offset for rtc-cmos is off by a full second

2) The readout of MC146818 (rtc-cmos and arch code) is broken and can return garbage.

2) Alexandre questioned the approach in general and wants to get rid of it. Of course there are better methods to do that and it can be completely done in user space.

Unfortunately it's not that simple as this would be a user visible change, so making it at least halfways correct.

3) Alexandre requested to move that code into the NTP code as this is not really RTC functionality and just usage of the RTC API.

4) The update offset itself was questioned, but the time between the write and the next seconds increment in the RTC is fundamentaly a hardware property. The transport time, which is pretty irrelevant for direct accessible RTCs (rtc-cmos), but relevant for RTC behind i2c/SPI needs to be added on top.

It's undebated that this transport time cannot be correctly estimated, but right now it's 500ms which is far off. The correct transport time can be calibrated, a halfways correct value supplied via DT, but that's an orthogonal problem.

The following series addresses the above:

1) Fix the readout function of MC146818
2) Fix the rtc-cmos offset
3) Reduce the default transport time

Quoted 8 lines
Quoted 5 lines

4) Switch the NTP periodic sync code to a hrtimer/work combo

5) Move rtc_set_npt_time() to the ntp code
6) Make the update offset more intuitive
7) Simplify the whole machinery

any opinion on this?

This looks very good to me, however, I think the 10ms offset is a bit too much. Do you mind waiting one or two days so I can get my test setup back up?

Signature · 3 lines
Alexandre Belloni, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#53 lore raw
Quoted 9 lines · Alexandre Belloni
Quoted 8 lines · Thomas Gleixner
Quoted 8 lines

The following series addresses the above:

1) Fix the readout function of MC146818
2) Fix the rtc-cmos offset
3) Reduce the default transport time

4) Switch the NTP periodic sync code to a hrtimer/work combo

Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

5) Move rtc_set_npt_time() to the ntp code
6) Make the update offset more intuitive
7) Simplify the whole machinery

any opinion on this?

This looks very good to me, however, I think the 10ms offset is a bit too much.

I pulled it out of thin air TBH. It's at least 50 times more accurate than what we had before :)

Quoted 2 lines

Do you mind waiting one or two days so I can get my test setup back up?

No problem.

Thanks,

tglx