Skip to contentSkip to conversation

gve: add support for PTP gettimex64

PATCH Applied Harshitha Ramamurthy 7 participants 24 messages May 14 – May 28

Subsystems (4)
lore
Share & tools
lore

Harshitha Ramamurthy

author maintainer
#0 lore raw

v8 cover gve: add support for PTP gettimex64

From: Jordan Rhee <[email protected]>

This patch series adds support to obtain near-simultaneous NIC and system timestamps with gettimex64. This enables daemons like chrony and phc2sys to synchronize the system clock to the NIC clock.

GVE does not have direct register access to the NIC hardware clock, so it must issue an AdminQ command to read the NIC clock. Two paths for obtaining a cross-timestamp are implemented: a precise path using system counter values sampled by the device, and a fallback path using system counter values sampled in the driver using ptp_read_system_prets()/postts().

To use the precise path, the current system clocksource must match the units returned by the device, which on x86 is X86_TSC and on ARM64 is ARM_ARCH_COUNTER. The clockid requested for the cross-timestamp must be either CLOCK_REALTIME or CLOCK_MONOTONIC_RAW. These conditions hold by default on GCP VMs using Chrony, so we expect the precise path to be used the vast majority of the time. If the system clocksource is changed to kvm-clock, it activates the fallback path. Ethtool counters have been added to count how many times each path is used.

The uncertainty window in the precise path is typically around 1-2us, while in the fallback path is around 60-80us. This table shows a comparison in chrony tracking statistics between the precise path and fallback path. The RMS offset is nearly 4 orders of magnitude smaller in the precise path.

|                 | Fallback Path         | Precise path             |
| --------------- | --------------------- | ------------------------ |
| System time     | 0.000000005 s slow    | 0.000000001 s fast       |
| Last offset     | +0.000005606 seconds  | +0.000000001 seconds     |
| RMS offset      | 0.000009020 seconds   | 0.000000002 seconds      |
| Frequency       | 4.115 ppm fast        | 0.362 ppm fast           |
| Residual freq   | +2.515 ppm            | +0.000 ppm               |
| Skew            | 18.480 ppm            | 0.001 ppm                |
| Root delay      | 0.000000001 seconds   | 0.000000001 seconds      |
| Root dispersion | 0.000081905 seconds   | 0.000001169 seconds      |
| Update interval | 0.5 seconds           | 0.5 seconds              |
| Leap status     | Normal                | Normal                   |

The first two patches pave the way for the PTP implementation by quieting excessive logging and refactoring an existing routine for thread safety.

---
Changelog:
V8:
- Fixed opcode extraction for extended commands (Sashiko)
- Link to v7: https://lore.kernel.org/netdev/[email protected]/

V7:
- Changed err from u32 to int (Sashiko)
- Actually committed stubs for adjtime and adjfine (Sashiko)
- Picked up Jake Keller's review tags
- Link to v6: https://lore.kernel.org/netdev/[email protected]/

V6:
- Added a fallback to driver-sampled time sandwich that is used when
the following conditions are not met:
- The system clock source is X86_TSC or ARM_ARCH_COUNTER
- The requested clockid is CLOCK_REALTIME or CLOCK_MONOTONIC_RAW
- The architecture is x86 or ARM64
- Added ethtool statistics to count how many cross-timestamps used the
precise path versus fallback path.
- Fixed printf format specifier.
- Added stub implementions of adjtime and adjfine to prevent NULL
dereference when phc2sys tries to adjust clock.
- Moved system time snapshot back to gve_ptp_gettimex64() so we can get
the current system clock source from it. It is OK for it to be outside
the mutex and retry loop because lock contention and retries should be extremely rare, and chrony filters out bad samples.
- Link to v5: https://lore.kernel.org/netdev/[email protected]/

V5:
- Reformulate retry loop in terms of total timeout instead of retry
count (Jakub Kicinski)
- Link to v4: https://lore.kernel.org/netdev/[email protected]/

V4:
- Call out change to dev_err_ratelimited() in patch 1 commit message (Jacob Keller)
- Ensure only one log is emitted when command returns GVE_ADMINQ_COMMAND_UNSET (Jacob Keller)
- Link to v3: https://lore.kernel.org/netdev/[email protected]/

V3:
- Take system time snapshot inside the mutex
- Return -EOPNOTSUPP if cross-timestamp is requested on an arch other
than x86 or arm64
- Fix initialization to only register PTP clock once all data is
initialized
- Link to v2: https://lore.kernel.org/netdev/[email protected]/

V2:
- Fixed compilation warning on ARM by casting to u64
- Link to v1: https://lore.kernel.org/netdev/[email protected]/
---

Ankit Garg (1):
gve: make nic clock reads thread safe

Jordan Rhee (2):
gve: skip error logging for retryable AdminQ commands
gve: implement PTP gettimex64

 drivers/net/ethernet/google/gve/gve.h         |  20 +-
 drivers/net/ethernet/google/gve/gve_adminq.c  |  41 +-
 drivers/net/ethernet/google/gve/gve_adminq.h  |   4 +-
 drivers/net/ethernet/google/gve/gve_ethtool.c |   6 +-
 drivers/net/ethernet/google/gve/gve_ptp.c     | 369 ++++++++++++++----
 5 files changed, 344 insertions(+), 96 deletions(-)

base-commit: 8ebd24a7822cbae25beeafba49b2159d6a68a5f2

Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author maintainer
#1 lore raw

PATCH v8 1/3 gve: skip error logging for retryable AdminQ commands

From: Jordan Rhee <[email protected]>

AdminQ commands may return -EAGAIN under certain transient conditions. These commands are intended to be retried by the driver, so logging a formal error to the system log is misleading and creates unnecessary noise.

Modify the logging logic to skip the error message when the result is -EAGAIN, and move logging to dev_err_ratelimited() to avoid spamming the log.

---
Changes in v8:
- Fixed opcode extraction for extended commands (Sashiko)

Changes in v7:
- fixed type of err to be int instead of u32 (Sashiko)
- Picked up Jake Keller's review tag

Changes in v4:
- call out change to dev_err_ratelimited() in the commit message (Jacob Keller)
- remove extra print when adminQ status is GVE_ADMINQ_COMMAND_UNSET (Jacob Keller)
---

---
 drivers/net/ethernet/google/gve/gve_adminq.c | 41 ++++++++++++++++----
 1 file changed, 33 insertions(+), 8 deletions(-)
drivers/net/ethernet/google/gve/gve_adminq.c +33 -8
index 08587bf40ed4..0d5a67523cba 100644
@@ -416,16 +416,10 @@ static bool gve_adminq_wait_for_cmd(struct gve_priv *priv, u32 prod_cnt)
 
 static int gve_adminq_parse_err(struct gve_priv *priv, u32 status)
 {
-	if (status != GVE_ADMINQ_COMMAND_PASSED &&
-	    status != GVE_ADMINQ_COMMAND_UNSET) {
-		dev_err(&priv->pdev->dev, "AQ command failed with status %d\n", status);
-		priv->adminq_cmd_fail++;
-	}
 	switch (status) {
 	case GVE_ADMINQ_COMMAND_PASSED:
 		return 0;
 	case GVE_ADMINQ_COMMAND_UNSET:
-		dev_err(&priv->pdev->dev, "parse_aq_err: err and status both unset, this should not be possible.\n");
 		return -EINVAL;
 	case GVE_ADMINQ_COMMAND_ERROR_ABORTED:
 	case GVE_ADMINQ_COMMAND_ERROR_CANCELLED:
@@ -455,6 +449,27 @@ static int gve_adminq_parse_err(struct gve_priv *priv, u32 status)
 	}
 }
 
+static bool gve_adminq_is_retryable(enum gve_adminq_opcodes opcode)
+{
+	switch (opcode) {
+	case GVE_ADMINQ_REPORT_NIC_TIMESTAMP:
+		return true;
+	default:
+		return false;
+	}
+}
+
+static enum gve_adminq_opcodes gve_extract_opcode(union gve_adminq_command *cmd)
+{
+	u32 opcode;
+
+	opcode = be32_to_cpu(READ_ONCE(cmd->opcode));
+	if (opcode == GVE_ADMINQ_EXTENDED_COMMAND)
+		opcode = be32_to_cpu(cmd->extended_command.inner_opcode);
+
+	return opcode;
+}
+
 /* Flushes all AQ commands currently queued and waits for them to complete.
  * If there are failures, it will return the first error.
  */
@@ -477,14 +492,24 @@ static int gve_adminq_kick_and_wait(struct gve_priv *priv)
 
 	for (i = tail; i < head; i++) {
 		union gve_adminq_command *cmd;
-		u32 status, err;
+		u32 status;
+		int err;
 
 		cmd = &priv->adminq[i & priv->adminq_mask];
 		status = be32_to_cpu(READ_ONCE(cmd->status));
 		err = gve_adminq_parse_err(priv, status);
-		if (err)
+		if (err) {
+			enum gve_adminq_opcodes opcode = gve_extract_opcode(cmd);
+
+			priv->adminq_cmd_fail++;
+			if (!gve_adminq_is_retryable(opcode) || err != -EAGAIN)
+				dev_err_ratelimited(&priv->pdev->dev,
+						    "AQ command %d failed with status %d\n",
+						    opcode, status);
+
 			// Return the first error if we failed.
 			return err;
+		}
 	}
 
 	return 0;
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author maintainer
#2 lore raw

PATCH v8 2/3 gve: make nic clock reads thread safe

In reply to Harshitha Ramamurthy

From: Ankit Garg <[email protected]>

Add a mutex to protect the shared DMA buffer that receives NIC timestamp reports. The NIC timestamp will be read from two different
threads: the periodic worker and upcoming gettimex64.

Move clock registration to the last step of initialization to ensure that all data needed by the clock module is initialized before the clock is exposed to usermode.

---
Changes in v7:
- Picked up Jake Keller's review tag

Changes in v3:
- Reorder init/teardown to register PTP clock last, and simplify code
- Move ptp-related members from gve_priv to gve_ptp
- Only assign priv->ptp after ptp module is successfully initialized
---

---
 drivers/net/ethernet/google/gve/gve.h         |  12 +-
 drivers/net/ethernet/google/gve/gve_ethtool.c |   3 +-
 drivers/net/ethernet/google/gve/gve_ptp.c     | 134 ++++++++----------
 3 files changed, 63 insertions(+), 86 deletions(-)
