Skip to contentSkip to conversation

gve: add support for PTP gettimex64

PATCH Superseded Harshitha Ramamurthy 5 participants 16 messages Mar 26 – Apr 2

Subsystems (3)

v2 of 8 Superseded Latest is v8 →

lore
Share & tools
lore

Harshitha Ramamurthy

author maintainer
#0 lore raw

v2 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. Due to relatively high latency of AQ commands (~100us), it is necessary for the hypervisor to sample the system time sandwich inside the AQ command.

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

When tested inside a GCE C3 VM, this enabled chrony to synchronize the NIC clock and system clock with sub-microsecond precision.

chronyc tracking
Reference ID : 50484330 (PHC0)
Stratum : 1
Ref time (UTC) : Sat Feb 14 01:53:42 2026
System time : 0.000000001 seconds fast of NTP time
Last offset : -0.000000000 seconds
RMS offset : 0.000000001 seconds
Frequency : 0.686 ppm fast
Residual freq : -0.000 ppm
Skew : 0.001 ppm
Root delay : 0.000000001 seconds
Root dispersion : 0.000000812 seconds
Update interval : 0.5 seconds
Leap status : Normal

---
Changelog:
V2:
- Fixed compilation warning on ARM by casting to u64

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        |   6 +-
 drivers/net/ethernet/google/gve/gve_adminq.c |  26 ++-
 drivers/net/ethernet/google/gve/gve_adminq.h |   4 +-
 drivers/net/ethernet/google/gve/gve_ptp.c    | 209 +++++++++++++++++--
 4 files changed, 220 insertions(+), 25 deletions(-)

base-commit: 5446b8691eb8278f10deca92048fad84ffd1e4d5

Signature · 1 line
2.53.0.1018.g2bb0e51243-goog
author maintainer
#1 lore raw

PATCH v2 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.

---
 drivers/net/ethernet/google/gve/gve_adminq.c | 26 +++++++++++++++-----
 1 file changed, 20 insertions(+), 6 deletions(-)
drivers/net/ethernet/google/gve/gve_adminq.c +20 -6
index 08587bf40ed4..c7834614c5f0 100644
@@ -416,11 +416,6 @@ 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;
@@ -455,6 +450,16 @@ 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;
+	}
+}
+
 /* Flushes all AQ commands currently queued and waits for them to complete.
  * If there are failures, it will return the first error.
  */
@@ -482,9 +487,18 @@ static int gve_adminq_kick_and_wait(struct gve_priv *priv)
 		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 =
+				be32_to_cpu(READ_ONCE(cmd->opcode));
+			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.53.0.1018.g2bb0e51243-goog
#2 lore raw

Re: [PATCH net-next v2 1/3] gve: skip error logging for retryable AdminQ commands

Hi,

Quoted 51 lines · Harshitha Ramamurthy

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.

---
 drivers/net/ethernet/google/gve/gve_adminq.c | 26 +++++++++++++++-----
 1 file changed, 20 insertions(+), 6 deletions(-)
drivers/net/ethernet/google/gve/gve_adminq.c +10 -5
index 08587bf40ed4..c7834614c5f0 100644
@@ -416,11 +416,6 @@ 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;
@@ -455,6 +450,16 @@ 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;
+	}
+}
+
 /* Flushes all AQ commands currently queued and waits for them to complete.
  * If there are failures, it will return the first error.
  */

drivers/net/ethernet/google/gve/gve_adminq.c static int gve_adminq_kick_and_wait(struct gve_priv *priv) · line 494

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_adminq.c +5 -1
@@ -482,9 +487,18 @@ static int gve_adminq_kick_and_wait(struct gve_priv *priv)
 		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 =
+				be32_to_cpu(READ_ONCE(cmd->opcode));
+			priv->adminq_cmd_fail++;
+			if (!gve_adminq_is_retryable(opcode) || err != -EAGAIN)

In gve_adminq_kick_and_wait(), the condition is:

	if (!gve_adminq_is_retryable(opcode) || err != -EAGAIN)
		dev_err_ratelimited(...);

Based on the commit log, the goal is to skip logging when the result is -EAGAIN for transient conditions. However, when gve_adminq_is_retryable() returns false (e.g., GVE_ADMINQ_COMMAND_ERROR_ABORTED), even if err is -EAGAIN, the condition evaluates to true and the error would still be logged.

Would it be more appropriate to use && instead of || here?

	if (!gve_adminq_is_retryable(opcode) && err != -EAGAIN)

I may be missing something, so please let me know if I've misunderstood.

drivers/net/ethernet/google/gve/gve_adminq.c static int gve_adminq_kick_and_wait(struct gve_priv *priv) · line 504

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_adminq.c +5 -0
+				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;

Best regards,
Li Xiasong

#3 lore raw

Re: [PATCH net-next v2 1/3] gve: skip error logging for retryable AdminQ commands

Hi Li, thank you very much for the review. The intent is only to skip logging for *retryable* commands that return -EAGAIN. If a non-retryable command fails, we do want to log, even if it returns -EAGAIN.
Jordan

Quoted 94 lines · Li Xiasong

Hi,

Quoted 51 lines · Harshitha Ramamurthy

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.

---
 drivers/net/ethernet/google/gve/gve_adminq.c | 26 +++++++++++++++-----
 1 file changed, 20 insertions(+), 6 deletions(-)
drivers/net/ethernet/google/gve/gve_adminq.c +10 -5
index 08587bf40ed4..c7834614c5f0 100644
@@ -416,11 +416,6 @@ 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;
@@ -455,6 +450,16 @@ 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;
+     }
+}
+
 /* Flushes all AQ commands currently queued and waits for them to complete.
  * If there are failures, it will return the first error.
  */

drivers/net/ethernet/google/gve/gve_adminq.c static int gve_adminq_kick_and_wait(struct gve_priv *priv) · line 494

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_adminq.c +5 -1
@@ -482,9 +487,18 @@ static int gve_adminq_kick_and_wait(struct gve_priv *priv)
              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 =
+                             be32_to_cpu(READ_ONCE(cmd->opcode));
+                     priv->adminq_cmd_fail++;
+                     if (!gve_adminq_is_retryable(opcode) || err != -EAGAIN)

In gve_adminq_kick_and_wait(), the condition is:

        if (!gve_adminq_is_retryable(opcode) || err != -EAGAIN)
                dev_err_ratelimited(...);

Based on the commit log, the goal is to skip logging when the result is -EAGAIN for transient conditions. However, when gve_adminq_is_retryable() returns false (e.g., GVE_ADMINQ_COMMAND_ERROR_ABORTED), even if err is -EAGAIN, the condition evaluates to true and the error would still be logged.

Would it be more appropriate to use && instead of || here?

        if (!gve_adminq_is_retryable(opcode) && err != -EAGAIN)

I may be missing something, so please let me know if I've misunderstood.

drivers/net/ethernet/google/gve/gve_adminq.c static int gve_adminq_kick_and_wait(struct gve_priv *priv) · line 504

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_adminq.c +5 -0
+                             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;

Best regards,
Li Xiasong

#4 lore raw

Re: [PATCH net-next v2 1/3] gve: skip error logging for retryable AdminQ commands

Hi, Jordan

Quoted 6 lines · Jordan Rhee

Hi Li, thank you very much for the review. The intent is only to skip logging for *retryable* commands that return -EAGAIN. If a non-retryable command fails, we do want to log, even if it returns -EAGAIN.
Jordan

Thanks for the explanation! I totally misread the condition - I confused opcode with err because they both start with GVE_ADMINQ_.

The || makes perfect sense now. Sorry for the noise!

Best regards,
Li Xiasong

Quoted 96 lines · Li Xiasong
Quoted 94 lines

Hi,

Quoted 51 lines · Harshitha Ramamurthy

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.

---
 drivers/net/ethernet/google/gve/gve_adminq.c | 26 +++++++++++++++-----
 1 file changed, 20 insertions(+), 6 deletions(-)