drivers/net/ethernet/google/gve/gve.h +4 -8
index 1d66d3834f7e..7b69d0cfc0d5 100644
@@ -792,6 +792,9 @@ struct gve_ptp {
 	struct ptp_clock_info info;
 	struct ptp_clock *clock;
 	struct gve_priv *priv;
+	struct mutex nic_ts_read_lock; /* Protects nic_ts_report */
+	struct gve_nic_ts_report *nic_ts_report;
+	dma_addr_t nic_ts_report_bus;
 };
 
 struct gve_priv {
@@ -923,8 +926,6 @@ struct gve_priv {
 	bool nic_timestamp_supported;
 	struct gve_ptp *ptp;
 	struct kernel_hwtstamp_config ts_config;
-	struct gve_nic_ts_report *nic_ts_report;
-	dma_addr_t nic_ts_report_bus;
 	u64 last_sync_nic_counter; /* Clock counter from last NIC TS report */
 };
 
@@ -1201,7 +1202,7 @@ static inline bool gve_supports_xdp_xmit(struct gve_priv *priv)
 
 static inline bool gve_is_clock_enabled(struct gve_priv *priv)
 {
-	return priv->nic_ts_report;
+	return priv->ptp;
 }
 
 /* gqi napi handler defined in gve_main.c */
@@ -1321,14 +1322,9 @@ int gve_flow_rules_reset(struct gve_priv *priv);
 int gve_init_rss_config(struct gve_priv *priv, u16 num_queues);
 /* PTP and timestamping */
 #if IS_ENABLED(CONFIG_PTP_1588_CLOCK)
-int gve_clock_nic_ts_read(struct gve_priv *priv);
 int gve_init_clock(struct gve_priv *priv);
 void gve_teardown_clock(struct gve_priv *priv);
 #else /* CONFIG_PTP_1588_CLOCK */
-static inline int gve_clock_nic_ts_read(struct gve_priv *priv)
-{
-	return -EOPNOTSUPP;
-}
 
 static inline int gve_init_clock(struct gve_priv *priv)
 {
drivers/net/ethernet/google/gve/gve_ethtool.c +1 -2
index dc2213b5ce24..4fd7e8a442c5 100644
@@ -972,8 +972,7 @@ static int gve_get_ts_info(struct net_device *netdev,
 		info->rx_filters |= BIT(HWTSTAMP_FILTER_NONE) |
 				    BIT(HWTSTAMP_FILTER_ALL);
 
-		if (priv->ptp)
-			info->phc_index = ptp_clock_index(priv->ptp->clock);
+		info->phc_index = ptp_clock_index(priv->ptp->clock);
 	}
 
 	return 0;
drivers/net/ethernet/google/gve/gve_ptp.c +58 -76

188 lines not on this page · raw message

Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author maintainer
#3 lore raw

PATCH v8 3/3 gve: implement PTP gettimex64

In reply to Harshitha Ramamurthy

From: Jordan Rhee <[email protected]>

Enable chrony and phc2sys to synchronize system clock to NIC clock.

Two paths are implemented: a precise path using system counter values sampled by the device, and a fallback path using system counter values sampled in the driver using ptp_read_system_prets()/postts().

To use the precise path, the current system clocksource must match the units returned by the device, which on x86 is X86_TSC and on ARM64 is ARM_ARCH_COUNTER. The clockid requested for the cross-timestamp must be either CLOCK_REALTIME or CLOCK_MONOTONIC_RAW. These conditions hold by default on GCP VMs using Chrony, so we expect the precise path to be used the vast majority of the time. If the system clocksource is changed to kvm-clock, it activates the fallback path. Ethtool counters have been added to count how many times each path is used.

The uncertainty window in the precise path is typically around 1-2us, while in the fallback path is around 60-80us.

Stub implementions of adjfine and adjtime are added to avoid NULL dereference when phc2sys tries to adjust the clock.

---
Changes in v7:
- Actually committed the stubs for adjtime and adjfine. (Sashiko)
- Picked up Jake Keller's review tag

Changes in v6:
- Added a fallback to driver-sampled time sandwich that is used when the following conditions are not met:
- The system clock source is X86_TSC or ARM_ARCH_COUNTER
- The requested clockid is CLOCK_REALTIME or CLOCK_MONOTONIC_RAW
- The architecture is x86 or ARM64
- Added ethtool statistics to count how many cross-timestamps used the precise path versus fallback path.
- Fixed printf format specifier.
- Added stub implementions of adjtime and adjfine to prevent NULL dereference when phc2sys tries to adjust clock.
- Moved system time snapshot back to gve_ptp_gettimex64() so we can get the current system clock source from it. It is OK for it to not be inside the mutex or retry loop because lock contention and retries should be extremely rare, and chrony filters out bad samples.

Changes in v5:
- Reformulate retry loop in terms of total timeout (Jakub Kicinski)

Changes in v3:
- Take system time snapshot inside the mutex
- Return -EOPNOTSUPP if cross-timestamp is requested on an arch other than x86 or arm64

Changes in v2:
- fix compilation warning on ARM by casting cycles_t to u64
---

---
 drivers/net/ethernet/google/gve/gve.h         |   8 +
 drivers/net/ethernet/google/gve/gve_adminq.h  |   4 +-
 drivers/net/ethernet/google/gve/gve_ethtool.c |   3 +
 drivers/net/ethernet/google/gve/gve_ptp.c     | 249 +++++++++++++++++-
 4 files changed, 255 insertions(+), 9 deletions(-)
drivers/net/ethernet/google/gve/gve.h +8 -0
index 7b69d0cfc0d5..4de3ce60060e 100644
@@ -880,6 +880,14 @@ struct gve_priv {
 	u32 stats_report_trigger_cnt; /* count of device-requested stats-reports since last reset */
 	u32 suspend_cnt; /* count of times suspended */
 	u32 resume_cnt; /* count of times resumed */
+	/* count of cross-timestamps attempted using system timestamps
+	 * from the AQ command
+	 */
+	u32 ptp_precise_xtstamps;
+	/* count of cross-timestamps attempted using system timestamps sampled
+	 * by the driver
+	 */
+	u32 ptp_fallback_xtstamps;
 	struct workqueue_struct *gve_wq;
 	struct work_struct service_task;
 	struct work_struct stats_report_task;
drivers/net/ethernet/google/gve/gve_adminq.h +2 -2
index 22a74b6aa17e..e6dcf6da9091 100644
@@ -411,8 +411,8 @@ static_assert(sizeof(struct gve_adminq_report_nic_ts) == 16);
 
 struct gve_nic_ts_report {
 	__be64 nic_timestamp; /* NIC clock in nanoseconds */
-	__be64 reserved1;
-	__be64 reserved2;
+	__be64 pre_cycles; /* System cycle counter before NIC clock read */
+	__be64 post_cycles; /* System cycle counter after NIC clock read */
 	__be64 reserved3;
 	__be64 reserved4;
 };
drivers/net/ethernet/google/gve/gve_ethtool.c +3 -0
index 4fd7e8a442c5..8a088dcc3603 100644
@@ -46,6 +46,7 @@ static const char gve_gstrings_main_stats[][ETH_GSTRING_LEN] = {
 	"rx_hsplit_unsplit_pkt",
 	"interface_up_cnt", "interface_down_cnt", "reset_cnt",
 	"page_alloc_fail", "dma_mapping_error", "stats_report_trigger_cnt",
+	"ptp_precise_xtstamps", "ptp_fallback_xtstamps",
 };
 
 static const char gve_gstrings_rx_stats[][ETH_GSTRING_LEN] = {
@@ -269,6 +270,8 @@ gve_get_ethtool_stats(struct net_device *netdev,
 	data[i++] = priv->page_alloc_fail;
 	data[i++] = priv->dma_mapping_error;
 	data[i++] = priv->stats_report_trigger_cnt;
+	data[i++] = priv->ptp_precise_xtstamps;
+	data[i++] = priv->ptp_fallback_xtstamps;
 	i = GVE_MAIN_STATS_LEN;
 
 	rx_base_stats_idx = 0;
drivers/net/ethernet/google/gve/gve_ptp.c +242 -7

290 lines not on this page · raw message

Signature · 1 line
2.54.0.563.g4f69b47b94-goog
maintainer
#4 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 17 lines · Harshitha Ramamurthy

From: Jordan Rhee <[email protected]>

Enable chrony and phc2sys to synchronize system clock to NIC clock.

Two paths are implemented: a precise path using system counter values sampled by the device, and a fallback path using system counter values sampled in the driver using ptp_read_system_prets()/postts().

To use the precise path, the current system clocksource must match the units returned by the device, which on x86 is X86_TSC and on ARM64 is ARM_ARCH_COUNTER. The clockid requested for the cross-timestamp must be either CLOCK_REALTIME or CLOCK_MONOTONIC_RAW. These conditions hold by default on GCP VMs using Chrony, so we expect the precise path to be used the vast majority of the time. If the system clocksource is changed to kvm-clock, it activates the fallback path. Ethtool counters have been added to count how many times each path is used.

Quoted 5 lines

The uncertainty window in the precise path is typically around 1-2us, while in the fallback path is around 60-80us.

Stub implementions of adjfine and adjtime are added to avoid NULL dereference when phc2sys tries to adjust the clock.

Sorry that I did not react to this earlier, but I was burried in regressions and allowed myself to take a few days off.

Quoted 6 lines
drivers/net/ethernet/google/gve/gve_ptp.c +6 -0
+/*
+ * Read NIC clock by issuing the AQ command. The command is subject to
+ * rate limiting and may need to be retried. Requires nic_ts_read_lock
+ * to be held.
+ */
+static int gve_ptp_read_timestamp(struct gve_ptp *ptp, cycles_t *pre_cycles,

drivers/net/ethernet/google/gve/gve_ptp.c line 43

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+				  cycles_t *post_cycles)
+{
+	unsigned long deadline = jiffies + msecs_to_jiffies(100);
+	unsigned long delay_us = 1000;
+	int err;
+
+	lockdep_assert_held(&ptp->nic_ts_read_lock);
+
+	do {
+		*pre_cycles = get_cycles();

This is a completely non-sensical hack. Why do you need get_cycles() here, which is a horrible and ill-defined interface that others are trying to get rid of?

Just because it's still there is not a good answer and it's actually not required at all. See below.

Quoted 20 lines
drivers/net/ethernet/google/gve/gve_ptp.c +20 -0
+		err = gve_adminq_report_nic_ts(ptp->priv,
+					       ptp->nic_ts_report_bus);
+
+		/* Prevent get_cycles() from being speculatively executed
+		 * before the AdminQ command
+		 */
+		rmb();
+		*post_cycles = get_cycles();
+		if (likely(err != -EAGAIN))
+			return err;
+
+		fsleep(delay_us);
+
+		/* Exponential backoff */
+		delay_us *= 2;
+	} while (time_before(jiffies, deadline));
+
+	return -ETIMEDOUT;
+}
+

drivers/net/ethernet/google/gve/gve_ptp.c line 72

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +4 -1
 /* Read the nic timestamp from hardware via the admin queue. */
-static int gve_clock_nic_ts_read(struct gve_ptp *ptp, u64 *nic_raw)
+static int gve_clock_nic_ts_read(struct gve_ptp *ptp, u64 *nic_raw,
+				 struct gve_sysclock_sample *sysclock)
 {
+	cycles_t host_pre_cycles, host_post_cycles;
+	struct gve_nic_ts_report *ts_report;
 	int err;
 
 	mutex_lock(&ptp->nic_ts_read_lock);

Why is this lock taken _after_ the regular (fallback) pre/post timestamps are aquired?

What's wrong with doing:

       do {
         	guard(mutex)(&ptp->nic_ts_read_lock);

                ptp_read_system_prets(sts);
                err = read_nic_timestamp(...);
                ptp_read_system_postts(sts);
       } while (err && !timeout(...));

       return err;

which moves the "fallback" timestamp right next to the actual hardware readout?

That would make the "fallback" case too precise, right?

After noticing the obvious, I just checked what our new AI review overlord "sashiko" has to say about this:

"Does wrapping the timestamp read outside the locks and retry loops skew the
measurements?

In the fallback path, ptp_read_system_prets() is captured before calling gve_clock_nic_ts_read(), and postts() is captured after it returns. However, gve_clock_nic_ts_read() acquires ptp->nic_ts_read_lock and calls gve_ptp_read_timestamp(), which can sleep using fsleep() during retries. This means the prets/postts window could include mutex wait times and sleep durations."

It _IS_ actually on spot. So why the heck did this garbage get merged without addressing this obvious fail?

What "sashiko" actually saw aside of that, which I didn't see myself when looking at this, is:

"Similarly, in gve_ptp_read_timestamp(), the get_cycles() bounds are taken
outside the gve_adminq_report_nic_ts() call, which acquires the shared priv->adminq_lock. If there is lock contention, the cycle bounds could become extremely wide."

Oh well.

So what you really want is:

       do {
         	guard(mutex)(&ptp->nic_ts_read_lock);
         	guard(mutex)(&gpe_priv->adminq_lock);

                ptp_read_system_prets(sts);
                err = read_nic_timestamp(...) {
                   	...
                   	return gve_adminq_execute_cmd_locked(....);
                      }
                ptp_read_system_postts(sts);
       } while (err && !timeout(...));

       return err;

Or just rely on gpe_priv->adminq_lock in the first place. No?

But what's worse and escaped the AI scrutiny is:

Your attempt to convert these 'get_cycles()' time stamps after the fact and outside of the timekeeping core protection is fundamentally wrong.

get_device_system_crosststamp() does

      do {
      		seq = read_seqcount_begin(&tk_core.seq);
                take_timestamps(...);
                convert_timestamps(...)
      } while (read_seqcount_retry(&tk_core.seq, seq));

which covers the whole sequence of taking the snapshots from the hardware and the conversion.

Your abuse of this is completely out of spec. Just because it did not blow up in your face yet does not make it in any way correct. You do not even get bonus points for creative abuse.

Now let me look at the "firmware" provided timestamps.

That's the poor mans emulation of actual hardware timestamps aka PTM.

Why do you need all this pre_nic/post_nic muck there? Fix your firmware to actually honor PTM and not provide some made up version of it.

Also the whole debug mechanism of comparing the time stamps of get_cycles() with the timestamps provided by firmware tells me that your firmware is a hacked together piece of garbage.

If you want to use "hardware" timestamps then populate the ptp.info.getcrosststamp() callback.

If your firmware really can't do PTM and only provides pre and post values, then you simply can take the midpoint in your getcrosststamp() callback:

      do {
         	guard(mutex)(&ptp->nic_ts_read_lock);
                err = read_nic_timestamp(...);
                system_counterval->cycles = (nic_pre + nic_post) / 2;
      } while (err && !timeout(...));

If you do not even trust your firmware then you still can validate it easily without creating horrible hacks:

      do {
         	guard(mutex)(...);

                ptp_read_system_prets(&ctx->sts);
                err = read_nic_timestamp(...);
                system_counterval->cycles = (nic_pre + nic_post) / 2;
                ptp_read_system_postts(&ctx->sts);
      } while (err && !timeout(...));

and then check the ctx->sts timestamps against the results provided by get_device_system_crosststamp() after conversion in your ptp.info.getcrosststamp() callback:

        err = get_device_system_crosststamp(..., &ctx);
        if (err)
           return err;
        if (ctx.sts.pre_ts > xtstamp.sys... || ctx.sts.post_ts < xtstamp.sys...)
           return -EBROKENFIRMWARE;        

no?

Jakub, please back out this hackery before it makes a precedence for others to copy from.

Thanks,

tglx

maintainer
#5 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 2 lines · On Wed, 20 May 2026 23:08:42 +0200 Thomas Gleixner wrote:

Jakub, please back out this hackery before it makes a precedence for others to copy from.

Done! 0ae361f7e43c in net-next.

I'd also appreciate if you could cast your eyes over:
https://lore.kernel.org/[email protected]
Different kettle of fish, but firmly more time than network..

#6 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

In reply to Thomas Gleixner

Hi Thomas,
Thank you for the review. We plan to rework this to use
https://lore.kernel.org/all/[email protected]/,
which will let us use the midpoint of pre and post while still propagating the uncertainty window up the stack. I am going to address some of the concerns you raised simply for the record, not because I am trying to convince you one way or another. I do not expect a response. Thank you,
Jordan

Quoted 40 lines · Thomas Gleixner
Quoted 17 lines · Harshitha Ramamurthy

From: Jordan Rhee <[email protected]>

Enable chrony and phc2sys to synchronize system clock to NIC clock.

Two paths are implemented: a precise path using system counter values sampled by the device, and a fallback path using system counter values sampled in the driver using ptp_read_system_prets()/postts().

To use the precise path, the current system clocksource must match the units returned by the device, which on x86 is X86_TSC and on ARM64 is ARM_ARCH_COUNTER. The clockid requested for the cross-timestamp must be either CLOCK_REALTIME or CLOCK_MONOTONIC_RAW. These conditions hold by default on GCP VMs using Chrony, so we expect the precise path to be used the vast majority of the time. If the system clocksource is changed to kvm-clock, it activates the fallback path. Ethtool counters have been added to count how many times each path is used.

Quoted 5 lines

The uncertainty window in the precise path is typically around 1-2us, while in the fallback path is around 60-80us.

Stub implementions of adjfine and adjtime are added to avoid NULL dereference when phc2sys tries to adjust the clock.

Sorry that I did not react to this earlier, but I was burried in regressions and allowed myself to take a few days off.

Quoted 12 lines
drivers/net/ethernet/google/gve/gve_ptp.c +12 -0
+/*
+ * Read NIC clock by issuing the AQ command. The command is subject to
+ * rate limiting and may need to be retried. Requires nic_ts_read_lock
+ * to be held.
+ */
+static int gve_ptp_read_timestamp(struct gve_ptp *ptp, cycles_t *pre_cycles,
+                               cycles_t *post_cycles)
+{
+     unsigned long deadline = jiffies + msecs_to_jiffies(100);
+     unsigned long delay_us = 1000;
+     int err;
+
Quoted 8 lines

drivers/net/ethernet/google/gve/gve_ptp.c line 43

Quoted 4 lines
drivers/net/ethernet/google/gve/gve_ptp.c +4 -0
+     lockdep_assert_held(&ptp->nic_ts_read_lock);
+
+     do {
+             *pre_cycles = get_cycles();

This is a completely non-sensical hack. Why do you need get_cycles() here, which is a horrible and ill-defined interface that others are trying to get rid of?

We use get_cycles() purely as a sanity check against the TSC values returned by firmware. We do not use them in the time conversion. This check found a serious correctness bug in the firmware.

Quoted 50 lines

Just because it's still there is not a good answer and it's actually not required at all. See below.

Quoted 20 lines
drivers/net/ethernet/google/gve/gve_ptp.c +20 -0
+             err = gve_adminq_report_nic_ts(ptp->priv,
+                                            ptp->nic_ts_report_bus);
+
+             /* Prevent get_cycles() from being speculatively executed
+              * before the AdminQ command
+              */
+             rmb();
+             *post_cycles = get_cycles();
+             if (likely(err != -EAGAIN))
+                     return err;
+
+             fsleep(delay_us);
+
+             /* Exponential backoff */
+             delay_us *= 2;
+     } while (time_before(jiffies, deadline));
+
+     return -ETIMEDOUT;
+}
+

drivers/net/ethernet/google/gve/gve_ptp.c line 72

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +4 -1
 /* Read the nic timestamp from hardware via the admin queue. */
-static int gve_clock_nic_ts_read(struct gve_ptp *ptp, u64 *nic_raw)
+static int gve_clock_nic_ts_read(struct gve_ptp *ptp, u64 *nic_raw,
+                              struct gve_sysclock_sample *sysclock)
 {
+     cycles_t host_pre_cycles, host_post_cycles;
+     struct gve_nic_ts_report *ts_report;
      int err;
 
      mutex_lock(&ptp->nic_ts_read_lock);

Why is this lock taken _after_ the regular (fallback) pre/post timestamps are aquired?

What's wrong with doing:

       do {
                guard(mutex)(&ptp->nic_ts_read_lock);

                ptp_read_system_prets(sts);
                err = read_nic_timestamp(...);
                ptp_read_system_postts(sts);
       } while (err && !timeout(...));

       return err;
Quoted 2 lines

which moves the "fallback" timestamp right next to the actual hardware readout?

The lock is taken at the smallest scope possible, which does not include the pre/post TS reading. This routine is called by multiple callers, not all of which need the pre/post timestamp. Options are to:
- move the pre/post TS reading here and add branches to conditionally
sample them only when needed
- always capture the pre/post TS readings and discard them when not needed
- duplicate the locking logic, once for path that needs pre/post TS,
once for path that doesn't need pre/post TS

Since the fallback path is expected to be rarely used, lock contention and retries are expected to be extremely rare, and chrony is resilient to samples with high uncertainty window, I chose to prioritize cleanliness of the code and keep the pre/post TS reading in the caller where it is actually needed. That said, I do not feel strongly about this and would be open to moving pre/post inside the mutex if I were sending another revision.

Quoted 2 lines

That would make the "fallback" case too precise, right?

Moving pre/post inside the mutex makes no measurable difference because the lock is rarely contended. There is 4 orders of magnitude difference in RMS offset between precise and fallback paths.

Quoted 14 lines

After noticing the obvious, I just checked what our new AI review overlord "sashiko" has to say about this:

"Does wrapping the timestamp read outside the locks and retry loops skew the
measurements?

In the fallback path, ptp_read_system_prets() is captured before calling gve_clock_nic_ts_read(), and postts() is captured after it returns. However, gve_clock_nic_ts_read() acquires ptp->nic_ts_read_lock and calls gve_ptp_read_timestamp(), which can sleep using fsleep() during retries. This means the prets/postts window could include mutex wait times and sleep durations."

Quoted 2 lines

It _IS_ actually on spot. So why the heck did this garbage get merged without addressing this obvious fail?

- The fallback path is expected to be rarely used since it requires changing the default configuration
- The lock is rarely contended as there are only 2 callers, one of which only executes once every 250ms,
and retries would only occur if a VM exceeded their rate limits
which have been tuned not to occur
under normal chrony calling patterns.

Quoted 10 lines

What "sashiko" actually saw aside of that, which I didn't see myself when looking at this, is:

"Similarly, in gve_ptp_read_timestamp(), the get_cycles() bounds are taken
outside the gve_adminq_report_nic_ts() call, which acquires the shared priv->adminq_lock. If there is lock contention, the cycle bounds could become extremely wide."

Oh well.

get_cycles() is only used for sanity checking the values from firmware, not in any time conversion.

Quoted 17 lines

So what you really want is:

       do {
                guard(mutex)(&ptp->nic_ts_read_lock);
                guard(mutex)(&gpe_priv->adminq_lock);

                ptp_read_system_prets(sts);
                err = read_nic_timestamp(...) {
                        ...
                        return gve_adminq_execute_cmd_locked(....);
                      }
                ptp_read_system_postts(sts);
       } while (err && !timeout(...));

       return err;
Quoted 1 line

Or just rely on gpe_priv->adminq_lock in the first place. No?

adminq_lock is private to the adminq layer and protects adminq shared data structures. nic_ts_read_lock protects the global DMA buffer that receives the timestamps. Since retries are a response to rate limiting, we must wait between retries, so we do not want to hold the adminq lock across these retries as it would block other non rate-limited commands.

Quoted 15 lines

But what's worse and escaped the AI scrutiny is:

Your attempt to convert these 'get_cycles()' time stamps after the fact and outside of the timekeeping core protection is fundamentally wrong.

get_device_system_crosststamp() does

      do {
                seq = read_seqcount_begin(&tk_core.seq);
                take_timestamps(...);
                convert_timestamps(...)
      } while (read_seqcount_retry(&tk_core.seq, seq));
Quoted 6 lines

which covers the whole sequence of taking the snapshots from the hardware and the conversion.

Your abuse of this is completely out of spec. Just because it did not blow up in your face yet does not make it in any way correct. You do not even get bonus points for creative abuse.

We use ktime_get_snapshot() to capture a historical snapshot before sampling the TSC, and we pass it to get_device_system_crosststamp() which uses the snapshot to interpolate the sample if it occurs before the current timekeeping interval. Perfectly within spec.

Quoted 8 lines

Now let me look at the "firmware" provided timestamps.

That's the poor mans emulation of actual hardware timestamps aka PTM.

Why do you need all this pre_nic/post_nic muck there? Fix your firmware to actually honor PTM and not provide some made up version of it.

This has to run on platforms that don't support PTM.

Quoted 12 lines

Also the whole debug mechanism of comparing the time stamps of get_cycles() with the timestamps provided by firmware tells me that your firmware is a hacked together piece of garbage.

If you want to use "hardware" timestamps then populate the ptp.info.getcrosststamp() callback.

If your firmware really can't do PTM and only provides pre and post values, then you simply can take the midpoint in your getcrosststamp() callback:

Quoted 5 lines
      do {
                guard(mutex)(&ptp->nic_ts_read_lock);
                err = read_nic_timestamp(...);
                system_counterval->cycles = (nic_pre + nic_post) / 2;
      } while (err && !timeout(...));

We considered returning the midpoint of pre/post up through getcrosststamp(), but there was
no way to communicate the uncertainty interval which is important for some of our use cases.
https://lore.kernel.org/all/[email protected]/
fixes that issue, so we can use that when it lands.

Quoted 17 lines

If you do not even trust your firmware then you still can validate it easily without creating horrible hacks:

      do {
                guard(mutex)(...);

                ptp_read_system_prets(&ctx->sts);
                err = read_nic_timestamp(...);
                system_counterval->cycles = (nic_pre + nic_post) / 2;
                ptp_read_system_postts(&ctx->sts);
      } while (err && !timeout(...));

and then check the ctx->sts timestamps against the results provided by get_device_system_crosststamp() after conversion in your ptp.info.getcrosststamp() callback:

Quoted 7 lines
        err = get_device_system_crosststamp(..., &ctx);
        if (err)
           return err;
        if (ctx.sts.pre_ts > xtstamp.sys... || ctx.sts.post_ts < xtstamp.sys...)
           return -EBROKENFIRMWARE;

no?

get_device_system_crosststamp() has nontrivial logic that operates on the system timestamps, so I am not confident that a bad TSC value would be detected if we ran it through get_device_system_crosststamp() first. The check is simplest
and strongest when performed against the raw TSC values received from the device, before passing them to any kernel API. But I hear your point about mistrusting
the firmware enough to need this check.

Quoted 7 lines

Jakub, please back out this hackery before it makes a precedence for others to copy from.

Thanks,

tglx

#7 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Hello,

We would like to request the community's guidance on how to proceed with adding cross-timestamp functionality to GVE. The key challenge is that the NIC clock can only be sampled in the hypervisor because the NIC time registers are only present on the PF, and a hypercall takes 60-80us. To minimize the uncertainty window, the hypervisor takes a TSC sandwich around the reading with an uncertainty window of ~1.2us, converts it to guest TSC, and returns it to the guest.

The goals which led to this implementation were to minimize the uncertainty window and communicate the uncertainty window up the stack. I've reviewed
https://lore.kernel.org/netdev/[email protected]/
but I'm not sure how we would use it, so if it is intended to support our use case I would appreciate if someone could explain how we should use it.

Here are some options on how to proceed, but other ideas are welcome.

1) resubmit the patch with the same high level approach with the feedback addressed. This is our preference since it achieves the smallest possible uncertainty window and communicates it up the stack.
- move system timestamp sampling and ktime_get_snapshot()
inside the mutex
- remove get_cycles() and the ordering sanity check
2) implement getcrosstimestamp() and return the midpoint of pre/post, but lose the uncertainty window
3) wait for https://lore.kernel.org/all/[email protected]/
which adds error_bound to getcrosstimestamp()
- error_bound calculation: convert TSC delta to nsec using
tsc_khz/arch_timer_get_cntfrq() => clocks_calc_mult_shift() => clocksource_cyc2ns()
- since this patch changes usermode interface, chrony/phc2sys would
need changes to consume the new IOCTLs, and it is unclear whether there is an intention to do so
4) implement gettimex64() using only system timestamps sampled in the VM (i.e. remove the precise path). Accept uncertainty window of 60-80us vs. 1-2us
5) implement gettimex64() using the midpoint of pre/post to make a single call to get_device_system_crosststamp(), then compute the pre/post ktimes by adding/subtracting the delta/2 between the TSC readings from the firmware

Thank you,
Jordan

Quoted 310 lines · Jordan Rhee

Hi Thomas,
Thank you for the review. We plan to rework this to use
https://lore.kernel.org/all/[email protected]/,
which will let us use the midpoint of pre and post while still propagating the uncertainty window up the stack. I am going to address some of the concerns you raised simply for the record, not because I am trying to convince you one way or another. I do not expect a response. Thank you,
Jordan

Quoted 40 lines · Thomas Gleixner
Quoted 17 lines · Harshitha Ramamurthy

From: Jordan Rhee <[email protected]>

Enable chrony and phc2sys to synchronize system clock to NIC clock.

Two paths are implemented: a precise path using system counter values sampled by the device, and a fallback path using system counter values sampled in the driver using ptp_read_system_prets()/postts().

To use the precise path, the current system clocksource must match the units returned by the device, which on x86 is X86_TSC and on ARM64 is ARM_ARCH_COUNTER. The clockid requested for the cross-timestamp must be either CLOCK_REALTIME or CLOCK_MONOTONIC_RAW. These conditions hold by default on GCP VMs using Chrony, so we expect the precise path to be used the vast majority of the time. If the system clocksource is changed to kvm-clock, it activates the fallback path. Ethtool counters have been added to count how many times each path is used.

Quoted 5 lines

The uncertainty window in the precise path is typically around 1-2us, while in the fallback path is around 60-80us.

Stub implementions of adjfine and adjtime are added to avoid NULL dereference when phc2sys tries to adjust the clock.

Sorry that I did not react to this earlier, but I was burried in regressions and allowed myself to take a few days off.

Quoted 12 lines
drivers/net/ethernet/google/gve/gve_ptp.c +12 -0
+/*
+ * Read NIC clock by issuing the AQ command. The command is subject to
+ * rate limiting and may need to be retried. Requires nic_ts_read_lock
+ * to be held.
+ */
+static int gve_ptp_read_timestamp(struct gve_ptp *ptp, cycles_t *pre_cycles,
+                               cycles_t *post_cycles)
+{
+     unsigned long deadline = jiffies + msecs_to_jiffies(100);
+     unsigned long delay_us = 1000;
+     int err;
+
Quoted 8 lines

drivers/net/ethernet/google/gve/gve_ptp.c line 43

Quoted 4 lines
drivers/net/ethernet/google/gve/gve_ptp.c +4 -0
+     lockdep_assert_held(&ptp->nic_ts_read_lock);
+
+     do {
+             *pre_cycles = get_cycles();

This is a completely non-sensical hack. Why do you need get_cycles() here, which is a horrible and ill-defined interface that others are trying to get rid of?

We use get_cycles() purely as a sanity check against the TSC values returned by firmware. We do not use them in the time conversion. This check found a serious correctness bug in the firmware.

Quoted 50 lines

Just because it's still there is not a good answer and it's actually not required at all. See below.

Quoted 20 lines
drivers/net/ethernet/google/gve/gve_ptp.c +20 -0
+             err = gve_adminq_report_nic_ts(ptp->priv,
+                                            ptp->nic_ts_report_bus);
+
+             /* Prevent get_cycles() from being speculatively executed
+              * before the AdminQ command
+              */
+             rmb();
+             *post_cycles = get_cycles();
+             if (likely(err != -EAGAIN))
+                     return err;
+
+             fsleep(delay_us);
+
+             /* Exponential backoff */
+             delay_us *= 2;
+     } while (time_before(jiffies, deadline));
+
+     return -ETIMEDOUT;
+}
+

drivers/net/ethernet/google/gve/gve_ptp.c line 72

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +4 -1
 /* Read the nic timestamp from hardware via the admin queue. */
-static int gve_clock_nic_ts_read(struct gve_ptp *ptp, u64 *nic_raw)
+static int gve_clock_nic_ts_read(struct gve_ptp *ptp, u64 *nic_raw,
+                              struct gve_sysclock_sample *sysclock)
 {
+     cycles_t host_pre_cycles, host_post_cycles;
+     struct gve_nic_ts_report *ts_report;
      int err;
 
      mutex_lock(&ptp->nic_ts_read_lock);

Why is this lock taken _after_ the regular (fallback) pre/post timestamps are aquired?

What's wrong with doing:

       do {
                guard(mutex)(&ptp->nic_ts_read_lock);

                ptp_read_system_prets(sts);
                err = read_nic_timestamp(...);
                ptp_read_system_postts(sts);
       } while (err && !timeout(...));

       return err;
Quoted 2 lines

which moves the "fallback" timestamp right next to the actual hardware readout?

The lock is taken at the smallest scope possible, which does not include the pre/post TS reading. This routine is called by multiple callers, not all of which need the pre/post timestamp. Options are to:
- move the pre/post TS reading here and add branches to conditionally
sample them only when needed
- always capture the pre/post TS readings and discard them when not needed
- duplicate the locking logic, once for path that needs pre/post TS,
once for path that doesn't need pre/post TS

Since the fallback path is expected to be rarely used, lock contention and retries are expected to be extremely rare, and chrony is resilient to samples with high uncertainty window, I chose to prioritize cleanliness of the code and keep the pre/post TS reading in the caller where it is actually needed. That said, I do not feel strongly about this and would be open to moving pre/post inside the mutex if I were sending another revision.

Quoted 2 lines

That would make the "fallback" case too precise, right?

Moving pre/post inside the mutex makes no measurable difference because the lock is rarely contended. There is 4 orders of magnitude difference in RMS offset between precise and fallback paths.

Quoted 14 lines

After noticing the obvious, I just checked what our new AI review overlord "sashiko" has to say about this:

"Does wrapping the timestamp read outside the locks and retry loops skew the
measurements?

In the fallback path, ptp_read_system_prets() is captured before calling gve_clock_nic_ts_read(), and postts() is captured after it returns. However, gve_clock_nic_ts_read() acquires ptp->nic_ts_read_lock and calls gve_ptp_read_timestamp(), which can sleep using fsleep() during retries. This means the prets/postts window could include mutex wait times and sleep durations."

Quoted 2 lines

It _IS_ actually on spot. So why the heck did this garbage get merged without addressing this obvious fail?

- The fallback path is expected to be rarely used since it requires changing the default configuration
- The lock is rarely contended as there are only 2 callers, one of which only executes once every 250ms,
and retries would only occur if a VM exceeded their rate limits
which have been tuned not to occur
under normal chrony calling patterns.

Quoted 10 lines

What "sashiko" actually saw aside of that, which I didn't see myself when looking at this, is:

"Similarly, in gve_ptp_read_timestamp(), the get_cycles() bounds are taken
outside the gve_adminq_report_nic_ts() call, which acquires the shared priv->adminq_lock. If there is lock contention, the cycle bounds could become extremely wide."

Oh well.

get_cycles() is only used for sanity checking the values from firmware, not in any time conversion.

Quoted 17 lines

So what you really want is:

       do {
                guard(mutex)(&ptp->nic_ts_read_lock);
                guard(mutex)(&gpe_priv->adminq_lock);

                ptp_read_system_prets(sts);
                err = read_nic_timestamp(...) {
                        ...
                        return gve_adminq_execute_cmd_locked(....);
                      }
                ptp_read_system_postts(sts);
       } while (err && !timeout(...));

       return err;
Quoted 1 line

Or just rely on gpe_priv->adminq_lock in the first place. No?

adminq_lock is private to the adminq layer and protects adminq shared data structures. nic_ts_read_lock protects the global DMA buffer that receives the timestamps. Since retries are a response to rate limiting, we must wait between retries, so we do not want to hold the adminq lock across these retries as it would block other non rate-limited commands.

Quoted 15 lines

But what's worse and escaped the AI scrutiny is:

Your attempt to convert these 'get_cycles()' time stamps after the fact and outside of the timekeeping core protection is fundamentally wrong.

get_device_system_crosststamp() does

      do {
                seq = read_seqcount_begin(&tk_core.seq);
                take_timestamps(...);
                convert_timestamps(...)
      } while (read_seqcount_retry(&tk_core.seq, seq));
Quoted 6 lines

which covers the whole sequence of taking the snapshots from the hardware and the conversion.

Your abuse of this is completely out of spec. Just because it did not blow up in your face yet does not make it in any way correct. You do not even get bonus points for creative abuse.

We use ktime_get_snapshot() to capture a historical snapshot before sampling the TSC, and we pass it to get_device_system_crosststamp() which uses the snapshot to interpolate the sample if it occurs before the current timekeeping interval. Perfectly within spec.

Quoted 8 lines

Now let me look at the "firmware" provided timestamps.

That's the poor mans emulation of actual hardware timestamps aka PTM.

Why do you need all this pre_nic/post_nic muck there? Fix your firmware to actually honor PTM and not provide some made up version of it.

This has to run on platforms that don't support PTM.

Quoted 12 lines

Also the whole debug mechanism of comparing the time stamps of get_cycles() with the timestamps provided by firmware tells me that your firmware is a hacked together piece of garbage.

If you want to use "hardware" timestamps then populate the ptp.info.getcrosststamp() callback.

If your firmware really can't do PTM and only provides pre and post values, then you simply can take the midpoint in your getcrosststamp() callback:

Quoted 5 lines
      do {
                guard(mutex)(&ptp->nic_ts_read_lock);
                err = read_nic_timestamp(...);
                system_counterval->cycles = (nic_pre + nic_post) / 2;
      } while (err && !timeout(...));

We considered returning the midpoint of pre/post up through getcrosststamp(), but there was
no way to communicate the uncertainty interval which is important for some of our use cases.
https://lore.kernel.org/all/[email protected]/
fixes that issue, so we can use that when it lands.

Quoted 17 lines

If you do not even trust your firmware then you still can validate it easily without creating horrible hacks:

      do {
                guard(mutex)(...);

                ptp_read_system_prets(&ctx->sts);
                err = read_nic_timestamp(...);
                system_counterval->cycles = (nic_pre + nic_post) / 2;
                ptp_read_system_postts(&ctx->sts);
      } while (err && !timeout(...));

and then check the ctx->sts timestamps against the results provided by get_device_system_crosststamp() after conversion in your ptp.info.getcrosststamp() callback:

Quoted 7 lines
        err = get_device_system_crosststamp(..., &ctx);
        if (err)
           return err;
        if (ctx.sts.pre_ts > xtstamp.sys... || ctx.sts.post_ts < xtstamp.sys...)
           return -EBROKENFIRMWARE;

no?

get_device_system_crosststamp() has nontrivial logic that operates on the system timestamps, so I am not confident that a bad TSC value would be detected if we ran it through get_device_system_crosststamp() first. The check is simplest
and strongest when performed against the raw TSC values received from the device, before passing them to any kernel API. But I hear your point about mistrusting
the firmware enough to need this check.

Quoted 7 lines

Jakub, please back out this hackery before it makes a precedence for others to copy from.

Thanks,

tglx

#8 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 19 lines · Jordan Rhee

Hello,

We would like to request the community's guidance on how to proceed with adding
cross-timestamp functionality to GVE. The key challenge is that the NIC clock can only be sampled in the hypervisor because the NIC time registers are only present on the PF, and a hypercall takes 60-80us. To minimize the uncertainty window, the hypervisor takes a TSC sandwich around the reading with an uncertainty window of ~1.2us, converts it to guest TSC, and returns it to the guest.

The goals which led to this implementation were to minimize the uncertainty window and communicate the uncertainty window up the stack. I've reviewed
https://lore.kernel.org/netdev/[email protected]/
but I'm not sure how we would use it, so if it is intended to support our use case I would appreciate if someone could explain how we should use it.

Quoted 1 line

Here are some options on how to proceed, but other ideas are welcome.

So, your hypercall gives you the ABA timestamps of PTP_SYS_OFFSET_EXTENDED where the 'A' timestamps are in the form of guest TSC readings? It does not give you *simultaneous* capture and thus you can not, and should attempt to, implement PTP_SYS_OFFSET_PRECISE? Don't even think about that "midpoint" crap?

And your driver brackets the hypercalls with *actual* guest TSC reads, to keep the hypervisor honest?

Based on Thomas's branch, I'd probably do something like:

• ptp_read_system_prets()
• Make the hypercall
• ptp_read_system_postts()

Then do your sanity check that the guest TSC values provided by the hypervisor are reasonable (inside the raw_cycles¹ values in the guest pre/post snapshots). If not, return immediately using the wider uncertainty window.

If you *do* believe the hypervisor-provided TSC readings, can't you convert *each* of them to the system clock using get_device_system_crosststamp(), a history from your captured prets, and a get_time_fn callback that just creates xtstamp->sys_counter from the hypervisor-provided TSC value for pre/post respectively, each time you call it?

Take the code sample below with a *massive* pinch of salt; I only shouted at the AI a few times when asking it to translate the suggestion above into sample code, and I haven't gone over it with a fine-tooth comb. But hopefully it helps enlighten what I'm suggesting...

/*
* Suggested approach for GVE PTP gettimex64 with hypervisor-provided
* TSC values converted via get_device_system_crosststamp(). *
* This gives PTP_SYS_OFFSET_EXTENDED with ~1.2µs uncertainty
* (from the hypervisor's TSC sandwich) rather than ~60-80µs
* (from the guest-side hypercall latency).
*/

struct gve_xtstamp_ctx {
	u64 cycles;
};

static int gve_get_time_fn(ktime_t *device_time,

			   struct system_counterval_t *sys_counter,
			   void *_ctx)
{
	struct gve_xtstamp_ctx *ctx = _ctx;

	*device_time = 0;
	sys_counter->cycles = ctx->cycles;
	sys_counter->cs_id = CSID_X86_TSC;
	return 0;
}

static int gve_ptp_gettimex64(struct ptp_clock_info *info,
struct timespec64 *ts, struct ptp_system_timestamp *sts)

{
	struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
	struct gve_sysclock_sample sysclock;
	u64 nic_ts;
	int err;

	mutex_lock(&ptp->nic_ts_read_lock);
	ptp_read_system_prets(sts);
	err = gve_ptp_read_timestamp(ptp, &sysclock);
	ptp_read_system_postts(sts);
	mutex_unlock(&ptp->nic_ts_read_lock);
	if (err)
		return err;

	nic_ts = sysclock.nic_timestamp;
	*ts = ns_to_timespec64(nic_ts);

	if (!sts)
		return 0;

	/*
	 * Sanity check: hypervisor-provided TSC values must fall
	 * within our guest-side bracket (using raw_cycles from the
	 * snapshots taken by ptp_read_system_prets/postts).
	 */
	if (sysclock.nic_pre_cycles >= sts->pre_sts.raw_cycles &&
	    sysclock.nic_post_cycles <= sts->post_sts.raw_cycles) {
		struct system_device_crosststamp xtstamp;
		struct gve_xtstamp_ctx ctx;

		/*
		 * Hypervisor values are trustworthy. Convert each TSC
		 * value to system time, narrowing the pre/post window
		 * from ~60-80µs to ~1.2µs.
		 */
		ctx.cycles = sysclock.nic_pre_cycles;
		err = get_device_system_crosststamp(gve_get_time_fn, &ctx,
						    &sts->pre_sts, &xtstamp);
		if (!err) {
			sts->pre_sts.sys = xtstamp.sys_realtime;
			sts->pre_sts.raw = xtstamp.sys_monoraw;
			sts->pre_sts.cycles = sysclock.nic_pre_cycles;
			sts->pre_sts.cs_id = CSID_X86_TSC;
		}

		ctx.cycles = sysclock.nic_post_cycles;
		err = get_device_system_crosststamp(gve_get_time_fn, &ctx,
						    &sts->pre_sts, &xtstamp);
		if (!err) {
			sts->post_sts.sys = xtstamp.sys_realtime;
			sts->post_sts.raw = xtstamp.sys_monoraw;
			sts->post_sts.cycles = sysclock.nic_post_cycles;
			sts->post_sts.cs_id = CSID_X86_TSC;
		}
	}
	/* else: keep the wider pre/post from ptp_read_system_prets/postts */

	return 0;
}

¹ https://lore.kernel.org/all/[email protected]/

#9 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 43 lines · David Woodhouse
Quoted 19 lines · Jordan Rhee

Hello,

We would like to request the community's guidance on how to proceed with adding
cross-timestamp functionality to GVE. The key challenge is that the NIC clock can only be sampled in the hypervisor because the NIC time registers are only present on the PF, and a hypercall takes 60-80us. To minimize the uncertainty window, the hypervisor takes a TSC sandwich around the reading with an uncertainty window of ~1.2us, converts it to guest TSC, and returns it to the guest.

The goals which led to this implementation were to minimize the uncertainty window and communicate the uncertainty window up the stack. I've reviewed
https://lore.kernel.org/netdev/[email protected]/
but I'm not sure how we would use it, so if it is intended to support our use case I would appreciate if someone could explain how we should use it.

Quoted 1 line

Here are some options on how to proceed, but other ideas are welcome.

So, your hypercall gives you the ABA timestamps of PTP_SYS_OFFSET_EXTENDED where the 'A' timestamps are in the form of guest TSC readings? It does not give you *simultaneous* capture and thus you can not, and should attempt to, implement PTP_SYS_OFFSET_PRECISE? Don't even think about that "midpoint" crap?

And your driver brackets the hypercalls with *actual* guest TSC reads, to keep the hypervisor honest?

Based on Thomas's branch, I'd probably do something like:

• ptp_read_system_prets()
• Make the hypercall
• ptp_read_system_postts()

Then do your sanity check that the guest TSC values provided by the hypervisor are reasonable (inside the raw_cycles¹ values in the guest pre/post snapshots). If not, return immediately using the wider uncertainty window.

Quoted 6 lines

If you *do* believe the hypervisor-provided TSC readings, can't you convert *each* of them to the system clock using get_device_system_crosststamp(), a history from your captured prets, and a get_time_fn callback that just creates xtstamp->sys_counter from the hypervisor-provided TSC value for pre/post respectively, each time you call it?

Thank you David, that's a great idea. We will respin with this approach after https://lore.kernel.org/netdev/[email protected]/
lands. In the meantime, we have some other GVE patches that we need to send up.

Quoted 96 lines

Take the code sample below with a *massive* pinch of salt; I only shouted at the AI a few times when asking it to translate the suggestion above into sample code, and I haven't gone over it with a fine-tooth comb. But hopefully it helps enlighten what I'm suggesting...

/*
* Suggested approach for GVE PTP gettimex64 with hypervisor-provided
* TSC values converted via get_device_system_crosststamp(). *
* This gives PTP_SYS_OFFSET_EXTENDED with ~1.2µs uncertainty
* (from the hypervisor's TSC sandwich) rather than ~60-80µs
* (from the guest-side hypercall latency).
*/

struct gve_xtstamp_ctx {
        u64 cycles;
};

static int gve_get_time_fn(ktime_t *device_time,
struct system_counterval_t *sys_counter, void *_ctx)

{
        struct gve_xtstamp_ctx *ctx = _ctx;

        *device_time = 0;
        sys_counter->cycles = ctx->cycles;
        sys_counter->cs_id = CSID_X86_TSC;
        return 0;
}

static int gve_ptp_gettimex64(struct ptp_clock_info *info,
struct timespec64 *ts, struct ptp_system_timestamp *sts)

{
        struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
        struct gve_sysclock_sample sysclock;
        u64 nic_ts;
        int err;

        mutex_lock(&ptp->nic_ts_read_lock);
        ptp_read_system_prets(sts);
        err = gve_ptp_read_timestamp(ptp, &sysclock);
        ptp_read_system_postts(sts);
        mutex_unlock(&ptp->nic_ts_read_lock);
        if (err)
                return err;

        nic_ts = sysclock.nic_timestamp;
        *ts = ns_to_timespec64(nic_ts);

        if (!sts)
                return 0;

        /*
         * Sanity check: hypervisor-provided TSC values must fall
         * within our guest-side bracket (using raw_cycles from the
         * snapshots taken by ptp_read_system_prets/postts).
         */
        if (sysclock.nic_pre_cycles >= sts->pre_sts.raw_cycles &&
            sysclock.nic_post_cycles <= sts->post_sts.raw_cycles) {
                struct system_device_crosststamp xtstamp;
                struct gve_xtstamp_ctx ctx;

                /*
                 * Hypervisor values are trustworthy. Convert each TSC
                 * value to system time, narrowing the pre/post window
                 * from ~60-80µs to ~1.2µs.
                 */
                ctx.cycles = sysclock.nic_pre_cycles;
                err = get_device_system_crosststamp(gve_get_time_fn, &ctx,
                                                    &sts->pre_sts, &xtstamp);
                if (!err) {
                        sts->pre_sts.sys = xtstamp.sys_realtime;
                        sts->pre_sts.raw = xtstamp.sys_monoraw;
                        sts->pre_sts.cycles = sysclock.nic_pre_cycles;
                        sts->pre_sts.cs_id = CSID_X86_TSC;
                }

                ctx.cycles = sysclock.nic_post_cycles;
                err = get_device_system_crosststamp(gve_get_time_fn, &ctx,
                                                    &sts->pre_sts, &xtstamp);
                if (!err) {
                        sts->post_sts.sys = xtstamp.sys_realtime;
                        sts->post_sts.raw = xtstamp.sys_monoraw;
                        sts->post_sts.cycles = sysclock.nic_post_cycles;
                        sts->post_sts.cs_id = CSID_X86_TSC;
                }
        }
        /* else: keep the wider pre/post from ptp_read_system_prets/postts */

        return 0;
}

¹ https://lore.kernel.org/all/[email protected]/

#10 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 9 lines · Jordan Rhee
Quoted 7 lines

If you *do* believe the hypervisor-provided TSC readings, can't you convert *each* of them to the system clock using get_device_system_crosststamp(), a history from your captured prets, and a get_time_fn callback that just creates xtstamp->sys_counter from the hypervisor-provided TSC value for pre/post respectively, each time you call it?

Thank you David, that's a great idea.

Having now looked closer at your original patch, it's mostly what you were doing already, isn't it? So I think you're being kind with 'idea' :)

Quoted 3 lines

We will respin with this approach after
https://lore.kernel.org/netdev/[email protected]/
lands.

I don't think that series enables anything fundamental that you need. It lets you pass actual counter values back *from* the driver callback via the timestamp, but in your case you already had them anyway. But still, base on that anyway as your code will need to be reworked fairly significantly on top of it if you don't.

My version is basically still using get_system_device_crosststamp() in precisely the same way you were before. I've responded to Thomas directly about his feedback on that, as I just can't see any reason why adjust_historical_crosststamp() would exist at all, if what you're doing here wasn't valid.

The kerneldoc for the @history_begin argument *literally* describes it as 'Historical reference point used to interpolate system time when the counter value provided by the driver is before the current interval'.

#11 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

In reply to Thomas Gleixner
Quoted 1 line · On Wed, 20 May 2026 23:08:42 +0200 Thomas Gleixner <[email protected]> wrote:

On Thu, May 14 2026 at 22:58, Harshitha Ramamurthy wrote:

...

Quoted 6 lines

drivers/net/ethernet/google/gve/gve_ptp.c line 43

Quoted 2 lines
drivers/net/ethernet/google/gve/gve_ptp.c +2 -0
+	do {
+		*pre_cycles = get_cycles();  

This is a completely non-sensical hack. Why do you need get_cycles() here, which is a horrible and ill-defined interface that others are trying to get rid of?

ISTR that it has always returned 0 on some architectures.

-- David

#12 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

In reply to Thomas Gleixner
Quoted 15 lines · Thomas Gleixner

But what's worse and escaped the AI scrutiny is:

  Your attempt to convert these 'get_cycles()' time stamps after the fact and outside of the timekeeping core protection is fundamentally wrong.

get_device_system_crosststamp() does

      do {
       seq = read_seqcount_begin(&tk_core.seq); take_timestamps(...); convert_timestamps(...)
      } while (read_seqcount_retry(&tk_core.seq, seq));

Quoted 6 lines

which covers the whole sequence of taking the snapshots from the hardware and the conversion.

Your abuse of this is completely out of spec. Just because it did not blow up in your face yet does not make it in any way correct. You do not even get bonus points for creative abuse.

I'm not sure I concur. As I understand it, the requirement is that the time stamp must be after the snapshot passed in to get_device_system_crosststamp() as its 'history_begin' argument.

Not that the time stamp is literally within the do{} loop you mention.

That loop literally has:

		interval_start = tk->tkr_mono.cycle_last;
		if (!timestamp_in_interval(interval_start, now, cycles)) {
			...
			do_interp = true;

...which triggers the whole adjust_historical_crosststamp() thing further down, *none* of which would have any reason to exist if what you say above is true, surely?

#13 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

In reply to Harshitha Ramamurthy
Quoted 10 lines · Harshitha Ramamurthy
drivers/net/ethernet/google/gve/gve_ptp.c +9 -0
+static bool
+gve_can_use_system_ts_from_device(enum clocksource_ids system_clock_source,
+				  clockid_t clockid)
+{
+	if (clockid != CLOCK_REALTIME && clockid != CLOCK_MONOTONIC_RAW)
+		return false;
+
+	/* If the system clock source matches the system clock
+	 * returned by the AdminQ command, we can use the system

drivers/net/ethernet/google/gve/gve_ptp.c line 179

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+	 * timestamps returned by the device, otherwise we have to
+	 * fall back to sampling system time from the host which
+	 * is less accurate.
+	 */
+	if (IS_ENABLED(CONFIG_X86))
+		return system_clock_source == CSID_X86_TSC;
+	else if (IS_ENABLED(CONFIG_ARM64))
+		return system_clock_source == CSID_ARM_ARCH_COUNTER;
+
+	return false;

Strictly, you could manage to convert to CSID_X86_KVM_CLK here too. The x86 kvm_arch_ptp_get_crosststamp() for ptp_kvm does so unconditionally.

For ptp_vmclock we support both; we do the conversion only if the cs_id in the snapshot *is* the KVM clock, which seemed a bit more reasonable.

And here you add a third variant which *only* copes with CSID_X86_TSC, to complete the set of possibilities :)

With PTM and the various virt enlightenments, there are an increasing number of "PTP" clocks which literally *just* tell us a cycle count at the moment of the corresponding reading, and we don't need the ABA sandwich of local clock readings around it any more.

I've got another one waiting in the wings which will literally just latch the counter value when a PPS signal comes in, too.

It might be good to harmonise the way we convert to KVM clock if we're going to support that (although I'll accept an argument that any guest which chooses to use the KVM clock doesn't *deserve* to have accurate timekeeping).

I'd also like consensus on exposing it to userspace. I think Thomas is going to suggest that we should always convert to MONOTONIC_RAW, but what I asked Arthur to do in
https://lore.kernel.org/all/[email protected]/
exposes the raw counter values instead.

From the dedicating hosting point of view, we *only* care about the counter, and absolutely DGAF about the host's timekeeping. Migrating KVM guests requires getting the guest TSC right (in terms of scaling factors and offset from the host TSC), and feeding accurate time to guests is done in terms of the guest TSC to realtime relationship. So our ideal state is that we discipline the TSC against real time in userspace, and enabling those PHC drivers to *give* us the raw cycle counts that they actually measured seemed best.

Could we do that all on MONOTONIC_RAW, if Thomas insists? Maybe... although I like the model of disciplining one *specific* counter, and then telling the kernel about *that* counter. If the kernel for some reason has randomly switched to the HPET then the kernel is free to ignore what we're telling it about the TSC.

maintainer
#14 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 11 lines · David Woodhouse

Review

Quoted 6 lines · Harshitha Ramamurthy
(quoted diff) +6 -0
+	if (IS_ENABLED(CONFIG_X86))
+		return system_clock_source == CSID_X86_TSC;
+	else if (IS_ENABLED(CONFIG_ARM64))
+		return system_clock_source == CSID_ARM_ARCH_COUNTER;
+
+	return false;

Strictly, you could manage to convert to CSID_X86_KVM_CLK here too. The x86 kvm_arch_ptp_get_crosststamp() for ptp_kvm does so unconditionally.

Quoted 5 lines

For ptp_vmclock we support both; we do the conversion only if the cs_id in the snapshot *is* the KVM clock, which seemed a bit more reasonable.

And here you add a third variant which *only* copes with CSID_X86_TSC, to complete the set of possibilities :)

Yeah, let's sprinkle that all over the tree so nobody can figure out a coherent picture anymore. :)

Quoted 4 lines

With PTM and the various virt enlightenments, there are an increasing number of "PTP" clocks which literally *just* tell us a cycle count at the moment of the corresponding reading, and we don't need the ABA sandwich of local clock readings around it any more.

That's what the PRECISE ioctl and ptp::info::getcrosstimestamp() is for, which utilizes get_device_system_crosststamp() and provides the translation from PTM, on x86 that's ART which is converted to TSC.

It then correlates the converted system time stamp to CLOCK_REALTIME and CLOCK_MONOTONIC_RAW.

That has been implemented long ago exactly for that purpose, but people need to reinvent the wheel over and over just because it makes the kernel so more maintainable.

Quoted 2 lines

I've got another one waiting in the wings which will literally just latch the counter value when a PPS signal comes in, too.

That can use a similar mechanism.

Quoted 4 lines

It might be good to harmonise the way we convert to KVM clock if we're going to support that (although I'll accept an argument that any guest which chooses to use the KVM clock doesn't *deserve* to have accurate timekeeping).

:)

Quoted 5 lines

I'd also like consensus on exposing it to userspace. I think Thomas is going to suggest that we should always convert to MONOTONIC_RAW, but what I asked Arthur to do in
https://lore.kernel.org/all/[email protected]/
exposes the raw counter values instead.

I'm not against that per se, but that really wants to be a consistent snapshot and not some pulled out of thin air cycles value.

ktime_get_snapshot() provides that already today, so that can be arguably used for pre/post timestamp mechanisms, except that it lacks support for AUX clocks.

get_device_system_crosststamp() does not provide cycles and clock id, but that's not rocket science to extend.

Quoted 5 lines

From the dedicating hosting point of view, we *only* care about the counter, and absolutely DGAF about the host's timekeeping. Migrating KVM guests requires getting the guest TSC right (in terms of scaling factors and offset from the host TSC), and feeding accurate time to guests is done in terms of the guest TSC to realtime relationship.

The offset has nothing to do with the scaling. It's the delta to the TSC value which the migrated guest saw last when it was packed up for migration.

The scaling is not required to be cycles based either. You need to know the frequency ratio of the guest TSC to the new host TSC. cycles are not telling you that. So you need extra information from the previous host, i.e. the assumed raw TSC frequency of the guest plus the steered frequency in your virtual PCH interface.

So sure you can utilize the raw counter values for that, but you can do the same with CLOCK_MONOTONIC_RAW by exposing the mult/shift factor which the guest keeps unmodified after boot or a frequency value derived from that. That's IMO way more sensible than measuring it somehow and the shift/mult conversion inaccuracy you mentioned is laughable TBH. TSC usually ends up with a shift value of 24, so the conversion loss of the TSC to CLOCK_MONOTONIC_RAW is +/- 1ns, which is totally irrelevant in the larger picture.

Quoted 3 lines

So our ideal state is that we discipline the TSC against real time in userspace, and enabling those PHC drivers to *give* us the raw cycle counts that they actually measured seemed best.

As I said, I'm not against that per se, but then we want to provide interfaces which are generic enough so they can be used for your purposes, but also for the requirements of chrony et al. Looking at the patch you linked to above:

Quoted 14 lines
(quoted diff) +14 -0
+static long ptp_sys_offset_precise_attrs(struct ptp_clock *ptp, void __user *arg)
+{
+	struct ptp_sys_offset_precise_attrs precise_offset_attrs;
+	struct system_device_crosststamp xtstamp;
+	struct ptp_clock_attributes att = {};
+	struct timespec64 ts;
+	int err;
+
+	if (!ptp->info->getcrosststampattrs)
+		return -EOPNOTSUPP;
+
+	err = ptp->info->getcrosststampattrs(ptp->info, &xtstamp, &att);
+	if (err)
+		return err;

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+	memset(&precise_offset_attrs, 0, sizeof(precise_offset_attrs));
+	ts = ktime_to_timespec64(xtstamp.device);
+	precise_offset_attrs.device.pct.sec = ts.tv_sec;
+	precise_offset_attrs.device.pct.nsec = ts.tv_nsec;
+	precise_offset_attrs.device.att.error_bound = att.error_bound;
+	precise_offset_attrs.device.att.timescale = att.timescale;
+	precise_offset_attrs.device.att.status = att.status;
+	precise_offset_attrs.device.att.counter_id = att.counter_id;
+	precise_offset_attrs.device.att.counter_value = att.counter_value;

That's exactly the hackery which is counterproductive. Why?

Where does ptp::info::getcrosststampattrs() retrieve the system counter value from?

Either it has to convert from the ART based timestamp to TSC magically by circumventing the core code or it has to use get_cycles() separately which defeats the whole purpose of a hardware latched combo timestamp.

While this:

include/linux/timekeeping.h +15 -13
index aee2c1a46e47..43a55f618235 100644
@@ -296,19 +296,6 @@ struct system_time_snapshot {
 	u8			cs_was_changed_seq;
 };
 
-/**
- * struct system_device_crosststamp - system/device cross-timestamp
- *				      (synchronized capture)
- * @device:		Device time
- * @sys_realtime:	Realtime simultaneous with device time
- * @sys_monoraw:	Monotonic raw simultaneous with device time
- */
-struct system_device_crosststamp {
-	ktime_t device;
-	ktime_t sys_realtime;
-	ktime_t sys_monoraw;
-};
-
 /**
  * struct system_counterval_t - system counter value with the ID of the
  *				corresponding clocksource
@@ -325,6 +312,21 @@ struct system_counterval_t {
 	bool			use_nsecs;
 };
 
+/**
+ * struct system_device_crosststamp - system/device cross-timestamp
+ *				      (synchronized capture)
+ * @device:		Device time
+ * @sys_counter:	Clocksource counter value simultaneous with device time
+ * @sys_realtime:	Realtime simultaneous with device time
+ * @sys_monoraw:	Monotonic raw simultaneous with device time
+ */
+struct system_device_crosststamp {
+	ktime_t				device;
+	struct system_counterval_t	sys_counter;
+	ktime_t				sys_realtime;
+	ktime_t				sys_monoraw;
+};
+
 extern bool ktime_real_to_base_clock(ktime_t treal,
 				     enum clocksource_ids base_id, u64 *cycles);
 extern bool timekeeping_clocksource_has_base(enum clocksource_ids id);
kernel/time/timekeeping.c +1 -0
index c493a4010305..11df7e25bdca 100644
@@ -1506,6 +1506,7 @@ int get_device_system_crosststamp(int (*get_time_fn)
 		nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
 	} while (read_seqcount_retry(&tk_core.seq, seq));
 
+	xtstamp->sys_counter = system_counterval;
 	xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
 	xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
 

Provides the information coherently and without any extra hacks. No?

Extending get_device_system_crosststamp() for AUX clocks is on my todo list for a long time, but I did not come around to it yet. It's not really complicated to make that work.

The actual ena_phc_gettimexattrs64() implementation does not provide the counter value at all despite the fact that it could trivially do so with a modified ktime_get_snapshot() except for AUX clock IDs, but that's a solvable problem. See uncompiled PoC below.

I really have to ask why we put a lot of effort into consolidated infrastructure, when every drivers/foo/ subsystem decides it needs it's own absymal hacks just because sitting down and extending the generic infrastructure is asked too much. TBH, that's frustrating as hell and no, none of these usecases is so special that it would justify a single one of these hacks.

Quoted 5 lines

Could we do that all on MONOTONIC_RAW, if Thomas insists? Maybe... although I like the model of disciplining one *specific* counter, and then telling the kernel about *that* counter. If the kernel for some reason has randomly switched to the HPET then the kernel is free to ignore what we're telling it about the TSC.

Well, if the kernel has switched to HPET for timekeeping, then there is a good reason especially with the reworked clocksource watchdog, which is not longer being stupid under load and on big machines. If the sysadmin thinks it's cool to switch to HPET, then he can keep the pieces. In those cases the machine has other problems than taming the TSC for guests....

Thanks,

tglx
---

include/linux/timekeeping.h +7 -2
@@ -276,19 +276,24 @@ static inline bool ktime_get_aux_ts64(cl
 #endif
 
 /**
- * struct system_time_snapshot - simultaneous raw/real time capture with
+ * struct system_time_snapshot - simultaneous raw/CLOCK_REALTIME or CLOCK_AUX$N time capture with
  *				 counter value
  * @cycles:	Clocksource counter value to produce the system times
  * @real:	Realtime system time
+ * @aux:	Auxiliary system time if selected in ktime_get_snapshot_id()
  * @boot:	Boot time
  * @raw:	Monotonic raw system time
  * @cs_id:	Clocksource ID
  * @clock_was_set_seq:	The sequence number of clock-was-set events
  * @cs_was_changed_seq:	The sequence number of clocksource change events
+ * @clock_valid:	The clock is valid
  */
 struct system_time_snapshot {
 	u64			cycles;
-	ktime_t			real;
+	union {
+		ktime_t		real;
+		ktime_t		aux;
+	};
 	ktime_t			boot;
 	ktime_t			raw;
 	enum clocksource_ids	cs_id;
kernel/time/timekeeping.c +49 -12

103 lines not on this page · raw message

#15 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 14 lines · Thomas Gleixner
Quoted 4 lines · David Woodhouse

With PTM and the various virt enlightenments, there are an increasing number of "PTP" clocks which literally *just* tell us a cycle count at the moment of the corresponding reading, and we don't need the ABA sandwich of local clock readings around it any more.

That's what the PRECISE ioctl and ptp::info::getcrosstimestamp() is for, which utilizes get_device_system_crosststamp() and provides the translation from PTM, on x86 that's ART which is converted to TSC.

It then correlates the converted system time stamp to CLOCK_REALTIME and CLOCK_MONOTONIC_RAW.

Quoted 8 lines

That has been implemented long ago exactly for that purpose, but people need to reinvent the wheel over and over just because it makes the kernel so more maintainable.

Quoted 2 lines

I've got another one waiting in the wings which will literally just latch the counter value when a PPS signal comes in, too.

That can use a similar mechanism.

Yep. In both cases, some userspace actually wants the *counter value*.

Quoted 6 lines
Quoted 4 lines

It might be good to harmonise the way we convert to KVM clock if we're going to support that (although I'll accept an argument that any guest which chooses to use the KVM clock doesn't *deserve* to have accurate timekeeping).

:)

I'm not sure I'm joking. The KVM clock is.... *hosed*. It was invented to work around the ancient broken variable-speed TSCs which stopped on HLT, etc.

In *those* days, sure it made sense for the hypervisor to constantly update a data structure which let you approximate a TSC→nanoseconds conversion.

These days, a guest using the *actual* TSC is going to be a lot more accurate, and guests basically shouldn't be using the kvmclock AT ALL.

When I made it DTRT for ptp_vmclock, I did look briefly at what it would take to do it centrally in common code.

But that lumbers the common PTP code with x86 arch-specific horridness about the KVM clock. And it literally has to call back into the driver in the seqcount loop, so I guess drivers would need to have a flag or something that says it's OK to do that (they're fast enough, or something?).

I didn't spent *that* long trying, but I couldn't see a way of doing it centrally, which didn't end up making me sadder than the initial duplication.

Honestly, whether it was intent or omission, I suspect the approach Harshitha took for GVE is the right one: Support TSC, and anyone who uses KVM clock doesn't deserve accurate time anyway.

Quoted 8 lines
Quoted 5 lines

I'd also like consensus on exposing it to userspace. I think Thomas is going to suggest that we should always convert to MONOTONIC_RAW, but what I asked Arthur to do in
https://lore.kernel.org/all/[email protected]/
exposes the raw counter values instead.

I'm not against that per se, but that really wants to be a consistent snapshot and not some pulled out of thin air cycles value.

Definitely.

Quoted 6 lines

ktime_get_snapshot() provides that already today, so that can be arguably used for pre/post timestamp mechanisms, except that it lacks support for AUX clocks.

get_device_system_crosststamp() does not provide cycles and clock id, but that's not rocket science to extend.

Yep.

Quoted 9 lines
Quoted 5 lines

From the dedicating hosting point of view, we *only* care about the counter, and absolutely DGAF about the host's timekeeping. Migrating KVM guests requires getting the guest TSC right (in terms of scaling factors and offset from the host TSC), and feeding accurate time to guests is done in terms of the guest TSC to realtime relationship.

The offset has nothing to do with the scaling. It's the delta to the TSC value which the migrated guest saw last when it was packed up for migration.

Sure. As long as that guest TSC value is a consistent snapshot and not some pulled out of thin air cycles value :)

There is lots to be said about accurate KVM migration, and a series of 30-odd patches on the KVM list which attempts to improve it.

But either way, we still DGAF about the host's CLOCK_REALTIME when we're doing it at scale.

KVM doesn't *have* a clean way to get/set the guest TSC based on realtime; it only has the scaling and offsets from the host TSC. So to do things precisely, we end up converting via the host TSC.

So we end up comparing a {host TSC, realtime} pair between source and destination hosts, calculating the *guest* ticks that should have occurred in the intervening time, and setting the "offset from host" on the destination host to achieve the desired results. Almost all of which is in terms of TSC cycles and offsets.

Quoted 27 lines
Quoted 3 lines

So our ideal state is that we discipline the TSC against real time in userspace, and enabling those PHC drivers to *give* us the raw cycle counts that they actually measured seemed best.

As I said, I'm not against that per se, but then we want to provide interfaces which are generic enough so they can be used for your purposes, but also for the requirements of chrony et al. Looking at the patch you linked to above:

Quoted 18 lines
(quoted diff) +18 -0
+static long ptp_sys_offset_precise_attrs(struct ptp_clock *ptp, void __user *arg)
+{
+	struct ptp_sys_offset_precise_attrs precise_offset_attrs;
+	struct system_device_crosststamp xtstamp;
+	struct ptp_clock_attributes att = {};
+	struct timespec64 ts;
+	int err;
+
+	if (!ptp->info->getcrosststampattrs)
+		return -EOPNOTSUPP;
+
+	err = ptp->info->getcrosststampattrs(ptp->info, &xtstamp, &att);
+	if (err)
+		return err;
+
+	memset(&precise_offset_attrs, 0, sizeof(precise_offset_attrs));
+	ts = ktime_to_timespec64(xtstamp.device);
+	precise_offset_attrs.device.pct.sec = ts.tv_sec;
Quoted 8 lines

Review

Quoted 6 lines
(quoted diff) +6 -0
+	precise_offset_attrs.device.pct.nsec = ts.tv_nsec;
+	precise_offset_attrs.device.att.error_bound = att.error_bound;
+	precise_offset_attrs.device.att.timescale = att.timescale;
+	precise_offset_attrs.device.att.status = att.status;
+	precise_offset_attrs.device.att.counter_id = att.counter_id;
+	precise_offset_attrs.device.att.counter_value = att.counter_value;

That's exactly the hackery which is counterproductive. Why?

That's the same pattern as in the existing ptp_sys_offset_precise(), isn't it? Copying from the internal data structures it got from the driver, into the specific userspace structure for the ioctl that was called.

Quoted 6 lines

Where does ptp::info::getcrosststampattrs() retrieve the system counter value from?

Either it has to convert from the ART based timestamp to TSC magically by circumventing the core code or it has to use get_cycles() separately which defeats the whole purpose of a hardware latched combo timestamp.

The point in ptp_sys_offset_precise is that all the timestamps are the *same* time, isn't it?

So surely a device can only support this if it *does* have a precise hardware timestamp, e.g. from ART? And the corresponding sys_realtime and sys_monoraw fields also have to be from the *same* value, surely?

Is that not how it works? If not.... WTF *is* it for?

We're allowed to set *fire* to anyone who just throws a random get_cycles() call in there, aren't we? That's basically just self- defence, m'lud.

Quoted 57 lines

While this:

include/linux/timekeeping.h +0 -0
index aee2c1a46e47..43a55f618235 100644
@@ -296,19 +296,6 @@ struct system_time_snapshot {
  	u8			cs_was_changed_seq;
  };

include/linux/timekeeping.h +0 -13
-/**
- * struct system_device_crosststamp - system/device cross-timestamp
- *				      (synchronized capture)
- * @device:		Device time
- * @sys_realtime:	Realtime simultaneous with device time
- * @sys_monoraw:	Monotonic raw simultaneous with device time
- */
-struct system_device_crosststamp {
-	ktime_t device;
-	ktime_t sys_realtime;
-	ktime_t sys_monoraw;
-};
-

 /**
  * struct system_counterval_t - system counter value with the ID of the
  * corresponding clocksource

include/linux/timekeeping.h +0 -0
@@ -325,6 +312,21 @@ struct system_counterval_t {
  	bool			use_nsecs;
  };

include/linux/timekeeping.h +15 -0
+/**
+ * struct system_device_crosststamp - system/device cross-timestamp
+ *				      (synchronized capture)
+ * @device:		Device time
+ * @sys_counter:	Clocksource counter value simultaneous with device time
+ * @sys_realtime:	Realtime simultaneous with device time
+ * @sys_monoraw:	Monotonic raw simultaneous with device time
+ */
+struct system_device_crosststamp {
+	ktime_t				device;
+	struct system_counterval_t	sys_counter;
+	ktime_t				sys_realtime;
+	ktime_t				sys_monoraw;
+};
+

 extern bool ktime_real_to_base_clock(ktime_t treal,
       enum clocksource_ids base_id, u64 *cycles); extern bool timekeeping_clocksource_has_base(enum clocksource_ids id);

kernel/time/timekeeping.c +0 -0
index c493a4010305..11df7e25bdca 100644
@@ -1506,6 +1506,7 @@ int get_device_system_crosststamp(int (*get_time_fn)
  		nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
  	} while (read_seqcount_retry(&tk_core.seq, seq));

kernel/time/timekeeping.c +1 -0
+	xtstamp->sys_counter = system_counterval;
Quoted 4 lines

  xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real); xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
Provides the information coherently and without any extra hacks. No?

Yeah, that looks eminently reasonable. It isn't actually that far off what Arthur did in patch 1 of the series, is it? He was adding other clock quality attributes at the same time, and ended up shoe-horning the cs_id and cycle_count into those instead of using a separate system_counterval_t as you have here, which *is* cleaner. So yes, let's get him to do that, but that part is cosmetic?

Quoted 8 lines

Extending get_device_system_crosststamp() for AUX clocks is on my todo list for a long time, but I did not come around to it yet. It's not really complicated to make that work.

The actual ena_phc_gettimexattrs64() implementation does not provide the counter value at all despite the fact that it could trivially do so with a modified ktime_get_snapshot() except for AUX clock IDs, but that's a solvable problem. See uncompiled PoC below.

Huh? Unless it has PTM and is converting from ART (or is something virtual like vmclock or the older non-LM-safe KVM hacks), surely the driver has no business pretending to support 'precise' mode, and no business providing a counter value?

In this case, we'd want the pre_ts and post_ts to be generated by the common code using ktime_get_snapshot_id(cs_id) so that we have the corresponding system_counterval_t in the 'A' parts of the ABA tuple... but the device part of it can't pull one out of thin air unless it is *part* of the device reading, surely?

Quoted 6 lines

I really have to ask why we put a lot of effort into consolidated infrastructure, when every drivers/foo/ subsystem decides it needs it's own absymal hacks just because sitting down and extending the generic infrastructure is asked too much. TBH, that's frustrating as hell and no, none of these usecases is so special that it would justify a single one of these hacks.

Meh. I'm literally here trying to join the dots between timekeeping, PTP and KVM, and come up with a holistic solution that makes sense for all the use cases. And my brain hurts... :)

kernel/time/timekeeping.c void ktime_get_snapshot(struct system_ti · line 1259

Quoted 2 lines
kernel/time/timekeeping.c +1 -1
-EXPORT_SYMBOL_GPL(ktime_get_snapshot);
+EXPORT_SYMBOL_GPL(ktime_get_snapshot_id);

Ack. I think Arthur needs to use that in the pre_ts/post_ts helpers. Thanks.

maintainer
#16 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 8 lines · David Woodhouse
Quoted 6 lines · Thomas Gleixner
Quoted 4 lines

It might be good to harmonise the way we convert to KVM clock if we're going to support that (although I'll accept an argument that any guest which chooses to use the KVM clock doesn't *deserve* to have accurate timekeeping).

:)

Quoted 7 lines

I'm not sure I'm joking. The KVM clock is.... *hosed*. It was invented to work around the ancient broken variable-speed TSCs which stopped on HLT, etc.

In *those* days, sure it made sense for the hypervisor to constantly update a data structure which let you approximate a TSC→nanoseconds conversion.

It was broken from day one and I explained the why in great length several times. But features first, correctness later...

At some point I gave up and ignored all complaints about time inconsistencies in guests which use kvmclock.

Quoted 2 lines

These days, a guest using the *actual* TSC is going to be a lot more accurate, and guests basically shouldn't be using the kvmclock AT ALL.

You're preaching to the choir.

Quoted 9 lines

When I made it DTRT for ptp_vmclock, I did look briefly at what it would take to do it centrally in common code.

But that lumbers the common PTP code with x86 arch-specific horridness about the KVM clock. And it literally has to call back into the driver in the seqcount loop, so I guess drivers would need to have a flag or something that says it's OK to do that (they're fast enough, or something?).

Quoted 7 lines

I didn't spent *that* long trying, but I couldn't see a way of doing it centrally, which didn't end up making me sadder than the initial duplication.

Honestly, whether it was intent or omission, I suspect the approach Harshitha took for GVE is the right one: Support TSC, and anyone who uses KVM clock doesn't deserve accurate time anyway.

I agree with the sentiment, but the implementation is just bonkers TBH.

The driver should not even care about TSC/ARM_XX. Drivers have to be mostly agnostic of this and we went to a great length for that with the existing PTM core support. The core might need extensions for the pre/post muck, but that's not a justification for hacks like this GVE stuff.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

From the dedicating hosting point of view, we *only* care about the counter, and absolutely DGAF about the host's timekeeping. Migrating KVM guests requires getting the guest TSC right (in terms of scaling factors and offset from the host TSC), and feeding accurate time to guests is done in terms of the guest TSC to realtime relationship.

Quoted 6 lines
Quoted 3 lines

The offset has nothing to do with the scaling. It's the delta to the TSC value which the migrated guest saw last when it was packed up for migration.

Sure. As long as that guest TSC value is a consistent snapshot and not some pulled out of thin air cycles value :)

That's a different problem, which has nothing to do with the issue at hand and if that's not solved, then providing accurate frequency ratios is not making it much better :)

Quoted 10 lines

There is lots to be said about accurate KVM migration, and a series of 30-odd patches on the KVM list which attempts to improve it.

But either way, we still DGAF about the host's CLOCK_REALTIME when we're doing it at scale.

KVM doesn't *have* a clean way to get/set the guest TSC based on realtime; it only has the scaling and offsets from the host TSC. So to do things precisely, we end up converting via the host TSC.

Quoted 5 lines

So we end up comparing a {host TSC, realtime} pair between source and destination hosts, calculating the *guest* ticks that should have occurred in the intervening time, and setting the "offset from host" on the destination host to achieve the desired results. Almost all of which is in terms of TSC cycles and offsets.

Fine, but you can only do that accurately if you have the relevant parameters:

1) Guest TSC value at freeze
2) Guest nominal TSC frequency
3) Old host REALTIME at freeze - Ideally you use TAI
4) New host TSC frequency
5) New host TSC/REALTIME/TAI snapshot

#1 is a KVM problem, but see #3

#2 ideally communicated from the guest to the host after early
initialization at boot.

You really want this information because the guest won't change the mult/shift pair for it ever.

That is more accurate than using the scaling factor on the old host plus the old host frequency. Especially if you are migrating the VM several times because every migration results obviously in rounding errors, while if you use the nominal guest frequency you keep this back and forth conversions and the resulting errors out of the way.