drivers/net/ethernet/google/gve/gve_adminq.c +10 -5
index 08587bf40ed4..c7834614c5f0 100644
@@ -416,11 +416,6 @@ 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;
@@ -455,6 +450,16 @@ 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;
+     }
+}
+
 /* Flushes all AQ commands currently queued and waits for them to complete.
  * If there are failures, it will return the first error.
  */

drivers/net/ethernet/google/gve/gve_adminq.c static int gve_adminq_kick_and_wait(struct gve_priv *priv) · line 494

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_adminq.c +5 -1
@@ -482,9 +487,18 @@ static int gve_adminq_kick_and_wait(struct gve_priv *priv)
              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 =
+                             be32_to_cpu(READ_ONCE(cmd->opcode));
+                     priv->adminq_cmd_fail++;
+                     if (!gve_adminq_is_retryable(opcode) || err != -EAGAIN)

In gve_adminq_kick_and_wait(), the condition is:

        if (!gve_adminq_is_retryable(opcode) || err != -EAGAIN)
                dev_err_ratelimited(...);

Based on the commit log, the goal is to skip logging when the result is -EAGAIN for transient conditions. However, when gve_adminq_is_retryable() returns false (e.g., GVE_ADMINQ_COMMAND_ERROR_ABORTED), even if err is -EAGAIN, the condition evaluates to true and the error would still be logged.

Would it be more appropriate to use && instead of || here?

        if (!gve_adminq_is_retryable(opcode) && err != -EAGAIN)

I may be missing something, so please let me know if I've misunderstood.

drivers/net/ethernet/google/gve/gve_adminq.c static int gve_adminq_kick_and_wait(struct gve_priv *priv) · line 504

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_adminq.c +5 -0
+                             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;

Best regards,
Li Xiasong

author maintainer
#5 lore raw

PATCH v2 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.

---
 drivers/net/ethernet/google/gve/gve.h     |  6 +----
 drivers/net/ethernet/google/gve/gve_ptp.c | 32 +++++++++++++++--------
 2 files changed, 22 insertions(+), 16 deletions(-)