#3 That's obviously related to #1

The old host knows the guest TSC scaling and the guest offset, so it can take a coherent snapshot on the host side of REALTIME/TAI and the host TSC value, which is convertible to the guest TSC value.

#4, 5

are obviously required to set up the new host scaling/offset for the guest TSC, but if based on the nominal assumed TSC frequency of the guest it becomes actually accurate and usable across several migrations.

Anything else is just crystal ball magic, which is what KVM has today....

Quoted 9 lines
Quoted 4 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+	precise_offset_attrs.device.att.counter_id = att.counter_id;
+	precise_offset_attrs.device.att.counter_value = att.counter_value;

That's exactly the hackery which is counterproductive. Why?

That's the same pattern as in the existing ptp_sys_offset_precise(), isn't it? Copying from the internal data structures it got from the driver, into the specific userspace structure for the ioctl that was called.

No.

Q: How does the driver know what the snapshot of NIC/SYSTEM time means?
A: It does not.

That's what get_device_system_crosststamp() encapsulates in a generic way, which removes architecture/system specific knowledge from the driver.

Q: How can the driver fill in att.counter_id and att.counter_value
_without_ specific knowlegde?
A: It _cannot_ without get_device_system_crosststamp() providing it.

Which is what I tried to explain you here:

Quoted 9 lines
Quoted 6 lines

Where does ptp::info::getcrosststampattrs() retrieve the system counter value from?

Either it has to convert from the ART based timestamp to TSC magically by circumventing the core code or it has to use get_cycles() separately which defeats the whole purpose of a hardware latched combo timestamp.

The point in ptp_sys_offset_precise is that all the timestamps are the *same* time, isn't it?

Yes.

Quoted 3 lines

So surely a device can only support this if it *does* have a precise hardware timestamp, e.g. from ART? And the corresponding sys_realtime and sys_monoraw fields also have to be from the *same* value, surely?

That is correct, but you still fail to explain how this new made up att.counter_id/att.counter_value is filled in coherently without the driver doing something abysmal?

You can't explain it, because the only way to do that correctly is by extending the cross time stamp struct and get_device_system_crosststamp().

Quoted 1 line

Is that not how it works? If not.... WTF *is* it for?

Yes, that's the way it works since get_device_system_crosststamp() got introduced, but that does not give a random driver access to the actual converted (TSC) counter value. The driver can only observe the PTM value which is ART on x86 and whatever on other architectures. So it does not know anything about it.

Quoted 3 lines

We're allowed to set *fire* to anyone who just throws a random get_cycles() call in there, aren't we? That's basically just self- defence, m'lud.

I agree, but the way how this attr.counter_id/value extension is defined either requires unholy hacks to get access to the ART/TSC conversion or resort to get_cycles().