drivers/net/ethernet/google/gve/gve.h +1 -5
index 1d66d3834f7e..7b8f78bd1968 100644
@@ -923,6 +923,7 @@ struct gve_priv {
 	bool nic_timestamp_supported;
 	struct gve_ptp *ptp;
 	struct kernel_hwtstamp_config ts_config;
+	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;
 	u64 last_sync_nic_counter; /* Clock counter from last NIC TS report */
@@ -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_ptp.c +21 -11
index 06b1cf4a5efc..140b8fbce4f4 100644
@@ -11,19 +11,20 @@
 #define GVE_NIC_TS_SYNC_INTERVAL_MS 250
 
 /* Read the nic timestamp from hardware via the admin queue. */
-int gve_clock_nic_ts_read(struct gve_priv *priv)
+static int gve_clock_nic_ts_read(struct gve_priv *priv, u64 *nic_raw)
 {
-	u64 nic_raw;
 	int err;
 
+	mutex_lock(&priv->nic_ts_read_lock);
 	err = gve_adminq_report_nic_ts(priv, priv->nic_ts_report_bus);
 	if (err)
-		return err;
+		goto out;
 
-	nic_raw = be64_to_cpu(priv->nic_ts_report->nic_timestamp);
-	WRITE_ONCE(priv->last_sync_nic_counter, nic_raw);
+	*nic_raw = be64_to_cpu(priv->nic_ts_report->nic_timestamp);
 
-	return 0;
+out:
+	mutex_unlock(&priv->nic_ts_read_lock);
+	return err;
 }
 
 static int gve_ptp_gettimex64(struct ptp_clock_info *info,
@@ -43,15 +44,19 @@ static long gve_ptp_do_aux_work(struct ptp_clock_info *info)
 {
 	const struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
 	struct gve_priv *priv = ptp->priv;
+	u64 nic_raw;
 	int err;
 
 	if (gve_get_reset_in_progress(priv) || !gve_get_admin_queue_ok(priv))
 		goto out;
 
-	err = gve_clock_nic_ts_read(priv);
-	if (err && net_ratelimit())
-		dev_err(&priv->pdev->dev,
-			"%s read err %d\n", __func__, err);
+	err = gve_clock_nic_ts_read(priv, &nic_raw);
+	if (err) {
+		dev_err_ratelimited(&priv->pdev->dev, "%s read err %d\n",
+				    __func__, err);
+		goto out;
+	}
+	WRITE_ONCE(priv->last_sync_nic_counter, nic_raw);
 
 out:
 	return msecs_to_jiffies(GVE_NIC_TS_SYNC_INTERVAL_MS);
@@ -109,6 +114,7 @@ static void gve_ptp_release(struct gve_priv *priv)
 
 int gve_init_clock(struct gve_priv *priv)
 {
+	u64 nic_raw;
 	int err;
 
 	err = gve_ptp_init(priv);
@@ -125,17 +131,20 @@ int gve_init_clock(struct gve_priv *priv)
 		err = -ENOMEM;
 		goto release_ptp;
 	}
-	err = gve_clock_nic_ts_read(priv);
+	mutex_init(&priv->nic_ts_read_lock);
+	err = gve_clock_nic_ts_read(priv, &nic_raw);
 	if (err) {
 		dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
 		goto release_nic_ts_report;
 	}
+	WRITE_ONCE(priv->last_sync_nic_counter, nic_raw);
 	ptp_schedule_worker(priv->ptp->clock,
 			    msecs_to_jiffies(GVE_NIC_TS_SYNC_INTERVAL_MS));
 
 	return 0;
 
 release_nic_ts_report:
+	mutex_destroy(&priv->nic_ts_read_lock);
 	dma_free_coherent(&priv->pdev->dev,
 			  sizeof(struct gve_nic_ts_report),
 			  priv->nic_ts_report, priv->nic_ts_report_bus);
@@ -150,6 +159,7 @@ void gve_teardown_clock(struct gve_priv *priv)
 	gve_ptp_release(priv);
 
 	if (priv->nic_ts_report) {
+		mutex_destroy(&priv->nic_ts_read_lock);
 		dma_free_coherent(&priv->pdev->dev,
 				  sizeof(struct gve_nic_ts_report),
 				  priv->nic_ts_report, priv->nic_ts_report_bus);
Signature · 1 line
2.53.0.1018.g2bb0e51243-goog
maintainer
#6 lore raw

Re: [PATCH net-next v2 2/3] gve: make nic clock reads thread safe

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
gve: make nic clock reads thread safe

This commit adds a mutex to protect the shared DMA buffer used for receiving NIC timestamp reports. The lock is needed to synchronize the periodic worker and the upcoming gettimex64 ioctl.

Quoted 4 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 06b1cf4a5efc..140b8fbce4f4 100644

[ ... ]

Quoted 8 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -0
@@ -109,6 +114,7 @@ static void gve_ptp_release(struct gve_priv *priv)
 
 int gve_init_clock(struct gve_priv *priv)
 {
+	u64 nic_raw;
 	int err;
 
 	err = gve_ptp_init(priv);

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 135

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
@@ -125,17 +131,20 @@ int gve_init_clock(struct gve_priv *priv)
 		err = -ENOMEM;
 		goto release_ptp;
 	}
-	err = gve_clock_nic_ts_read(priv);
+	mutex_init(&priv->nic_ts_read_lock);
+	err = gve_clock_nic_ts_read(priv, &nic_raw);

Could this lead to a race condition with userspace?

If gve_ptp_init() registers the PTP clock via ptp_clock_register(), the device is exposed to userspace immediately. If a userspace process opens the device and calls the gettimex64 ioctl before the mutex and DMA buffer are initialized here, it could cause a NULL pointer dereference or operate on an uninitialized mutex.

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -0
 	if (err) {
 		dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
 		goto release_nic_ts_report;
 	}
+	WRITE_ONCE(priv->last_sync_nic_counter, nic_raw);

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 150

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -0
 	ptp_schedule_worker(priv->ptp->clock,
 			    msecs_to_jiffies(GVE_NIC_TS_SYNC_INTERVAL_MS));
 
 	return 0;
 
 release_nic_ts_report:
+	mutex_destroy(&priv->nic_ts_read_lock);
 	dma_free_coherent(&priv->pdev->dev,
 			  sizeof(struct gve_nic_ts_report),
 			  priv->nic_ts_report, priv->nic_ts_report_bus);

Is it safe to destroy the mutex and free the DMA buffer before calling gve_ptp_release() here?

If the PTP clock is already registered and exposed to userspace by gve_ptp_init(), this error path frees resources while the clock is still active. A concurrent userspace ioctl could access the destroyed mutex or freed buffer before gve_ptp_release() unregisters the clock.

Should all resource allocation and initialization strictly precede ptp_clock_register(), and the error path unregister the clock before tearing down the resources?

Signature · 1 line
pw-bot: cr
#7 lore raw

Re: [PATCH net-next v2 2/3] gve: make nic clock reads thread safe

Quoted 38 lines · Jakub Kicinski

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
gve: make nic clock reads thread safe

This commit adds a mutex to protect the shared DMA buffer used for receiving NIC timestamp reports. The lock is needed to synchronize the periodic worker and the upcoming gettimex64 ioctl.

Quoted 4 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 06b1cf4a5efc..140b8fbce4f4 100644

[ ... ]

Quoted 8 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -0
@@ -109,6 +114,7 @@ static void gve_ptp_release(struct gve_priv *priv)
 
 int gve_init_clock(struct gve_priv *priv)
 {
+     u64 nic_raw;
      int err;
 
      err = gve_ptp_init(priv);

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 135

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
@@ -125,17 +131,20 @@ int gve_init_clock(struct gve_priv *priv)
              err = -ENOMEM;
              goto release_ptp;
      }
-     err = gve_clock_nic_ts_read(priv);
+     mutex_init(&priv->nic_ts_read_lock);
+     err = gve_clock_nic_ts_read(priv, &nic_raw);

Could this lead to a race condition with userspace?

Quoted 5 lines

If gve_ptp_init() registers the PTP clock via ptp_clock_register(), the device is exposed to userspace immediately. If a userspace process opens the device and calls the gettimex64 ioctl before the mutex and DMA buffer are initialized here, it could cause a NULL pointer dereference or operate on an uninitialized mutex.

Ack, will fix.

Quoted 20 lines
Quoted 6 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -0
      if (err) {
              dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
              goto release_nic_ts_report;
      }
+     WRITE_ONCE(priv->last_sync_nic_counter, nic_raw);

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 150

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -0
      ptp_schedule_worker(priv->ptp->clock,
                          msecs_to_jiffies(GVE_NIC_TS_SYNC_INTERVAL_MS));
 
      return 0;
 
 release_nic_ts_report:
+     mutex_destroy(&priv->nic_ts_read_lock);
      dma_free_coherent(&priv->pdev->dev,
                        sizeof(struct gve_nic_ts_report),
                        priv->nic_ts_report, priv->nic_ts_report_bus);

Is it safe to destroy the mutex and free the DMA buffer before calling gve_ptp_release() here?

Quoted 8 lines

If the PTP clock is already registered and exposed to userspace by gve_ptp_init(), this error path frees resources while the clock is still active. A concurrent userspace ioctl could access the destroyed mutex or freed buffer before gve_ptp_release() unregisters the clock.

Should all resource allocation and initialization strictly precede ptp_clock_register(), and the error path unregister the clock before tearing down the resources?

Ack, will fix.

Quoted 2 lines

--
pw-bot: cr

author maintainer
#8 lore raw

PATCH v2 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.

The system cycle counters are sampled by the device to minimize the uncertainty window. If the system times are sampled in the host, the delta between pre and post readings is 100us or more due to AQ command latency. The system times returned by the device have a delta of ~1us, which enables significantly more accurate clock synchronization.

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

---
 drivers/net/ethernet/google/gve/gve_adminq.h |   4 +-
 drivers/net/ethernet/google/gve/gve_ptp.c    | 189 ++++++++++++++++++-
 2 files changed, 184 insertions(+), 9 deletions(-)
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_ptp.c +182 -7

224 lines not on this page · raw message

Signature · 1 line
2.53.0.1018.g2bb0e51243-goog
maintainer
#9 lore raw

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

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
Subject: gve: implement PTP gettimex64

This commit implements the PTP gettimex64 function to enable chrony and phc2sys to synchronize the system clock to the NIC clock. It reads the NIC timestamp along with pre and post system cycle counters to minimize the uncertainty window.

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 140b8fbce4f4..bea794541f30 100644
@@ -10,28 +10,203 @@

[ ... ]

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +7 -0
+static int gve_adminq_read_timestamp(struct gve_priv *priv,
+				     cycles_t *pre_cycles,
+				     cycles_t *post_cycles)
+{
+	unsigned long delay_us = 1000;
+	int retry_count = 0;
+	int err;

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+
+	lockdep_assert_held(&priv->nic_ts_read_lock);
+
+	do {
+		*pre_cycles = get_cycles();
+		err = gve_adminq_report_nic_ts(priv, priv->nic_ts_report_bus);
+
+		/* Ensure cycle counter is sampled after AdminQ cmd returns */
+		rmb();
+		*post_cycles = get_cycles();

Are execution barriers needed around get_cycles() here? rmb() orders memory accesses, but the CPU might still speculatively execute the cycle counter reads out of order with respect to the AdminQ commands.

Could this speculative reordering cause the strict bounds validation in gve_ptp_gettimex64() to fail spuriously?

[ ... ]

Quoted 7 lines

static int gve_ptp_gettimex64(struct ptp_clock_info *info,

drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
 			      struct timespec64 *ts,
 			      struct ptp_system_timestamp *sts)
 {
-	return -EOPNOTSUPP;
+	struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
+	struct gve_sysclock_sample sysclock = {0};

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+	struct gve_priv *priv = ptp->priv;
+	struct system_time_snapshot snap;
+	u64 nic_ts;
+	int err;
+
+	/* Take system clock snapshot before sampling cycle counters */
+	if (sts)
+		ktime_get_snapshot(&snap);
+
+	err = gve_clock_nic_ts_read(priv, &nic_ts, &sysclock);

Could the system time snapshot become stale here?

If priv->nic_ts_read_lock is contended, or if gve_adminq_read_timestamp() retries and sleeps, the snapshot might be taken significantly before the actual hardware read.

Would it be more accurate to take the snapshot immediately before reading the hardware, inside the mutex?

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +5 -0
+	if (err)
+		return err;
+
+	if (sts) {
+		/* Reject samples with out of order system clock values */

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+		if (!(sysclock.host_pre_cycles <= sysclock.nic_pre_cycles &&
+		      sysclock.nic_pre_cycles  <= sysclock.nic_post_cycles &&
+		      sysclock.nic_post_cycles <= sysclock.host_post_cycles)) {
+			dev_err_ratelimited(&priv->pdev->dev,
+					    "AdminQ system clock cycle counts out of order. Expecting %llu <= %llu <= %llu <= %llu\n",
+					    (u64)sysclock.host_pre_cycles,
+					    sysclock.nic_pre_cycles,
+					    sysclock.nic_post_cycles,
+					    (u64)sysclock.host_post_cycles);
+			return -EBADMSG;

How does this behave on architectures where get_cycles() is not implemented and returns 0, or with older firmware that leaves nic_pre_cycles and nic_post_cycles as 0?

It looks like the bounds check would unconditionally fail and return -EBADMSG. Since userspace tools like chrony usually expect -EOPNOTSUPP for unsupported extended ioctls to fall back to basic PTP ioctls, will returning -EBADMSG cause a hard failure for clock synchronization?

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 313

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -1
@@ -132,7 +307,7 @@ int gve_init_clock(struct gve_priv *priv)
 		goto release_ptp;
 	}
 	mutex_init(&priv->nic_ts_read_lock);
-	err = gve_clock_nic_ts_read(priv, &nic_raw);
+	err = gve_clock_nic_ts_read(priv, &nic_raw, NULL);
 	if (err) {
 		dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
 		goto release_nic_ts_report;

Is there a race condition exposing the PTP device to userspace before its resources are fully initialized?

Looking at gve_init_clock(), gve_ptp_init() is called before allocating nic_ts_report and initializing nic_ts_read_lock:

    err = gve_ptp_init(priv);
    if (err)
        return err;

    priv->nic_ts_report = dma_alloc_coherent(...);
    ...
    mutex_init(&priv->nic_ts_read_lock);

If a concurrent userspace process immediately invokes the PTP_SYS_OFFSET_EXTENDED ioctl after gve_ptp_init() registers the /dev/ptpX device, could it call gve_ptp_gettimex64() and attempt to lock the uninitialized mutex or dereference the NULL nic_ts_report pointer?

Additionally, in the error path for gve_init_clock():

    release_nic_ts_report:
        mutex_destroy(&priv->nic_ts_read_lock);
        dma_free_coherent(...);
        priv->nic_ts_report = NULL;
    release_ptp:
        gve_ptp_release(priv);

Could destroying the mutex and freeing the memory before gve_ptp_release() create a use-after-free window if an ioctl is currently running?

#10 lore raw

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

Quoted 41 lines · Jakub Kicinski

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
Subject: gve: implement PTP gettimex64

This commit implements the PTP gettimex64 function to enable chrony and phc2sys to synchronize the system clock to the NIC clock. It reads the NIC timestamp along with pre and post system cycle counters to minimize the uncertainty window.

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 140b8fbce4f4..bea794541f30 100644
@@ -10,28 +10,203 @@

[ ... ]

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +7 -0
+static int gve_adminq_read_timestamp(struct gve_priv *priv,
+                                  cycles_t *pre_cycles,
+                                  cycles_t *post_cycles)
+{
+     unsigned long delay_us = 1000;
+     int retry_count = 0;
+     int err;

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+
+     lockdep_assert_held(&priv->nic_ts_read_lock);
+
+     do {
+             *pre_cycles = get_cycles();
+             err = gve_adminq_report_nic_ts(priv, priv->nic_ts_report_bus);
+
+             /* Ensure cycle counter is sampled after AdminQ cmd returns */
+             rmb();
+             *post_cycles = get_cycles();

Are execution barriers needed around get_cycles() here? rmb() orders memory accesses, but the CPU might still speculatively execute the cycle counter reads out of order with respect to the AdminQ commands.

Quoted 2 lines

Could this speculative reordering cause the strict bounds validation in gve_ptp_gettimex64() to fail spuriously?

I will add mb() barriers to be totally safe.

Quoted 22 lines

[ ... ]

Quoted 7 lines

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

drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
-     return -EOPNOTSUPP;
+     struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
+     struct gve_sysclock_sample sysclock = {0};

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+     struct gve_priv *priv = ptp->priv;
+     struct system_time_snapshot snap;
+     u64 nic_ts;
+     int err;
+
+     /* Take system clock snapshot before sampling cycle counters */
+     if (sts)
+             ktime_get_snapshot(&snap);
+
+     err = gve_clock_nic_ts_read(priv, &nic_ts, &sysclock);

Could the system time snapshot become stale here?

Quoted 6 lines

If priv->nic_ts_read_lock is contended, or if gve_adminq_read_timestamp() retries and sleeps, the snapshot might be taken significantly before the actual hardware read.

Would it be more accurate to take the snapshot immediately before reading the hardware, inside the mutex?

Ack, will fix.

Quoted 17 lines
Quoted 6 lines
drivers/net/ethernet/google/gve/gve_ptp.c +5 -0
+     if (err)
+             return err;
+
+     if (sts) {
+             /* Reject samples with out of order system clock values */

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+             if (!(sysclock.host_pre_cycles <= sysclock.nic_pre_cycles &&
+                   sysclock.nic_pre_cycles  <= sysclock.nic_post_cycles &&
+                   sysclock.nic_post_cycles <= sysclock.host_post_cycles)) {
+                     dev_err_ratelimited(&priv->pdev->dev,
+                                         "AdminQ system clock cycle counts out of order. Expecting %llu <= %llu <= %llu <= %llu\n",
+                                         (u64)sysclock.host_pre_cycles,
+                                         sysclock.nic_pre_cycles,
+                                         sysclock.nic_post_cycles,
+                                         (u64)sysclock.host_post_cycles);
+                     return -EBADMSG;
Quoted 3 lines

How does this behave on architectures where get_cycles() is not implemented and returns 0, or with older firmware that leaves nic_pre_cycles and nic_post_cycles as 0?

Firmware is not allowed to return 0. 0 should trigger the check.

Quoted 4 lines

It looks like the bounds check would unconditionally fail and return -EBADMSG. Since userspace tools like chrony usually expect -EOPNOTSUPP for unsupported extended ioctls to fall back to basic PTP ioctls, will returning -EBADMSG cause a hard failure for clock synchronization?

Will fix. GVE is only supported on x86_64 and arm64, and will fail on other architectures with -EOPNOTSUPP due to the check in gve_cycles_to_clock_fn(). However, if an architecture returns get_cycles() as 0, it will fail here first with -EBADMSG. I will add an explicit check for x86 || arm64 earlier in this function.

Quoted 41 lines

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 313

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -1
@@ -132,7 +307,7 @@ int gve_init_clock(struct gve_priv *priv)
              goto release_ptp;
      }
      mutex_init(&priv->nic_ts_read_lock);
-     err = gve_clock_nic_ts_read(priv, &nic_raw);
+     err = gve_clock_nic_ts_read(priv, &nic_raw, NULL);
      if (err) {
              dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
              goto release_nic_ts_report;

Is there a race condition exposing the PTP device to userspace before its resources are fully initialized?

Looking at gve_init_clock(), gve_ptp_init() is called before allocating nic_ts_report and initializing nic_ts_read_lock:

    err = gve_ptp_init(priv);
    if (err)
        return err;

    priv->nic_ts_report = dma_alloc_coherent(...);
    ...
    mutex_init(&priv->nic_ts_read_lock);

If a concurrent userspace process immediately invokes the PTP_SYS_OFFSET_EXTENDED ioctl after gve_ptp_init() registers the /dev/ptpX device, could it call gve_ptp_gettimex64() and attempt to lock the uninitialized mutex or dereference the NULL nic_ts_report pointer?

Additionally, in the error path for gve_init_clock():

    release_nic_ts_report:
        mutex_destroy(&priv->nic_ts_read_lock);
        dma_free_coherent(...);
        priv->nic_ts_report = NULL;
    release_ptp:
        gve_ptp_release(priv);
Quoted 2 lines

Could destroying the mutex and freeing the memory before gve_ptp_release() create a use-after-free window if an ioctl is currently running?

Will be fixed in the previous patch in the series.

#11 lore raw

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

Quoted 43 lines · Jordan Rhee
Quoted 41 lines · Jakub Kicinski

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
Subject: gve: implement PTP gettimex64

This commit implements the PTP gettimex64 function to enable chrony and phc2sys to synchronize the system clock to the NIC clock. It reads the NIC timestamp along with pre and post system cycle counters to minimize the uncertainty window.

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 140b8fbce4f4..bea794541f30 100644
@@ -10,28 +10,203 @@

[ ... ]

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +7 -0
+static int gve_adminq_read_timestamp(struct gve_priv *priv,
+                                  cycles_t *pre_cycles,
+                                  cycles_t *post_cycles)
+{
+     unsigned long delay_us = 1000;
+     int retry_count = 0;
+     int err;

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+
+     lockdep_assert_held(&priv->nic_ts_read_lock);
+
+     do {
+             *pre_cycles = get_cycles();
+             err = gve_adminq_report_nic_ts(priv, priv->nic_ts_report_bus);
+
+             /* Ensure cycle counter is sampled after AdminQ cmd returns */
+             rmb();
+             *post_cycles = get_cycles();

Are execution barriers needed around get_cycles() here? rmb() orders memory accesses, but the CPU might still speculatively execute the cycle counter reads out of order with respect to the AdminQ commands.

Quoted 4 lines
Quoted 2 lines

Could this speculative reordering cause the strict bounds validation in gve_ptp_gettimex64() to fail spuriously?

I will add mb() barriers to be totally safe.

I'm not so sure that rmb() is insufficient here. In x86_64 rmb() is an lfence. lfence is used to prevent speculative execution (per the x86 barrier_nospec implementation) and rdtsc_ordered, which is called by the ktime* helpers, also prefaces rdtsc with an lfence. On ARM the get_cycles implementation adds an isb instruction before reading cntvct_el0.

Quoted 111 lines
Quoted 23 lines

[ ... ]

Quoted 7 lines

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

drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
-     return -EOPNOTSUPP;
+     struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
+     struct gve_sysclock_sample sysclock = {0};

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+     struct gve_priv *priv = ptp->priv;
+     struct system_time_snapshot snap;
+     u64 nic_ts;
+     int err;
+
+     /* Take system clock snapshot before sampling cycle counters */
+     if (sts)
+             ktime_get_snapshot(&snap);
+
+     err = gve_clock_nic_ts_read(priv, &nic_ts, &sysclock);

Could the system time snapshot become stale here?

Quoted 6 lines

If priv->nic_ts_read_lock is contended, or if gve_adminq_read_timestamp() retries and sleeps, the snapshot might be taken significantly before the actual hardware read.

Would it be more accurate to take the snapshot immediately before reading the hardware, inside the mutex?

Ack, will fix.

Quoted 17 lines
Quoted 6 lines
drivers/net/ethernet/google/gve/gve_ptp.c +5 -0
+     if (err)
+             return err;
+
+     if (sts) {
+             /* Reject samples with out of order system clock values */

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+             if (!(sysclock.host_pre_cycles <= sysclock.nic_pre_cycles &&
+                   sysclock.nic_pre_cycles  <= sysclock.nic_post_cycles &&
+                   sysclock.nic_post_cycles <= sysclock.host_post_cycles)) {
+                     dev_err_ratelimited(&priv->pdev->dev,
+                                         "AdminQ system clock cycle counts out of order. Expecting %llu <= %llu <= %llu <= %llu\n",
+                                         (u64)sysclock.host_pre_cycles,
+                                         sysclock.nic_pre_cycles,
+                                         sysclock.nic_post_cycles,
+                                         (u64)sysclock.host_post_cycles);
+                     return -EBADMSG;
Quoted 3 lines

How does this behave on architectures where get_cycles() is not implemented and returns 0, or with older firmware that leaves nic_pre_cycles and nic_post_cycles as 0?

Firmware is not allowed to return 0. 0 should trigger the check.

Quoted 4 lines

It looks like the bounds check would unconditionally fail and return -EBADMSG. Since userspace tools like chrony usually expect -EOPNOTSUPP for unsupported extended ioctls to fall back to basic PTP ioctls, will returning -EBADMSG cause a hard failure for clock synchronization?

Will fix. GVE is only supported on x86_64 and arm64, and will fail on other architectures with -EOPNOTSUPP due to the check in gve_cycles_to_clock_fn(). However, if an architecture returns get_cycles() as 0, it will fail here first with -EBADMSG. I will add an explicit check for x86 || arm64 earlier in this function.

Quoted 41 lines

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 313

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -1
@@ -132,7 +307,7 @@ int gve_init_clock(struct gve_priv *priv)
              goto release_ptp;
      }
      mutex_init(&priv->nic_ts_read_lock);
-     err = gve_clock_nic_ts_read(priv, &nic_raw);
+     err = gve_clock_nic_ts_read(priv, &nic_raw, NULL);
      if (err) {
              dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
              goto release_nic_ts_report;

Is there a race condition exposing the PTP device to userspace before its resources are fully initialized?

Looking at gve_init_clock(), gve_ptp_init() is called before allocating nic_ts_report and initializing nic_ts_read_lock:

    err = gve_ptp_init(priv);
    if (err)
        return err;

    priv->nic_ts_report = dma_alloc_coherent(...);
    ...
    mutex_init(&priv->nic_ts_read_lock);

If a concurrent userspace process immediately invokes the PTP_SYS_OFFSET_EXTENDED ioctl after gve_ptp_init() registers the /dev/ptpX device, could it call gve_ptp_gettimex64() and attempt to lock the uninitialized mutex or dereference the NULL nic_ts_report pointer?

Additionally, in the error path for gve_init_clock():

    release_nic_ts_report:
        mutex_destroy(&priv->nic_ts_read_lock);
        dma_free_coherent(...);
        priv->nic_ts_report = NULL;
    release_ptp:
        gve_ptp_release(priv);
Quoted 2 lines

Could destroying the mutex and freeing the memory before gve_ptp_release() create a use-after-free window if an ioctl is currently running?

Will be fixed in the previous patch in the series.

#12 lore raw

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

We know that gve_adminq_report_nic_ts() will cause a VM exit, which will act as a full barrier. Additional barriers are not strictly necessary from a functional perspective. Can we rely on this fact or do we need explicit barriers?

Quoted 169 lines · Naman Gulati
Quoted 43 lines · Jordan Rhee
Quoted 41 lines · Jakub Kicinski

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
Subject: gve: implement PTP gettimex64

This commit implements the PTP gettimex64 function to enable chrony and phc2sys to synchronize the system clock to the NIC clock. It reads the NIC timestamp along with pre and post system cycle counters to minimize the uncertainty window.

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 140b8fbce4f4..bea794541f30 100644
@@ -10,28 +10,203 @@

[ ... ]

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +7 -0
+static int gve_adminq_read_timestamp(struct gve_priv *priv,
+                                  cycles_t *pre_cycles,
+                                  cycles_t *post_cycles)
+{
+     unsigned long delay_us = 1000;
+     int retry_count = 0;
+     int err;

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+
+     lockdep_assert_held(&priv->nic_ts_read_lock);
+
+     do {
+             *pre_cycles = get_cycles();
+             err = gve_adminq_report_nic_ts(priv, priv->nic_ts_report_bus);
+
+             /* Ensure cycle counter is sampled after AdminQ cmd returns */
+             rmb();
+             *post_cycles = get_cycles();

Are execution barriers needed around get_cycles() here? rmb() orders memory accesses, but the CPU might still speculatively execute the cycle counter reads out of order with respect to the AdminQ commands.

Quoted 4 lines
Quoted 2 lines

Could this speculative reordering cause the strict bounds validation in gve_ptp_gettimex64() to fail spuriously?

I will add mb() barriers to be totally safe.

I'm not so sure that rmb() is insufficient here. In x86_64 rmb() is an lfence. lfence is used to prevent speculative execution (per the x86 barrier_nospec implementation) and rdtsc_ordered, which is called by the ktime* helpers, also prefaces rdtsc with an lfence. On ARM the get_cycles implementation adds an isb instruction before reading cntvct_el0.

Quoted 111 lines
Quoted 23 lines

[ ... ]

Quoted 7 lines

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

drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
-     return -EOPNOTSUPP;
+     struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
+     struct gve_sysclock_sample sysclock = {0};

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+     struct gve_priv *priv = ptp->priv;
+     struct system_time_snapshot snap;
+     u64 nic_ts;
+     int err;
+
+     /* Take system clock snapshot before sampling cycle counters */
+     if (sts)
+             ktime_get_snapshot(&snap);
+
+     err = gve_clock_nic_ts_read(priv, &nic_ts, &sysclock);

Could the system time snapshot become stale here?

Quoted 6 lines

If priv->nic_ts_read_lock is contended, or if gve_adminq_read_timestamp() retries and sleeps, the snapshot might be taken significantly before the actual hardware read.

Would it be more accurate to take the snapshot immediately before reading the hardware, inside the mutex?

Ack, will fix.

Quoted 17 lines
Quoted 6 lines
drivers/net/ethernet/google/gve/gve_ptp.c +5 -0
+     if (err)
+             return err;
+
+     if (sts) {
+             /* Reject samples with out of order system clock values */

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+             if (!(sysclock.host_pre_cycles <= sysclock.nic_pre_cycles &&
+                   sysclock.nic_pre_cycles  <= sysclock.nic_post_cycles &&
+                   sysclock.nic_post_cycles <= sysclock.host_post_cycles)) {
+                     dev_err_ratelimited(&priv->pdev->dev,
+                                         "AdminQ system clock cycle counts out of order. Expecting %llu <= %llu <= %llu <= %llu\n",
+                                         (u64)sysclock.host_pre_cycles,
+                                         sysclock.nic_pre_cycles,
+                                         sysclock.nic_post_cycles,
+                                         (u64)sysclock.host_post_cycles);
+                     return -EBADMSG;
Quoted 3 lines

How does this behave on architectures where get_cycles() is not implemented and returns 0, or with older firmware that leaves nic_pre_cycles and nic_post_cycles as 0?

Firmware is not allowed to return 0. 0 should trigger the check.

Quoted 4 lines

It looks like the bounds check would unconditionally fail and return -EBADMSG. Since userspace tools like chrony usually expect -EOPNOTSUPP for unsupported extended ioctls to fall back to basic PTP ioctls, will returning -EBADMSG cause a hard failure for clock synchronization?

Will fix. GVE is only supported on x86_64 and arm64, and will fail on other architectures with -EOPNOTSUPP due to the check in gve_cycles_to_clock_fn(). However, if an architecture returns get_cycles() as 0, it will fail here first with -EBADMSG. I will add an explicit check for x86 || arm64 earlier in this function.

Quoted 41 lines

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 313

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -1
@@ -132,7 +307,7 @@ int gve_init_clock(struct gve_priv *priv)
              goto release_ptp;
      }
      mutex_init(&priv->nic_ts_read_lock);
-     err = gve_clock_nic_ts_read(priv, &nic_raw);
+     err = gve_clock_nic_ts_read(priv, &nic_raw, NULL);
      if (err) {
              dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
              goto release_nic_ts_report;

Is there a race condition exposing the PTP device to userspace before its resources are fully initialized?

Looking at gve_init_clock(), gve_ptp_init() is called before allocating nic_ts_report and initializing nic_ts_read_lock:

    err = gve_ptp_init(priv);
    if (err)
        return err;

    priv->nic_ts_report = dma_alloc_coherent(...);
    ...
    mutex_init(&priv->nic_ts_read_lock);

If a concurrent userspace process immediately invokes the PTP_SYS_OFFSET_EXTENDED ioctl after gve_ptp_init() registers the /dev/ptpX device, could it call gve_ptp_gettimex64() and attempt to lock the uninitialized mutex or dereference the NULL nic_ts_report pointer?

Additionally, in the error path for gve_init_clock():

    release_nic_ts_report:
        mutex_destroy(&priv->nic_ts_read_lock);
        dma_free_coherent(...);
        priv->nic_ts_report = NULL;
    release_ptp:
        gve_ptp_release(priv);
Quoted 2 lines

Could destroying the mutex and freeing the memory before gve_ptp_release() create a use-after-free window if an ioctl is currently running?

Will be fixed in the previous patch in the series.

#13 lore raw

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

Quoted 5 lines · Jordan Rhee

We know that gve_adminq_report_nic_ts() will cause a VM exit, which will act as a full barrier. Additional barriers are not strictly necessary from a functional perspective. Can we rely on this fact or do we need explicit barriers?

I don't think that's enough. Without a barrier get_cycles can be speculatively executed before gve_adminq_report_nic_ts.

Quoted 172 lines · Naman Gulati
Quoted 169 lines · Jordan Rhee
Quoted 43 lines · Jakub Kicinski
Quoted 41 lines

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
Subject: gve: implement PTP gettimex64

This commit implements the PTP gettimex64 function to enable chrony and phc2sys to synchronize the system clock to the NIC clock. It reads the NIC timestamp along with pre and post system cycle counters to minimize the uncertainty window.

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 140b8fbce4f4..bea794541f30 100644
@@ -10,28 +10,203 @@

[ ... ]

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +7 -0
+static int gve_adminq_read_timestamp(struct gve_priv *priv,
+                                  cycles_t *pre_cycles,
+                                  cycles_t *post_cycles)
+{
+     unsigned long delay_us = 1000;
+     int retry_count = 0;
+     int err;

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+
+     lockdep_assert_held(&priv->nic_ts_read_lock);
+
+     do {
+             *pre_cycles = get_cycles();
+             err = gve_adminq_report_nic_ts(priv, priv->nic_ts_report_bus);
+
+             /* Ensure cycle counter is sampled after AdminQ cmd returns */
+             rmb();
+             *post_cycles = get_cycles();

Are execution barriers needed around get_cycles() here? rmb() orders memory accesses, but the CPU might still speculatively execute the cycle counter reads out of order with respect to the AdminQ commands.

Quoted 4 lines
Quoted 2 lines

Could this speculative reordering cause the strict bounds validation in gve_ptp_gettimex64() to fail spuriously?

I will add mb() barriers to be totally safe.

I'm not so sure that rmb() is insufficient here. In x86_64 rmb() is an lfence. lfence is used to prevent speculative execution (per the x86 barrier_nospec implementation) and rdtsc_ordered, which is called by the ktime* helpers, also prefaces rdtsc with an lfence. On ARM the get_cycles implementation adds an isb instruction before reading cntvct_el0.

Quoted 111 lines
Quoted 23 lines

[ ... ]

Quoted 7 lines

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

drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
-     return -EOPNOTSUPP;
+     struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
+     struct gve_sysclock_sample sysclock = {0};

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+     struct gve_priv *priv = ptp->priv;
+     struct system_time_snapshot snap;
+     u64 nic_ts;
+     int err;
+
+     /* Take system clock snapshot before sampling cycle counters */
+     if (sts)
+             ktime_get_snapshot(&snap);
+
+     err = gve_clock_nic_ts_read(priv, &nic_ts, &sysclock);

Could the system time snapshot become stale here?

Quoted 6 lines

If priv->nic_ts_read_lock is contended, or if gve_adminq_read_timestamp() retries and sleeps, the snapshot might be taken significantly before the actual hardware read.

Would it be more accurate to take the snapshot immediately before reading the hardware, inside the mutex?

Ack, will fix.

Quoted 17 lines
Quoted 6 lines
drivers/net/ethernet/google/gve/gve_ptp.c +5 -0
+     if (err)
+             return err;
+
+     if (sts) {
+             /* Reject samples with out of order system clock values */

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+             if (!(sysclock.host_pre_cycles <= sysclock.nic_pre_cycles &&
+                   sysclock.nic_pre_cycles  <= sysclock.nic_post_cycles &&
+                   sysclock.nic_post_cycles <= sysclock.host_post_cycles)) {
+                     dev_err_ratelimited(&priv->pdev->dev,
+                                         "AdminQ system clock cycle counts out of order. Expecting %llu <= %llu <= %llu <= %llu\n",
+                                         (u64)sysclock.host_pre_cycles,
+                                         sysclock.nic_pre_cycles,
+                                         sysclock.nic_post_cycles,
+                                         (u64)sysclock.host_post_cycles);
+                     return -EBADMSG;
Quoted 3 lines

How does this behave on architectures where get_cycles() is not implemented and returns 0, or with older firmware that leaves nic_pre_cycles and nic_post_cycles as 0?

Firmware is not allowed to return 0. 0 should trigger the check.

Quoted 4 lines

It looks like the bounds check would unconditionally fail and return -EBADMSG. Since userspace tools like chrony usually expect -EOPNOTSUPP for unsupported extended ioctls to fall back to basic PTP ioctls, will returning -EBADMSG cause a hard failure for clock synchronization?

Will fix. GVE is only supported on x86_64 and arm64, and will fail on other architectures with -EOPNOTSUPP due to the check in gve_cycles_to_clock_fn(). However, if an architecture returns get_cycles() as 0, it will fail here first with -EBADMSG. I will add an explicit check for x86 || arm64 earlier in this function.

Quoted 41 lines

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 313

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -1
@@ -132,7 +307,7 @@ int gve_init_clock(struct gve_priv *priv)
              goto release_ptp;
      }
      mutex_init(&priv->nic_ts_read_lock);
-     err = gve_clock_nic_ts_read(priv, &nic_raw);
+     err = gve_clock_nic_ts_read(priv, &nic_raw, NULL);
      if (err) {
              dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
              goto release_nic_ts_report;

Is there a race condition exposing the PTP device to userspace before its resources are fully initialized?

Looking at gve_init_clock(), gve_ptp_init() is called before allocating nic_ts_report and initializing nic_ts_read_lock:

    err = gve_ptp_init(priv);
    if (err)
        return err;

    priv->nic_ts_report = dma_alloc_coherent(...);
    ...
    mutex_init(&priv->nic_ts_read_lock);

If a concurrent userspace process immediately invokes the PTP_SYS_OFFSET_EXTENDED ioctl after gve_ptp_init() registers the /dev/ptpX device, could it call gve_ptp_gettimex64() and attempt to lock the uninitialized mutex or dereference the NULL nic_ts_report pointer?

Additionally, in the error path for gve_init_clock():

    release_nic_ts_report:
        mutex_destroy(&priv->nic_ts_read_lock);
        dma_free_coherent(...);
        priv->nic_ts_report = NULL;
    release_ptp:
        gve_ptp_release(priv);
Quoted 2 lines

Could destroying the mutex and freeing the memory before gve_ptp_release() create a use-after-free window if an ioctl is currently running?

Will be fixed in the previous patch in the series.

#14 lore raw

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

The iowrite32be() inside gve_adminq_report_nic_ts() will prevent reordering by the compiler because it uses volatile, and the VM exit will prevent speculative execution by the CPU.

Quoted 183 lines · Naman Gulati
Quoted 5 lines · Jordan Rhee

We know that gve_adminq_report_nic_ts() will cause a VM exit, which will act as a full barrier. Additional barriers are not strictly necessary from a functional perspective. Can we rely on this fact or do we need explicit barriers?

I don't think that's enough. Without a barrier get_cycles can be speculatively executed before gve_adminq_report_nic_ts.

Quoted 172 lines · Naman Gulati
Quoted 169 lines · Jordan Rhee
Quoted 43 lines · Jakub Kicinski
Quoted 41 lines

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
Subject: gve: implement PTP gettimex64

This commit implements the PTP gettimex64 function to enable chrony and phc2sys to synchronize the system clock to the NIC clock. It reads the NIC timestamp along with pre and post system cycle counters to minimize the uncertainty window.

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 140b8fbce4f4..bea794541f30 100644
@@ -10,28 +10,203 @@

[ ... ]

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +7 -0
+static int gve_adminq_read_timestamp(struct gve_priv *priv,
+                                  cycles_t *pre_cycles,
+                                  cycles_t *post_cycles)
+{
+     unsigned long delay_us = 1000;
+     int retry_count = 0;
+     int err;

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+
+     lockdep_assert_held(&priv->nic_ts_read_lock);
+
+     do {
+             *pre_cycles = get_cycles();
+             err = gve_adminq_report_nic_ts(priv, priv->nic_ts_report_bus);
+
+             /* Ensure cycle counter is sampled after AdminQ cmd returns */
+             rmb();
+             *post_cycles = get_cycles();

Are execution barriers needed around get_cycles() here? rmb() orders memory accesses, but the CPU might still speculatively execute the cycle counter reads out of order with respect to the AdminQ commands.

Quoted 4 lines
Quoted 2 lines

Could this speculative reordering cause the strict bounds validation in gve_ptp_gettimex64() to fail spuriously?

I will add mb() barriers to be totally safe.

I'm not so sure that rmb() is insufficient here. In x86_64 rmb() is an lfence. lfence is used to prevent speculative execution (per the x86 barrier_nospec implementation) and rdtsc_ordered, which is called by the ktime* helpers, also prefaces rdtsc with an lfence. On ARM the get_cycles implementation adds an isb instruction before reading cntvct_el0.

Quoted 111 lines
Quoted 23 lines

[ ... ]

Quoted 7 lines

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

drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
-     return -EOPNOTSUPP;
+     struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
+     struct gve_sysclock_sample sysclock = {0};

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+     struct gve_priv *priv = ptp->priv;
+     struct system_time_snapshot snap;
+     u64 nic_ts;
+     int err;
+
+     /* Take system clock snapshot before sampling cycle counters */
+     if (sts)
+             ktime_get_snapshot(&snap);
+
+     err = gve_clock_nic_ts_read(priv, &nic_ts, &sysclock);

Could the system time snapshot become stale here?

Quoted 6 lines

If priv->nic_ts_read_lock is contended, or if gve_adminq_read_timestamp() retries and sleeps, the snapshot might be taken significantly before the actual hardware read.

Would it be more accurate to take the snapshot immediately before reading the hardware, inside the mutex?

Ack, will fix.

Quoted 17 lines
Quoted 6 lines
drivers/net/ethernet/google/gve/gve_ptp.c +5 -0
+     if (err)
+             return err;
+
+     if (sts) {
+             /* Reject samples with out of order system clock values */

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+             if (!(sysclock.host_pre_cycles <= sysclock.nic_pre_cycles &&
+                   sysclock.nic_pre_cycles  <= sysclock.nic_post_cycles &&
+                   sysclock.nic_post_cycles <= sysclock.host_post_cycles)) {
+                     dev_err_ratelimited(&priv->pdev->dev,
+                                         "AdminQ system clock cycle counts out of order. Expecting %llu <= %llu <= %llu <= %llu\n",
+                                         (u64)sysclock.host_pre_cycles,
+                                         sysclock.nic_pre_cycles,
+                                         sysclock.nic_post_cycles,
+                                         (u64)sysclock.host_post_cycles);
+                     return -EBADMSG;
Quoted 3 lines

How does this behave on architectures where get_cycles() is not implemented and returns 0, or with older firmware that leaves nic_pre_cycles and nic_post_cycles as 0?

Firmware is not allowed to return 0. 0 should trigger the check.

Quoted 4 lines

It looks like the bounds check would unconditionally fail and return -EBADMSG. Since userspace tools like chrony usually expect -EOPNOTSUPP for unsupported extended ioctls to fall back to basic PTP ioctls, will returning -EBADMSG cause a hard failure for clock synchronization?

Will fix. GVE is only supported on x86_64 and arm64, and will fail on other architectures with -EOPNOTSUPP due to the check in gve_cycles_to_clock_fn(). However, if an architecture returns get_cycles() as 0, it will fail here first with -EBADMSG. I will add an explicit check for x86 || arm64 earlier in this function.

Quoted 41 lines

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 313

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -1
@@ -132,7 +307,7 @@ int gve_init_clock(struct gve_priv *priv)
              goto release_ptp;
      }
      mutex_init(&priv->nic_ts_read_lock);
-     err = gve_clock_nic_ts_read(priv, &nic_raw);
+     err = gve_clock_nic_ts_read(priv, &nic_raw, NULL);
      if (err) {
              dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
              goto release_nic_ts_report;

Is there a race condition exposing the PTP device to userspace before its resources are fully initialized?

Looking at gve_init_clock(), gve_ptp_init() is called before allocating nic_ts_report and initializing nic_ts_read_lock:

    err = gve_ptp_init(priv);
    if (err)
        return err;

    priv->nic_ts_report = dma_alloc_coherent(...);
    ...
    mutex_init(&priv->nic_ts_read_lock);

If a concurrent userspace process immediately invokes the PTP_SYS_OFFSET_EXTENDED ioctl after gve_ptp_init() registers the /dev/ptpX device, could it call gve_ptp_gettimex64() and attempt to lock the uninitialized mutex or dereference the NULL nic_ts_report pointer?

Additionally, in the error path for gve_init_clock():

    release_nic_ts_report:
        mutex_destroy(&priv->nic_ts_read_lock);
        dma_free_coherent(...);
        priv->nic_ts_report = NULL;
    release_ptp:
        gve_ptp_release(priv);
Quoted 2 lines

Could destroying the mutex and freeing the memory before gve_ptp_release() create a use-after-free window if an ioctl is currently running?

Will be fixed in the previous patch in the series.

#15 lore raw

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

Quoted 4 lines · Jordan Rhee

The iowrite32be() inside gve_adminq_report_nic_ts() will prevent reordering by the compiler because it uses volatile, and the VM exit will prevent speculative execution by the CPU.

After some offline discussion with Naman we agree it's functionally correct without
a barrier. However, since it's not explicitly part of the contract of gve_adminq_issue_cmd() that
it causes a VM exit, it would be best to use an rmb() to prevent the 2nd get_cycles()
from being speculatively executed before gve_adminq_issue_cmd(). This would prevent a subtle bug if gve_adminq_issue_cmd() were to change, and the performance hit of the barrier is negligible compared to the VM exit.

Quoted 185 lines · Naman Gulati
Quoted 183 lines · Jordan Rhee
Quoted 5 lines

We know that gve_adminq_report_nic_ts() will cause a VM exit, which will act as a full barrier. Additional barriers are not strictly necessary from a functional perspective. Can we rely on this fact or do we need explicit barriers?

I don't think that's enough. Without a barrier get_cycles can be speculatively executed before gve_adminq_report_nic_ts.

Quoted 172 lines · Naman Gulati
Quoted 169 lines · Jordan Rhee
Quoted 43 lines · Jakub Kicinski
Quoted 41 lines

This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
Subject: gve: implement PTP gettimex64

This commit implements the PTP gettimex64 function to enable chrony and phc2sys to synchronize the system clock to the NIC clock. It reads the NIC timestamp along with pre and post system cycle counters to minimize the uncertainty window.

Quoted 5 lines
drivers/net/ethernet/google/gve/gve_ptp.c +0 -0
index 140b8fbce4f4..bea794541f30 100644
@@ -10,28 +10,203 @@

[ ... ]

Quoted 7 lines
drivers/net/ethernet/google/gve/gve_ptp.c +7 -0
+static int gve_adminq_read_timestamp(struct gve_priv *priv,
+                                  cycles_t *pre_cycles,
+                                  cycles_t *post_cycles)
+{
+     unsigned long delay_us = 1000;
+     int retry_count = 0;
+     int err;

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+
+     lockdep_assert_held(&priv->nic_ts_read_lock);
+
+     do {
+             *pre_cycles = get_cycles();
+             err = gve_adminq_report_nic_ts(priv, priv->nic_ts_report_bus);
+
+             /* Ensure cycle counter is sampled after AdminQ cmd returns */
+             rmb();
+             *post_cycles = get_cycles();

Are execution barriers needed around get_cycles() here? rmb() orders memory accesses, but the CPU might still speculatively execute the cycle counter reads out of order with respect to the AdminQ commands.

Quoted 4 lines
Quoted 2 lines

Could this speculative reordering cause the strict bounds validation in gve_ptp_gettimex64() to fail spuriously?

I will add mb() barriers to be totally safe.

I'm not so sure that rmb() is insufficient here. In x86_64 rmb() is an lfence. lfence is used to prevent speculative execution (per the x86 barrier_nospec implementation) and rdtsc_ordered, which is called by the ktime* helpers, also prefaces rdtsc with an lfence. On ARM the get_cycles implementation adds an isb instruction before reading cntvct_el0.

Quoted 111 lines
Quoted 23 lines

[ ... ]

Quoted 7 lines

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

drivers/net/ethernet/google/gve/gve_ptp.c +2 -1
-     return -EOPNOTSUPP;
+     struct gve_ptp *ptp = container_of(info, struct gve_ptp, info);
+     struct gve_sysclock_sample sysclock = {0};

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+     struct gve_priv *priv = ptp->priv;
+     struct system_time_snapshot snap;
+     u64 nic_ts;
+     int err;
+
+     /* Take system clock snapshot before sampling cycle counters */
+     if (sts)
+             ktime_get_snapshot(&snap);
+
+     err = gve_clock_nic_ts_read(priv, &nic_ts, &sysclock);

Could the system time snapshot become stale here?

Quoted 6 lines

If priv->nic_ts_read_lock is contended, or if gve_adminq_read_timestamp() retries and sleeps, the snapshot might be taken significantly before the actual hardware read.

Would it be more accurate to take the snapshot immediately before reading the hardware, inside the mutex?

Ack, will fix.

Quoted 17 lines
Quoted 6 lines
drivers/net/ethernet/google/gve/gve_ptp.c +5 -0
+     if (err)
+             return err;
+
+     if (sts) {
+             /* Reject samples with out of order system clock values */

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

Quoted 10 lines
drivers/net/ethernet/google/gve/gve_ptp.c +10 -0
+             if (!(sysclock.host_pre_cycles <= sysclock.nic_pre_cycles &&
+                   sysclock.nic_pre_cycles  <= sysclock.nic_post_cycles &&
+                   sysclock.nic_post_cycles <= sysclock.host_post_cycles)) {
+                     dev_err_ratelimited(&priv->pdev->dev,
+                                         "AdminQ system clock cycle counts out of order. Expecting %llu <= %llu <= %llu <= %llu\n",
+                                         (u64)sysclock.host_pre_cycles,
+                                         sysclock.nic_pre_cycles,
+                                         sysclock.nic_post_cycles,
+                                         (u64)sysclock.host_post_cycles);
+                     return -EBADMSG;
Quoted 3 lines

How does this behave on architectures where get_cycles() is not implemented and returns 0, or with older firmware that leaves nic_pre_cycles and nic_post_cycles as 0?

Firmware is not allowed to return 0. 0 should trigger the check.

Quoted 4 lines

It looks like the bounds check would unconditionally fail and return -EBADMSG. Since userspace tools like chrony usually expect -EOPNOTSUPP for unsupported extended ioctls to fall back to basic PTP ioctls, will returning -EBADMSG cause a hard failure for clock synchronization?

Will fix. GVE is only supported on x86_64 and arm64, and will fail on other architectures with -EOPNOTSUPP due to the check in gve_cycles_to_clock_fn(). However, if an architecture returns get_cycles() as 0, it will fail here first with -EBADMSG. I will add an explicit check for x86 || arm64 earlier in this function.

Quoted 41 lines

[ ... ]

drivers/net/ethernet/google/gve/gve_ptp.c int gve_init_clock(struct gve_priv *priv) · line 313

Quoted 9 lines
drivers/net/ethernet/google/gve/gve_ptp.c +1 -1
@@ -132,7 +307,7 @@ int gve_init_clock(struct gve_priv *priv)
              goto release_ptp;
      }
      mutex_init(&priv->nic_ts_read_lock);
-     err = gve_clock_nic_ts_read(priv, &nic_raw);
+     err = gve_clock_nic_ts_read(priv, &nic_raw, NULL);
      if (err) {
              dev_err(&priv->pdev->dev, "failed to read NIC clock %d\n", err);
              goto release_nic_ts_report;

Is there a race condition exposing the PTP device to userspace before its resources are fully initialized?

Looking at gve_init_clock(), gve_ptp_init() is called before allocating nic_ts_report and initializing nic_ts_read_lock:

    err = gve_ptp_init(priv);
    if (err)
        return err;

    priv->nic_ts_report = dma_alloc_coherent(...);
    ...
    mutex_init(&priv->nic_ts_read_lock);

If a concurrent userspace process immediately invokes the PTP_SYS_OFFSET_EXTENDED ioctl after gve_ptp_init() registers the /dev/ptpX device, could it call gve_ptp_gettimex64() and attempt to lock the uninitialized mutex or dereference the NULL nic_ts_report pointer?

Additionally, in the error path for gve_init_clock():

    release_nic_ts_report:
        mutex_destroy(&priv->nic_ts_read_lock);
        dma_free_coherent(...);
        priv->nic_ts_report = NULL;
    release_ptp:
        gve_ptp_release(priv);
Quoted 2 lines

Could destroying the mutex and freeing the memory before gve_ptp_release() create a use-after-free window if an ioctl is currently running?

Will be fixed in the previous patch in the series.