Quoted 1 line
Quoted 1 line

While this:

...

Quoted 1 line

kernel/time/timekeeping.c int get_device_system_crosststamp(int (*get_time_fn) · line 1509

Quoted 1 line
kernel/time/timekeeping.c +1 -0
+	xtstamp->sys_counter = system_counterval;

...

simple core code change:

Quoted 8 lines
Quoted 1 line

Provides the information coherently and without any extra hacks. No?

Yeah, that looks eminently reasonable. It isn't actually that far off what Arthur did in patch 1 of the series, is it? He was adding other clock quality attributes at the same time, and ended up shoe-horning the cs_id and cycle_count into those instead of using a separate system_counterval_t as you have here, which *is* cleaner. So yes, let's get him to do that, but that part is cosmetic?

No. It's not cosmetic.

This patch #1 just defines new attributes, which include the CS ID and the CS counter value with absolutely ZERO explanation where these values are supposed to come from and ZERO explanation how they are coherent.

It suggests that the driver can fill them in along with the other truly driver related data, e.g. error_bound.

But as I explained before the driver _cannot_ fill them in coherently neither for the new gettimexattrs64() nor for the getcrosststampattrs() callbacks.

So you add an extension to the existing interface without core support, which means once that is merged the driver crowd will happily take any shortcut to support it.

Are _you_ going to mop up the resulting mess?

Quoted 9 lines
Quoted 8 lines

Extending get_device_system_crosststamp() for AUX clocks is on my todo list for a long time, but I did not come around to it yet. It's not really complicated to make that work.

The actual ena_phc_gettimexattrs64() implementation does not provide the counter value at all despite the fact that it could trivially do so with a modified ktime_get_snapshot() except for AUX clock IDs, but that's a solvable problem. See uncompiled PoC below.

Quoted 4 lines

Huh? Unless it has PTM and is converting from ART (or is something virtual like vmclock or the older non-LM-safe KVM hacks), surely the driver has no business pretending to support 'precise' mode, and no business providing a counter value?

Huch?

According to your earlier argumentation about counter values, you want the counter value, REALTIME, RAW combo even for gettimexattrs64() for the pre/post timestamps in case the hardware does not support PTM, no?

Quoted 5 lines

In this case, we'd want the pre_ts and post_ts to be generated by the common code using ktime_get_snapshot_id(cs_id) so that we have the corresponding system_counterval_t in the 'A' parts of the ABA tuple... but the device part of it can't pull one out of thin air unless it is *part* of the device reading, surely?

Correct, but where does the proposed patch set implement any of this?

In the ena driver it sets cs_id and cs_value to 0, which will be replaced by abysmal hacks within no time because someone figures out that adding these values will give "better" results ....

Neither the gettimexattrs64() nor the getcrosststampattrs() have any coherent way to fill in the CS related data, but you are pushing for adding this infrastructure first before thinking about the consequences. You can't be serious about that.

Quoted 10 lines
Quoted 6 lines

I really have to ask why we put a lot of effort into consolidated infrastructure, when every drivers/foo/ subsystem decides it needs it's own absymal hacks just because sitting down and extending the generic infrastructure is asked too much. TBH, that's frustrating as hell and no, none of these usecases is so special that it would justify a single one of these hacks.

Meh. I'm literally here trying to join the dots between timekeeping, PTP and KVM, and come up with a holistic solution that makes sense for all the use cases. And my brain hurts... :)

Welcome to the wonderful world of time(keeping). Once you have done that for 20 years your brain stops to hurt :)

Thanks,

tglx

#17 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 9 lines · Thomas Gleixner
Quoted 7 lines · David Woodhouse

I didn't spent *that* long trying, but I couldn't see a way of doing it centrally, which didn't end up making me sadder than the initial duplication.

Honestly, whether it was intent or omission, I suspect the approach Harshitha took for GVE is the right one: Support TSC, and anyone who uses KVM clock doesn't deserve accurate time anyway.

Quoted 6 lines

I agree with the sentiment, but the implementation is just bonkers TBH.

The driver should not even care about TSC/ARM_XX. Drivers have to be mostly agnostic of this and we went to a great length for that with the existing PTM core support. The core might need extensions for the pre/post muck, but that's not a justification for hacks like this GVE stuff.

I haven't looked hard at what GVE is trying to do; only glanced at the consistency of CSID_X86_TSC vs. CSID_X86_KVM_CLK handling as I was already sad about that one.

Quoted 2 lines
Quoted 1 line

<... migration...>

Anything else is just crystal ball magic, which is what KVM has today....

Yeah, we digress. There's a 30-odd patch series on the kvm list to clean up guest tsc/kvmclock handling and migration, and document the process, if you want to come play. But honestly, there aren't enough drugs in the world for someone to want to get involved in that crap *voluntarily*. I recommend you don't ;)

Quoted 10 lines
Quoted 3 lines

So surely a device can only support this if it *does* have a precise hardware timestamp, e.g. from ART? And the corresponding sys_realtime and sys_monoraw fields also have to be from the *same* value, surely?

That is correct, but you still fail to explain how this new made up att.counter_id/att.counter_value is filled in coherently without the driver doing something abysmal?

You can't explain it, because the only way to do that correctly is by extending the cross time stamp struct and get_device_system_crosststamp().

Yes. Isn't that what I asked Arthur to do?

Quoted 7 lines
Quoted 1 line

Is that not how it works? If not.... WTF *is* it for?

Yes, that's the way it works since get_device_system_crosststamp() got introduced, but that does not give a random driver access to the actual converted (TSC) counter value. The driver can only observe the PTM value which is ART on x86 and whatever on other architectures. So it does not know anything about it.

Sure, the driver can only return what it *knows*.

We're certainly missing some infrastructure here... maybe the pci_bus should have a CSID which corresponds to its PTM domain, which on x86 would be CSID_X86_ART?

(I really do want to get my hands on one of those PTM-capable atomic clock TimeCard things, and have a play with implementing vmclock on them using ART as the reference)

Quoted 7 lines
Quoted 3 lines

We're allowed to set *fire* to anyone who just throws a random get_cycles() call in there, aren't we? That's basically just self- defence, m'lud.

I agree, but the way how this attr.counter_id/value extension is defined either requires unholy hacks to get access to the ART/TSC conversion or resort to get_cycles().

Never get_cycles(). Let's perhaps make it *not* need unholy hacks to interpret a PTM counter value. Otherwise what's the point in ART and PTM at all?

Quoted 18 lines
Quoted 1 line
Quoted 1 line

While this:

...

Quoted 1 line

kernel/time/timekeeping.c int get_device_system_crosststamp(int (*get_time_fn) · line 1509

Quoted 1 line
kernel/time/timekeeping.c +1 -0
+	xtstamp->sys_counter = system_counterval;

...

simple core code change:

Quoted 8 lines
Quoted 1 line

Provides the information coherently and without any extra hacks. No?

Yeah, that looks eminently reasonable. It isn't actually that far off what Arthur did in patch 1 of the series, is it? He was adding other clock quality attributes at the same time, and ended up shoe-horning the cs_id and cycle_count into those instead of using a separate system_counterval_t as you have here, which *is* cleaner. So yes, let's get him to do that, but that part is cosmetic?

Quoted 5 lines

No. It's not cosmetic.

This patch #1 just defines new attributes, which include the CS ID and the CS counter value with absolutely ZERO explanation where these values are supposed to come from and ZERO explanation how they are coherent.

Pfft. Explanations are *definitely* cosmetic. And so is the difference between a system_counterval_t, and a separate pair of {csid, cycles} fields that precisely correspond to it; at least if we ignore use_nsecs (which I have thus far).

I'll stand by calling that part cosmetic.

Not that we shouldn't fix it, but we should try to make our request of the author clear and concise, and not catastrophise over the tweaks we need to be made.

Quoted 6 lines

It suggests that the driver can fill them in along with the other truly driver related data, e.g. error_bound.

But as I explained before the driver _cannot_ fill them in coherently neither for the new gettimexattrs64() nor for the getcrosststampattrs() callbacks.

And yet in patch 4/7, vmclock_populate_ptp_attributes() is *given* the count value from which the time reading is generated, puts it into the {csid, cycles} fields which we agree should be turned into a system_counterval_t as part of the device timestamp, and I don't see the problem.

Quoted 3 lines

So you add an extension to the existing interface without core support, which means once that is merged the driver crowd will happily take any shortcut to support it.

Please be specific. Aside from the values being a system_counterval_t in each timestamp (both pre/post and, for those devices which can, the device time), what is missing?

Quoted 16 lines

Are _you_ going to mop up the resulting mess?

Quoted 9 lines
Quoted 8 lines

Extending get_device_system_crosststamp() for AUX clocks is on my todo list for a long time, but I did not come around to it yet. It's not really complicated to make that work.

The actual ena_phc_gettimexattrs64() implementation does not provide the counter value at all despite the fact that it could trivially do so with a modified ktime_get_snapshot() except for AUX clock IDs, but that's a solvable problem. See uncompiled PoC below.

Quoted 4 lines

Huh? Unless it has PTM and is converting from ART (or is something virtual like vmclock or the older non-LM-safe KVM hacks), surely the driver has no business pretending to support 'precise' mode, and no business providing a counter value?

Quoted 5 lines

Huch?

According to your earlier argumentation about counter values, you want the counter value, REALTIME, RAW combo even for gettimexattrs64() for the pre/post timestamps in case the hardware does not support PTM, no?

For the pre/post timestamps, sure. Not the *device* timestamp when it doesn't support that.

Quoted 7 lines
Quoted 5 lines

In this case, we'd want the pre_ts and post_ts to be generated by the common code using ktime_get_snapshot_id(cs_id) so that we have the corresponding system_counterval_t in the 'A' parts of the ABA tuple... but the device part of it can't pull one out of thin air unless it is *part* of the device reading, surely?

Correct, but where does the proposed patch set implement any of this?

It doesn't yet; I only asked for it this evening. Should be in the next round.

Quoted 1 line

In the ena driver it sets cs_id and cs_value to 0,

Good. I hadn't looked hard at the ENA driver yet. So I asked Arthur if he'd tried to expose a cycle value for the ENA PHC and the answer was essentially "of course not; it doesn't have PTM".

Quoted 3 lines

which will be replaced by abysmal hacks within no time because someone figures out that adding these values will give "better" results ....

Those were the ones we were allowed to set fire to, right?

Quoted 4 lines

Neither the gettimexattrs64() nor the getcrosststampattrs() have any coherent way to fill in the CS related data, but you are pushing for adding this infrastructure first before thinking about the consequences. You can't be serious about that.

I do not believe I agree. I'm adding the infrastructure to report this information because we *do* have it, and userspace wants to see it.

Some drivers *do* have it. The vmclock gettimex64 method literally just calls ktime_get_snapshot(), populates both its pre and post timestamps with the *same* result, and the device timestamp is calculated from the same counter value at that precise moment.

It can *absolutely* also return the actual counter value used, if the infrastructure supports that. As can the ptp_kvm drivers. And, a device with PTM could report that too (although we do need a little more work on cleanly converting that to an understandable domain, as you say).

And even for drivers which don't have simultaneous cycle readings, userspace still wants to get the counter values corresponding to the pre/post readings, which again can absolutely be supported.

maintainer
#18 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 5 lines · David Woodhouse
Quoted 4 lines · Thomas Gleixner
Quoted 3 lines

So surely a device can only support this if it *does* have a precise hardware timestamp, e.g. from ART? And the corresponding sys_realtime and sys_monoraw fields also have to be from the *same* value, surely?

Quoted 8 lines
Quoted 6 lines

That is correct, but you still fail to explain how this new made up att.counter_id/att.counter_value is filled in coherently without the driver doing something abysmal?

You can't explain it, because the only way to do that correctly is by extending the cross time stamp struct and get_device_system_crosststamp().

Yes. Isn't that what I asked Arthur to do?

You maybe asked him, but I can't see any evidence of it anywhere. All I can see is a magic struct attr, which conveys CS related data that is supposed to be produced magically at some undefined place.

Quoted 8 lines
Quoted 7 lines
Quoted 1 line

Is that not how it works? If not.... WTF *is* it for?

Yes, that's the way it works since get_device_system_crosststamp() got introduced, but that does not give a random driver access to the actual converted (TSC) counter value. The driver can only observe the PTM value which is ART on x86 and whatever on other architectures. So it does not know anything about it.

Quoted 5 lines

Sure, the driver can only return what it *knows*.

We're certainly missing some infrastructure here... maybe the pci_bus should have a CSID which corresponds to its PTM domain, which on x86 would be CSID_X86_ART?

Yes, that's correct. But that does not solve the underlying problem:

The driver gets the PTP/SystemTime pair from the hardware/firmware, which is what it hands back to get_device_system_crosststamp(). What does SystemTime mean?

Here it gets interesting as that depends on the NIC/PTP magic firmware and the architecture:

On X86:

- The plain ART value, which is converted to TSC in get_device_system_crosststamp().

- The ART value which is magically converted to "nanoseconds" by the firmware.

That is conveyed in system_counterval_t and the 'use_nsec' flag, which is a misnomer, determines the conversion in the core.

- If set it uses the nominal frequency of the underlying base clock (ART) for conversion.

- If not it uses the nominator/denominator pair of the underlying base clock (ART) for conversion.

On ARM64:

- The ARM ARCH counter value (however that is converted from PTM magically)

- The ARM ARCH counter which is magically converted to "nanoseconds" by the firmware. Actually it's not, but the drivers claim it is.

It does not matter because the core does no conversion for ARM64 as the SystemTime CSID is the same as the core timekeeper CSID.

Q: How is a driver supposed to fill in attr->cs_cycles coherently?

A: Not at all.

The consequence of this is that the next driver writer will just go and do:

       attr->cs_id = IS_ENABLED(X86) ? CSID_X86_TSC : CSID_ARM_COUNTER;
       attr->cs_cycles = get_cycles();
   or
       attr->cs_cycles = ptm_cycles * pulledout_of_thin_air_factor +
                         pulledout_of_thin_air_offset;

and this mess is going to proliferate faster than you can breathe.

The same applies to the pre/post timestamp mechanism for gettimexattrs64().

These new attr IOCTLs are not restricted to your favorite vmclock PTP toy. They are available for every PTP driver which implements them, but there is no infrastructure to actually provide the required data. That ENA driver implementing gettimexattrs64() is demonstrating it. It at least does not try to make them up, but that's just a matter of time to happen.

I know you don't care because that's outside of your sandpit, but I care because providing this interface is going to result in random drivers growing the most absurd warts just to work around the lack of core infrastructure.

Are you going to monitor drivers/net/ for those instances and make sure they are burned before seeing the light of day?

Surely not and neither is netdev going to care as demonstrated with this GEV mess.

It took me half an hour to add basic support for that into the core infrastructure, but this new IOCTL stuff has been in the making for almost a year without anyone spending a single brain cycle to even think about it.

And you just have proven it by still claiming that this is a completely cosmetic problem.

Seriously?

Quoted 7 lines
Quoted 3 lines

I agree, but the way how this attr.counter_id/value extension is defined either requires unholy hacks to get access to the ART/TSC conversion or resort to get_cycles().

Never get_cycles(). Let's perhaps make it *not* need unholy hacks to interpret a PTM counter value. Otherwise what's the point in ART and PTM at all?

Perhaps? There is no perhaps and aside of that I gave you the solution for the problem already in the mail you just replied to, no?

I'm glad we agree on "Never get_cycles()" at least. May I ask you then to get a stiff drink ready and run:

  # git blame drivers/ptp/ptp_vmclock.c | grep get_cycles

:)

Thanks,

tglx

#19 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 10 lines · Thomas Gleixner
Quoted 9 lines · David Woodhouse
Quoted 8 lines · Thomas Gleixner
Quoted 3 lines

So surely a device can only support this if it *does* have a precise hardware timestamp, e.g. from ART? And the corresponding sys_realtime and sys_monoraw fields also have to be from the *same* value, surely?

That is correct, but you still fail to explain how this new made up att.counter_id/att.counter_value is filled in coherently without the driver doing something abysmal?

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

You can't explain it, because the only way to do that correctly is by extending the cross time stamp struct and get_device_system_crosststamp().

Yes. Isn't that what I asked Arthur to do?

You maybe asked him, but I can't see any evidence of it anywhere. All I can see is a magic struct attr, which conveys CS related data that is supposed to be produced magically at some undefined place.

https://lore.kernel.org/all/[email protected]/

Quoted 14 lines
Quoted 8 lines
Quoted 7 lines
Quoted 1 line

Is that not how it works? If not.... WTF *is* it for?

Yes, that's the way it works since get_device_system_crosststamp() got introduced, but that does not give a random driver access to the actual converted (TSC) counter value. The driver can only observe the PTM value which is ART on x86 and whatever on other architectures. So it does not know anything about it.

Quoted 5 lines

Sure, the driver can only return what it *knows*.

We're certainly missing some infrastructure here... maybe the pci_bus should have a CSID which corresponds to its PTM domain, which on x86 would be CSID_X86_ART?

Quoted 8 lines

Yes, that's correct. But that does not solve the underlying problem:

...

Q: How is a driver supposed to fill in attr->cs_cycles coherently?

A: Not at all.

Let me rephrase that to check my full understanding of it in context:

Q: There are drivers today which operate on the TSC or arch counter,
and they're just fine. But how is a future driver which uses PCIe PTM supposed to full in attr->cs_cycles coherently?

A: Yeah, our PCI and platform code lack the proper arch-agnostic
support for interpreting PTM time values; a driver wanting to do that is going to need to do some infrastructure work first to enable a proper conversion. But that's literally what PTM/ART is *for* so that work has to happen at some point anyway.

Quoted 8 lines

The consequence of this is that the next driver writer will just go and do:

       attr->cs_id = IS_ENABLED(X86) ? CSID_X86_TSC : CSID_ARM_COUNTER; attr->cs_cycles = get_cycles();
   or
       attr->cs_cycles = ptm_cycles * pulledout_of_thin_air_factor + pulledout_of_thin_air_offset;

Driver authors are crap, sure, but that would just be egregiously wrong and hopefully it would be caught in review. It has to be a literally *synchronous* capture or it's pointless.

Quoted 2 lines

The same applies to the pre/post timestamp mechanism for gettimexattrs64().

There's literally a ptp helper to generate those, which can use ktime_get_snapshot().

Quoted 6 lines

These new attr IOCTLs are not restricted to your favorite vmclock PTP toy. They are available for every PTP driver which implements them, but there is no infrastructure to actually provide the required data. That ENA driver implementing gettimexattrs64() is demonstrating it. It at least does not try to make them up, but that's just a matter of time to happen.

The ENA driver demonstrates nothing of the sort. It's *not* filling in those fields because it *doesn't* have PTM and it has nothing to fill in.

Not *all* driver authors will fill in an optional field with random bytes just because they *can*, Thomas.

Quoted 1 line

I know you don't care because that's outside of your sandpit,

Thomas, I'd like you to stop saying that. It's insulting, and it's wrong.

Of *course* I'm trying to solve things for the general case.

But that doesn't extend to implementing random parts of PCI and platform infrastructure to allow for hypothetical future drivers which want to use PTM to implement the optional fields we're adding today.

This yak is deep enough already :)

And although we're having this discussion *in* the GVE thread, I've barely even *looked* at those patches and I think I'm still calling it a 'hypothetical future driver', because obviously if it's trying to use PTM then it's going to need that generic support.

Quoted 5 lines

Are you going to monitor drivers/net/ for those instances and make sure they are burned before seeing the light of day?

Surely not and neither is netdev going to care as demonstrated with this GEV mess.

I think that message has been received loud and clear, Thomas :)

Quoted 6 lines
Quoted 3 lines

Never get_cycles(). Let's perhaps make it *not* need unholy hacks to interpret a PTM counter value. Otherwise what's the point in ART and PTM at all?

Perhaps? There is no perhaps and aside of that I gave you the solution for the problem already in the mail you just replied to, no?

Hm, did you? I'm sorry, I must have missed it. Even rereading it this morning, I see a lot of 'is bonkers' and 'unholy hacks' and '_cannot_ fill them in coherently' but I can't see a concrete constructive suggestion. You meant <87bje8v0xl.ffs@tglx>, yes?

Maybe it's lost in the noise. Let's try to simplify.

• Userspace would like to be able to use PTP clocks to discipline the actual counter which is directly accessible in userspace and by KVM guests. Do do this, we only really need a system_counterval_t in the pre/post timestamps, and the helpers can add that.

• *Some* drivers can actually provide a system_counterval_t in the device reading itself, either because they're naturally based on the CPU counter or because they have PTM. Drivers should report what they *do* know, in the correct time domain, and not make crap up.

• Any driver which actually wants to do this based on PTM in the future will need to do the infrastructure work to make that work cleanly, and avoid having to make crap up.

And if I'm understanding correctly:

• The GVE driver made crap up? Although they do so orthogonally to the patch set we're *actually* talking about in this thread, because they did that entirely on their own *without* reference to Arthur's userspace API changes?

Quoted 4 lines

I'm glad we agree on "Never get_cycles()" at least. May I ask you then to get a stiff drink ready and run:

  # git blame drivers/ptp/ptp_vmclock.c | grep get_cycles

That's different because it's actually using it for the *device* timestamp. But if you see an actual problem there, I'd love to know:

                /*
                 * When invoked for gettimex64(), fill in the pre/post system
                 * times. The simple case is when system time is based on the
                 * same counter as st->cs_id, in which case all three times
                 * will be derived from the *same* counter value.
                 *
                 * If the system isn't using the same counter, then the value
                 * from ktime_get_snapshot() will still be used as pre_ts, and
                 * ptp_read_system_postts() is called to populate postts after
                 * calling get_cycles().
                 *
                 * The conversion to timespec64 happens further down, outside
                 * the seq_count loop.
                 */
                if (sts) {
                        ktime_get_snapshot(&systime_snapshot);
                        if (systime_snapshot.cs_id == st->cs_id) {
                                cycle = systime_snapshot.cycles;
                        } else {
                                cycle = get_cycles();
                                ptp_read_system_postts(sts);
                        }
                } else {
                        cycle = get_cycles();
                }

                delta = cycle - le64_to_cpu(st->clk->counter_value);
                ...
maintainer
#20 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 8 lines · David Woodhouse
Quoted 5 lines · Thomas Gleixner
Quoted 1 line

Yes. Isn't that what I asked Arthur to do?

You maybe asked him, but I can't see any evidence of it anywhere. All I can see is a magic struct attr, which conveys CS related data that is supposed to be produced magically at some undefined place.

https://lore.kernel.org/all/[email protected]/

Right, after I pointed it out :)

Quoted 29 lines
Quoted 14 lines
Quoted 8 lines
Quoted 7 lines
Quoted 1 line

Is that not how it works? If not.... WTF *is* it for?

Yes, that's the way it works since get_device_system_crosststamp() got introduced, but that does not give a random driver access to the actual converted (TSC) counter value. The driver can only observe the PTM value which is ART on x86 and whatever on other architectures. So it does not know anything about it.

Quoted 5 lines

Sure, the driver can only return what it *knows*.

We're certainly missing some infrastructure here... maybe the pci_bus should have a CSID which corresponds to its PTM domain, which on x86 would be CSID_X86_ART?

Quoted 8 lines

Yes, that's correct. But that does not solve the underlying problem:

...

Q: How is a driver supposed to fill in attr->cs_cycles coherently?

A: Not at all.

Let me rephrase that to check my full understanding of it in context:

Q: There are drivers today which operate on the TSC or arch counter,
and they're just fine. But how is a future driver which uses PCIe PTM supposed to full in attr->cs_cycles coherently?

Quoted 5 lines

A: Yeah, our PCI and platform code lack the proper arch-agnostic
support for interpreting PTM time values; a driver wanting to do that is going to need to do some infrastructure work first to enable a proper conversion. But that's literally what PTM/ART is *for* so that work has to happen at some point anyway.

That work is there:

get_device_system_cross_timestamp()

The only lacking feature is that there is no generic PCI method to tell the driver which PMT clocksource ID it should use.

So the drivers do it manually:

   system->cycles = PTM_READ();
   system->cs_id = CSID_ART;

instead of doing:

   system->cs_id = pci_dev_ptm_csid(pdev);

everything else is done by the core code for several years already.

The core code provides:

- PCH timestamp
- sys_realtime derived from system->cycles
- sys_monoraw derived from system->cycles

So now with your new proposed attr extenstions, you want attr to return system->cycles to user space and you don't want the raw PTM value (ART) but you want the corresponding TSC value which is:

    TSC = M * ART + offset;

But the driver has no access to this information. That's why I'm ranting about an interface which lacks the infrastructure to utilize it properly.

I've seen this in the past 20 years over and over. The lack of infrastructure makes driver people do abysmal hacks because they are tasked to utilize the new interface. The result is a horrible mess, which others have to clean up later when they want to do core changes.

Quoted 11 lines
Quoted 8 lines

The consequence of this is that the next driver writer will just go and do:

       attr->cs_id = IS_ENABLED(X86) ? CSID_X86_TSC : CSID_ARM_COUNTER; attr->cs_cycles = get_cycles();
   or
       attr->cs_cycles = ptm_cycles * pulledout_of_thin_air_factor + pulledout_of_thin_air_offset;

Driver authors are crap, sure, but that would just be egregiously wrong and hopefully it would be caught in review.

You wish. Shit get's merged faster than you can mop it up.

I agree that driver authors are interesting creatures, but you can't whack them over the head when there is no generic infrastructure they can use. They never will go and extend existing or provide new infrastructure. That's on the people who add new functionality, which will be consumed by driver writers.

Quoted 1 line

It has to be a literally *synchronous* capture or it's pointless.

You know that and I know that, but ...

Quoted 5 lines
Quoted 2 lines

The same applies to the pre/post timestamp mechanism for gettimexattrs64().

There's literally a ptp helper to generate those, which can use ktime_get_snapshot().

With some massaging, yes. Now that someone provided an extensible snapshot function. :)

Quoted 5 lines

Of *course* I'm trying to solve things for the general case.

But that doesn't extend to implementing random parts of PCI and platform infrastructure to allow for hypothetical future drivers which want to use PTM to implement the optional fields we're adding today.

Optional fields are going to get filled when people see value in them. You need no new drivers for that. Existing drivers hop on the new bus as soon as it hits the road.

Quoted 11 lines
Quoted 6 lines
Quoted 3 lines

Never get_cycles(). Let's perhaps make it *not* need unholy hacks to interpret a PTM counter value. Otherwise what's the point in ART and PTM at all?

Perhaps? There is no perhaps and aside of that I gave you the solution for the problem already in the mail you just replied to, no?

Hm, did you? I'm sorry, I must have missed it. Even rereading it this morning, I see a lot of 'is bonkers' and 'unholy hacks' and '_cannot_ fill them in coherently' but I can't see a concrete constructive suggestion. You meant <87bje8v0xl.ffs@tglx>, yes?

The demonstration patches to extend ktime_get_snapshot() and the half assed support in get_device_system_crosststamp(). You actually asked me to provide a SOB for the ktime_get_snapshot_id() part. No?

Quoted 7 lines

Maybe it's lost in the noise. Let's try to simplify.

• Userspace would like to be able to use PTP clocks to discipline the actual counter which is directly accessible in userspace and by KVM guests. Do do this, we only really need a system_counterval_t in the pre/post timestamps, and the helpers can add that.

Quoted 5 lines

• *Some* drivers can actually provide a system_counterval_t in the device reading itself, either because they're naturally based on the CPU counter or because they have PTM. Drivers should report what they *do* know, in the correct time domain, and not make crap up.

Which needs support in get_device_system_crosststamp() because that's what drivers have to use to utilize PTM.

Quoted 3 lines

• Any driver which actually wants to do this based on PTM in the future will need to do the infrastructure work to make that work cleanly, and avoid having to make crap up.

That's wishful thinking. It did not happen in the last two decades so why would this be different today?

Quoted 6 lines

And if I'm understanding correctly:

• The GVE driver made crap up? Although they do so orthogonally to the patch set we're *actually* talking about in this thread, because they did that entirely on their own *without* reference to Arthur's userspace API changes?

Correct.

Let's move this to the other thread which actually talks about your vmclock stuff.

Thanks,

tglx

#21 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

In reply to Thomas Gleixner
Quoted 4 lines · Thomas Gleixner

Fine, but you can only do that accurately if you have the relevant parameters:

I had elided this discussion about KVM migration as a digression, but I'm coming back to it because I think it could use the clock_get_reference_time() thing we were talking about.

Quoted 6 lines

     1) Guest TSC value at freeze
     2) Guest nominal TSC frequency
     3) Old host REALTIME at freeze - Ideally you use TAI
     4) New host TSC frequency
     5) New host TSC/REALTIME/TAI snapshot

Quoted 7 lines

  #1 is a KVM problem, but see #3

  #2 ideally communicated from the guest to the host after early initialization at boot.

     You really want this information because the guest won't change the mult/shift pair for it ever.

If *tell* the guest the frequency in CPUID, then it shouldn't be trying to manually calibrate it against an emulated PIT while suffering steal time, and its mult/shift should have a little bit less entropy.

Even a system which *has* to do that crappy calibration still does it with a lot more *precision* than accuracy, so I suspect we ought to be rounding the result to the nearest 1MHz as long as that's within 10PPM or something like that. But that really *is* a digression :)

Quoted 13 lines

     That is more accurate than using the scaling factor on the old host plus the old host frequency. Especially if you are migrating the VM several times because every migration results obviously in rounding errors, while if you use the nominal guest frequency you keep this back and forth conversions and the resulting errors out of the way.

  #3 That's obviously related to #1

     The old host knows the guest TSC scaling and the guest offset, so it can take a coherent snapshot on the host side of REALTIME/TAI and the host TSC value, which is convertible to the guest TSC value.

Quoted 8 lines

  #4, 5

     are obviously required to set up the new host scaling/offset for the guest TSC, but if based on the nominal assumed TSC frequency of the guest it becomes actually accurate and usable across several migrations.

Anything else is just crystal ball magic, which is what KVM has today....

The model I'm enabling and documenting for KVM migration is basically within the noise of what you describe above, yes.

But if we want to give the illusion of the TSC just ticking away while the guest happens to experience a little steal time, when in fact it's been completely migrated to a new host, we actually want to work with the *true* running frequency of the TSC at the moment of migration.

So...

1) Use clock_get_time_reference() to get a { host tsc, time, rate }
from the source host at 'freeze' time.

2) Use clock_get_time_reference() to get a { host tsc, time, rate } from the destination host, when resuming.

3) (Optionally) scale the guest's TSC frequency, not by the *nominal* rates, but by the *actual* ratio of the rates from (1) and (2) above (plus any original nominal scaling of the guest's TSC from the original host).

4) Calculate the guest TSC *offset* in order to convey the effect that the guest's TSC continued to tick at the rate from (1), during the time period between (1) and (2).

5) (Optionally) Once the guest is running, slowly undo the scaling in (1) in order to get the guest back to a nice simple unscaled TSC (or scaled only by nominal frequencies as it was when launched)

Obviously, a dedicated environment which disciplines its TSC directly can do all of that right now already because it *has* all the information it would get from clock_get_time_reference().

But as you know perfectly well, Thomas, I'm never happy to keep the blinkers on and focus only on my specific use case at hand; I want this to work for the *general* case, including people running QEMU in a fairly standard environment. And I think clock_get_time_reference() might be a reasonable way of doing that, and a fairly clean counterpart to the clock_set_time_reference() you suggested?

maintainer
#22 lore raw

Re: [PATCH net-next v8 3/3] gve: implement PTP gettimex64

Quoted 12 lines · David Woodhouse
Quoted 11 lines · Thomas Gleixner

     1) Guest TSC value at freeze
     2) Guest nominal TSC frequency
     3) Old host REALTIME at freeze - Ideally you use TAI
     4) New host TSC frequency
     5) New host TSC/REALTIME/TAI snapshot

  #1 is a KVM problem, but see #3

  #2 ideally communicated from the guest to the host after early initialization at boot.

Quoted 6 lines
Quoted 2 lines

     You really want this information because the guest won't change the mult/shift pair for it ever.

If *tell* the guest the frequency in CPUID, then it shouldn't be trying to manually calibrate it against an emulated PIT while suffering steal time, and its mult/shift should have a little bit less entropy.

They are identical on every boot evaluation.

Quoted 4 lines

Even a system which *has* to do that crappy calibration still does it with a lot more *precision* than accuracy, so I suspect we ought to be rounding the result to the nearest 1MHz as long as that's within 10PPM or something like that. But that really *is* a digression :)

:)

Quoted 34 lines

The model I'm enabling and documenting for KVM migration is basically within the noise of what you describe above, yes.

But if we want to give the illusion of the TSC just ticking away while the guest happens to experience a little steal time, when in fact it's been completely migrated to a new host, we actually want to work with the *true* running frequency of the TSC at the moment of migration.

So...

1) Use clock_get_time_reference() to get a { host tsc, time, rate }
from the source host at 'freeze' time.

2) Use clock_get_time_reference() to get a { host tsc, time, rate } from the destination host, when resuming.

3) (Optionally) scale the guest's TSC frequency, not by the *nominal* rates, but by the *actual* ratio of the rates from (1) and (2) above (plus any original nominal scaling of the guest's TSC from the original host).

4) Calculate the guest TSC *offset* in order to convey the effect that the guest's TSC continued to tick at the rate from (1), during the time period between (1) and (2).

5) (Optionally) Once the guest is running, slowly undo the scaling in (1) in order to get the guest back to a nice simple unscaled TSC (or scaled only by nominal frequencies as it was when launched)

Obviously, a dedicated environment which disciplines its TSC directly can do all of that right now already because it *has* all the information it would get from clock_get_time_reference().

Quoted 6 lines

But as you know perfectly well, Thomas, I'm never happy to keep the blinkers on and focus only on my specific use case at hand; I want this to work for the *general* case, including people running QEMU in a fairly standard environment. And I think clock_get_time_reference() might be a reasonable way of doing that, and a fairly clean counterpart to the clock_set_time_reference() you suggested?

Agreed.

#23 lore raw
In reply to Harshitha Ramamurthy
This series was applied to netdev/net-next.git (main) by Jakub Kicinski <[email protected]>:

Hello:

This series was applied to netdev/net-next.git (main) by Jakub Kicinski <[email protected]>:

Quoted 6 lines · On Thu, 14 May 2026 22:58:39 +0000 you wrote:

From: Jordan Rhee <[email protected]>

This patch series adds support to obtain near-simultaneous NIC and system timestamps with gettimex64. This enables daemons like chrony and phc2sys to synchronize the system clock to the NIC clock.

Quoted 8 lines

GVE does not have direct register access to the NIC hardware clock, so it must issue an AdminQ command to read the NIC clock. Two paths for obtaining a cross-timestamp are implemented: a precise path using system counter values sampled by the device, and a fallback path using system counter values sampled in the driver using ptp_read_system_prets()/postts().

[...]

Here is the summary with links:
- [net-next,v8,1/3] gve: skip error logging for retryable AdminQ commands

    https://git.kernel.org/netdev/net-next/c/55687124a86f
  - [net-next,v8,2/3] gve: make nic clock reads thread safe
    https://git.kernel.org/netdev/net-next/c/4bbcd7e24aaa
  - [net-next,v8,3/3] gve: implement PTP gettimex64
    https://git.kernel.org/netdev/net-next/c/22b2aae747f7

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html