Skip to contentSkip to conversation

x86: further time/APIC improvements (and more)

PATCH In review Jan Beulich 3 participants 13 messages Mar 31, 2022 – Apr 5, 2022

lore
Share & tools
lore
#0 lore raw

v4 cover x86: further time/APIC improvements (and more)

... plus some tidying (or so I hope).

While perhaps seemingly unrelated, the 3rd patch is actually a result of my (successlessly) hunting for PASTE() or alike, as now being introduced by patch 2.

1: APIC: calibrate against platform timer when possible 2: APIC: make connections between seemingly arbitrary numbers 3: include: move STR() and IS_ALIGNED()
4: time: use fake read_tsc()

Jan

#1 lore raw

PATCH v4 1/4 x86/APIC: calibrate against platform timer when possible

Use the original calibration against PIT only when the platform timer is PIT. This implicitly excludes the "xen_guest" case from using the PIT logic (init_pit() fails there, and as of 5e73b2594c54 ["x86/time: minor adjustments to init_pit()"] using_pit also isn't being set too early anymore), so the respective hack there can be dropped at the same time. This also reduces calibration time from 100ms to 50ms, albeit this step is being skipped as of 0731a56c7c72 ("x86/APIC: no need for timer calibration when using TDT") anyway.

While re-indenting the PIT logic in calibrate_APIC_clock(), besides adjusting style also switch around the 2nd TSC/TMCCT read pair, to match the order of the 1st one, yielding more consistent deltas.

---
Open-coding apic_read() in apic_tmcct_read() isn't overly nice, but I wanted to avoid x2apic_enabled being evaluated twice in close succession. And I also wouldn't want to have the barrier there even for the (uncached) MMIO read.

Unlike the CPU frequencies enumerated in CPUID leaf 0x16 (which aren't precise), using CPUID[0x15].ECX - if populated - may be an option to skip calibration altogether. Aiui the value there is precise, but using the systems I have easy access to I cannot verify this: In the sample of three I have, none have ECX populated.

I wonder whether the secondary CPU freq measurement (used for display purposes only) wouldn't better be dropped at this occasion.
---
v3: Move (and rename) read_tmcct() as previously suggested.
v2: New.

xen/arch/x86/apic.c +35 -37
@@ -1183,18 +1183,20 @@ static void __init check_deadline_errata
            "please update microcode to version %#x (or later)\n", rev);
 }
 
-static void __init wait_tick_pvh(void)
+uint32_t __init apic_tmcct_read(void)
 {
-    u64 lapse_ns = 1000000000ULL / HZ;
-    s_time_t start, curr_time;
-
-    start = NOW();
+    if ( x2apic_enabled )
+    {
+        /*
+         * Have a barrier here just like in rdtsc_ordered() as it's
+         * unclear whether this non-serializing RDMSR also can be
+         * executed speculatively (like RDTSC can).
+         */
+        alternative("lfence", "mfence", X86_FEATURE_MFENCE_RDTSC);
+        return apic_rdmsr(APIC_TMCCT);
+    }
 
-    /* Won't wrap around */
-    do {
-        cpu_relax();
-        curr_time = NOW();
-    } while ( curr_time - start < lapse_ns );
+    return apic_mem_read(APIC_TMCCT);
 }
 
 /*
@@ -1212,9 +1214,6 @@ static void __init wait_tick_pvh(void)
 
 static void __init calibrate_APIC_clock(void)
 {
-    unsigned long long t1, t2;
-    unsigned long tt1, tt2;
-    unsigned int i;
     unsigned long bus_freq; /* KAF: pointer-size avoids compile warns. */
     unsigned int bus_cycle; /* length of one bus cycle in pico-seconds */
 #define LOOPS_FRAC 10U      /* measure for one tenth of a second */
@@ -1227,39 +1226,38 @@ static void __init calibrate_APIC_clock(
      */
     __setup_APIC_LVTT(0xffffffff);
 
-    if ( !xen_guest )
+    bus_freq = calibrate_apic_timer();
+    if ( !bus_freq )
+    {
+        unsigned int i, tt1, tt2;
+        unsigned long t1, t2;
+
+        ASSERT(!xen_guest);
+
         /*
-         * The timer chip counts down to zero. Let's wait
-         * for a wraparound to start exact measurement:
-         * (the current tick might have been already half done)
+         * The timer chip counts down to zero. Let's wait for a wraparound to
+         * start exact measurement (the current tick might have been already
+         * half done):
          */
         wait_8254_wraparound();
-    else
-        wait_tick_pvh();
 
-    /*
-     * We wrapped around just now. Let's start:
-     */
-    t1 = rdtsc_ordered();
-    tt1 = apic_read(APIC_TMCCT);
+        /* We wrapped around just now. Let's start: */
+        t1 = rdtsc_ordered();
+        tt1 = apic_read(APIC_TMCCT);
 
-    /*
-     * Let's wait HZ / LOOPS_FRAC ticks:
-     */
-    for (i = 0; i < HZ / LOOPS_FRAC; i++)
-        if ( !xen_guest )
+        /* Let's wait HZ / LOOPS_FRAC ticks: */
+        for ( i = 0; i < HZ / LOOPS_FRAC; ++i )
             wait_8254_wraparound();
-        else
-            wait_tick_pvh();
 
-    tt2 = apic_read(APIC_TMCCT);
-    t2 = rdtsc_ordered();
+        t2 = rdtsc_ordered();
+        tt2 = apic_read(APIC_TMCCT);
 
-    bus_freq = (tt1 - tt2) * APIC_DIVISOR * LOOPS_FRAC;
+        bus_freq = (tt1 - tt2) * APIC_DIVISOR * LOOPS_FRAC;
 
-    apic_printk(APIC_VERBOSE, "..... CPU clock speed is %lu.%04lu MHz.\n",
-                ((unsigned long)(t2 - t1) * LOOPS_FRAC) / 1000000,
-                (((unsigned long)(t2 - t1) * LOOPS_FRAC) / 100) % 10000);
+        apic_printk(APIC_VERBOSE, "..... CPU clock speed is %lu.%04lu MHz.\n",
+                    ((t2 - t1) * LOOPS_FRAC) / 1000000,
+                    (((t2 - t1) * LOOPS_FRAC) / 100) % 10000);
+    }
 
     apic_printk(APIC_VERBOSE, "..... host bus clock speed is %ld.%04ld MHz.\n",
                 bus_freq / 1000000, (bus_freq / 100) % 10000);
xen/arch/x86/include/asm/apic.h +3 -0
@@ -192,6 +192,9 @@ extern void record_boot_APIC_mode(void);
 extern enum apic_mode current_local_apic_mode(void);
 extern void check_for_unexpected_msi(unsigned int vector);
 
+uint64_t calibrate_apic_timer(void);
+uint32_t apic_tmcct_read(void);
+
 extern void check_nmi_watchdog(void);
 
 extern unsigned int nmi_watchdog;
xen/arch/x86/time.c +62 -0

74 lines not on this page · raw message

#2 lore raw

Re: [PATCH v4 1/4] x86/APIC: calibrate against platform timer when possible

Quoted 20 lines · Jan Beulich

Use the original calibration against PIT only when the platform timer is PIT. This implicitly excludes the "xen_guest" case from using the PIT logic (init_pit() fails there, and as of 5e73b2594c54 ["x86/time: minor adjustments to init_pit()"] using_pit also isn't being set too early anymore), so the respective hack there can be dropped at the same time. This also reduces calibration time from 100ms to 50ms, albeit this step is being skipped as of 0731a56c7c72 ("x86/APIC: no need for timer calibration when using TDT") anyway.

While re-indenting the PIT logic in calibrate_APIC_clock(), besides adjusting style also switch around the 2nd TSC/TMCCT read pair, to match the order of the 1st one, yielding more consistent deltas.

---
Open-coding apic_read() in apic_tmcct_read() isn't overly nice, but I wanted to avoid x2apic_enabled being evaluated twice in close succession. And I also wouldn't want to have the barrier there even for the (uncached) MMIO read.

Quoted 8 lines

Unlike the CPU frequencies enumerated in CPUID leaf 0x16 (which aren't precise), using CPUID[0x15].ECX - if populated - may be an option to skip calibration altogether. Aiui the value there is precise, but using the systems I have easy access to I cannot verify this: In the sample of three I have, none have ECX populated.

I wonder whether the secondary CPU freq measurement (used for display purposes only) wouldn't better be dropped at this occasion.

I don't have a strong opinion re those informative messages.

Quoted 61 lines
xen/arch/x86/include/asm/apic.h +3 -0
@@ -192,6 +192,9 @@ extern void record_boot_APIC_mode(void);
 extern enum apic_mode current_local_apic_mode(void);
 extern void check_for_unexpected_msi(unsigned int vector);
 
+uint64_t calibrate_apic_timer(void);
+uint32_t apic_tmcct_read(void);
+
 extern void check_nmi_watchdog(void);
 
 extern unsigned int nmi_watchdog;
xen/arch/x86/time.c +36 -0
@@ -26,6 +26,7 @@
 #include <xen/symbols.h>
 #include <xen/keyhandler.h>
 #include <xen/guest_access.h>
+#include <asm/apic.h>
 #include <asm/io.h>
 #include <asm/iocap.h>
 #include <asm/msr.h>
@@ -1018,6 +1019,67 @@ static u64 __init init_platform_timer(vo
     return rc;
 }
 
+static uint64_t __init read_pt_and_tmcct(uint32_t *tmcct)
+{
+    uint32_t tmcct_prev = *tmcct = apic_tmcct_read(), tmcct_min = ~0;
+    uint64_t best = best;
+    unsigned int i;
+
+    for ( i = 0; ; ++i )
+    {
+        uint64_t pt = plt_src.read_counter();
+        uint32_t tmcct_cur = apic_tmcct_read();
+        uint32_t tmcct_delta = tmcct_prev - tmcct_cur;
+
+        if ( tmcct_delta < tmcct_min )
+        {
+            tmcct_min = tmcct_delta;
+            *tmcct = tmcct_cur;
+            best = pt;
+        }
+        else if ( i > 2 )
+            break;
+
+        tmcct_prev = tmcct_cur;
+    }
+
+    return best;
+}
+
+uint64_t __init calibrate_apic_timer(void)
+{
+    uint32_t start, end;
+    uint64_t count = read_pt_and_tmcct(&start), elapsed;
+    uint64_t target = CALIBRATE_VALUE(plt_src.frequency), actual;
+    uint64_t mask = (uint64_t)~0 >> (64 - plt_src.counter_bits);
+
+    /*

xen/arch/x86/time.c static u64 __init init_platform_timer(vo · line 1066

Quoted 10 lines
xen/arch/x86/time.c +10 -0
+     * PIT cannot be used here as it requires the timer interrupt to maintain
+     * its 32-bit software counter, yet here we run with IRQs disabled.
+     */
+    if ( using_pit )
+        return 0;
+
+    while ( ((plt_src.read_counter() - count) & mask) < target )
+        continue;
+
+    actual = read_pt_and_tmcct(&end) - count;

Don't you need to apply the pt mask here?

xen/arch/x86/time.c static u64 __init init_platform_timer(vo · line 1071

Quoted 5 lines
xen/arch/x86/time.c +5 -0
+    elapsed = start - end;
+
+    if ( likely(actual > target) )
+    {
+        /* See the comment in calibrate_tsc(). */

I would maybe add that the counters used here might have > 32 bits, and hence we need to trim the values for muldiv64 to scale properly.

Thanks, Roger.

#3 lore raw

Re: [PATCH v4 1/4] x86/APIC: calibrate against platform timer when possible

Quoted 13 lines · Roger Pau Monné
Quoted 12 lines · Jan Beulich
xen/arch/x86/time.c +12 -0
+uint64_t __init calibrate_apic_timer(void)
+{
+    uint32_t start, end;
+    uint64_t count = read_pt_and_tmcct(&start), elapsed;
+    uint64_t target = CALIBRATE_VALUE(plt_src.frequency), actual;
+    uint64_t mask = (uint64_t)~0 >> (64 - plt_src.counter_bits);
+
+    /*
+     * PIT cannot be used here as it requires the timer interrupt to maintain
+     * its 32-bit software counter, yet here we run with IRQs disabled.
+     */
+    if ( using_pit )
Quoted 8 lines

xen/arch/x86/time.c static u64 __init init_platform_timer(vo · line 1066

Quoted 6 lines
xen/arch/x86/time.c +6 -0
+        return 0;
+
+    while ( ((plt_src.read_counter() - count) & mask) < target )
+        continue;
+
+    actual = read_pt_and_tmcct(&end) - count;

Don't you need to apply the pt mask here?

Oh, yes, of course. I guess I did clone an earlier mistake from calibrate_tsc().

Quoted 8 lines

xen/arch/x86/time.c static u64 __init init_platform_timer(vo · line 1071

Quoted 5 lines
xen/arch/x86/time.c +5 -0
+    elapsed = start - end;
+
+    if ( likely(actual > target) )
+    {
+        /* See the comment in calibrate_tsc(). */

I would maybe add that the counters used here might have > 32 bits, and hence we need to trim the values for muldiv64 to scale properly.

Sure - I've added "But first scale down values to actually fit muldiv64()'s input range."

Jan

Reviewed-by
#4 lore raw

Re: [PATCH v4 1/4] x86/APIC: calibrate against platform timer when possible

Quoted 32 lines · Jan Beulich
Quoted 13 lines · Roger Pau Monné
Quoted 12 lines · Jan Beulich
xen/arch/x86/time.c +12 -0
+uint64_t __init calibrate_apic_timer(void)
+{
+    uint32_t start, end;
+    uint64_t count = read_pt_and_tmcct(&start), elapsed;
+    uint64_t target = CALIBRATE_VALUE(plt_src.frequency), actual;
+    uint64_t mask = (uint64_t)~0 >> (64 - plt_src.counter_bits);
+
+    /*
+     * PIT cannot be used here as it requires the timer interrupt to maintain
+     * its 32-bit software counter, yet here we run with IRQs disabled.
+     */
+    if ( using_pit )
Quoted 8 lines

xen/arch/x86/time.c static u64 __init init_platform_timer(vo · line 1066

Quoted 6 lines
xen/arch/x86/time.c +6 -0
+        return 0;
+
+    while ( ((plt_src.read_counter() - count) & mask) < target )
+        continue;
+
+    actual = read_pt_and_tmcct(&end) - count;

Don't you need to apply the pt mask here?

Oh, yes, of course. I guess I did clone an earlier mistake from calibrate_tsc().

Quoted 6 lines
Quoted 5 lines
xen/arch/x86/time.c +5 -0
+    elapsed = start - end;
+
+    if ( likely(actual > target) )
+    {
+        /* See the comment in calibrate_tsc(). */
Quoted 5 lines
Quoted 2 lines

I would maybe add that the counters used here might have > 32 bits, and hence we need to trim the values for muldiv64 to scale properly.

Sure - I've added "But first scale down values to actually fit muldiv64()'s input range."

With those taken care of:

Thanks, Roger.

#5 lore raw

PATCH v4 2/4 x86/APIC: make connections between seemingly arbitrary numbers

In reply to Jan Beulich

Making adjustments to arbitrarily chosen values shouldn't require auditing the code for possible derived numbers - such a change should be doable in a single place, having an effect on all code depending on that choice.

For one make the TDCR write actually use APIC_DIVISOR. With the necessary mask constant introduced, also use that in vLAPIC code. While introducing the constant, drop APIC_TDR_DIV_TMBASE: The bit has been undefined in halfway recent SDM and PM versions.

And then introduce a constant tying together the scale used when converting nanoseconds to bus clocks.

No functional change intended.

---
v3: Introduce and use PASTE() instead of (ab)using _AC().
v2: New.

xen/arch/x86/apic.c +8 -5
@@ -1078,8 +1078,8 @@ static void __setup_APIC_LVTT(unsigned i
     lvtt_value = APIC_TIMER_MODE_ONESHOT | LOCAL_TIMER_VECTOR;
     apic_write(APIC_LVTT, lvtt_value);
 
-    tmp_value = apic_read(APIC_TDCR);
-    apic_write(APIC_TDCR, tmp_value | APIC_TDR_DIV_1);
+    tmp_value = apic_read(APIC_TDCR) & ~APIC_TDR_DIV_MASK;
+    apic_write(APIC_TDCR, tmp_value | PASTE(APIC_TDR_DIV_, APIC_DIVISOR));
 
     apic_write(APIC_TMICT, clocks / APIC_DIVISOR);
 }
@@ -1212,6 +1212,8 @@ uint32_t __init apic_tmcct_read(void)
  * APIC irq that way.
  */
 
+#define BUS_SCALE_SHIFT 18
+
 static void __init calibrate_APIC_clock(void)
 {
     unsigned long bus_freq; /* KAF: pointer-size avoids compile warns. */
@@ -1265,8 +1267,8 @@ static void __init calibrate_APIC_clock(
     /* set up multipliers for accurate timer code */
     bus_cycle  = 1000000000000UL / bus_freq; /* in pico seconds */
     bus_cycle += (1000000000000UL % bus_freq) * 2 > bus_freq;
-    bus_scale  = (1000*262144)/bus_cycle;
-    bus_scale += ((1000 * 262144) % bus_cycle) * 2 > bus_cycle;
+    bus_scale  = (1000 << BUS_SCALE_SHIFT) / bus_cycle;
+    bus_scale += ((1000 << BUS_SCALE_SHIFT) % bus_cycle) * 2 > bus_cycle;
 
     apic_printk(APIC_VERBOSE, "..... bus_scale = %#x\n", bus_scale);
     /* reset APIC to zero timeout value */
@@ -1353,7 +1355,8 @@ int reprogram_timer(s_time_t timeout)
     }
 
     if ( timeout && ((expire = timeout - NOW()) > 0) )
-        apic_tmict = min_t(u64, (bus_scale * expire) >> 18, UINT_MAX);
+        apic_tmict = min_t(uint64_t, (bus_scale * expire) >> BUS_SCALE_SHIFT,
+                           UINT32_MAX);
 
     apic_write(APIC_TMICT, (unsigned long)apic_tmict);
 
xen/arch/x86/hvm/vlapic.c +3 -3
@@ -580,7 +580,7 @@ static uint32_t vlapic_get_tmcct(const s
 static void vlapic_set_tdcr(struct vlapic *vlapic, unsigned int val)
 {
     /* Only bits 0, 1 and 3 are settable; others are MBZ. */
-    val &= 0xb;
+    val &= APIC_TDR_DIV_MASK;
     vlapic_set_reg(vlapic, APIC_TDCR, val);
 
     /* Update the demangled hw.timer_divisor. */
@@ -888,7 +888,7 @@ void vlapic_reg_write(struct vcpu *v, un
     {
         uint32_t current_divisor = vlapic->hw.timer_divisor;
 
-        vlapic_set_tdcr(vlapic, val & 0xb);
+        vlapic_set_tdcr(vlapic, val);
 
         vlapic_update_timer(vlapic, vlapic_get_reg(vlapic, APIC_LVTT), false,
                             current_divisor);
@@ -1020,7 +1020,7 @@ int guest_wrmsr_x2apic(struct vcpu *v, u
         break;
 
     case APIC_TDCR:
-        if ( msr_content & ~APIC_TDR_DIV_1 )
+        if ( msr_content & ~APIC_TDR_DIV_MASK )
             return X86EMUL_EXCEPTION;
         break;
 
xen/arch/x86/include/asm/apicdef.h +1 -1
@@ -106,7 +106,7 @@
 #define		APIC_TMICT	0x380
 #define		APIC_TMCCT	0x390
 #define		APIC_TDCR	0x3E0
-#define			APIC_TDR_DIV_TMBASE	(1<<2)
+#define			APIC_TDR_DIV_MASK	0xB
 #define			APIC_TDR_DIV_1		0xB
 #define			APIC_TDR_DIV_2		0x0
 #define			APIC_TDR_DIV_4		0x1
xen/include/xen/lib.h +4 -0
@@ -13,6 +13,10 @@
 #define count_args(args...) \
     count_args_(., ## args, 8, 7, 6, 5, 4, 3, 2, 1, 0)
 
+/* Indirect macros required for expanded argument pasting. */
+#define PASTE_(a, b) a ## b
+#define PASTE(a, b) PASTE_(a, b)
+
 #ifndef __ASSEMBLY__
 
 #include <xen/inttypes.h>
#6 lore raw

PATCH v4 3/4 include: move STR() and IS_ALIGNED()

In reply to Jan Beulich

lib.h is imo a better fit for them than config.h.

---
v4: New.
---
Originally I thought I'd also move KB() etc, but they're used in places where yet further adjustments (adding of #include) would be necessary.

xen/arch/arm/xen.lds.S +1 -0
@@ -3,6 +3,7 @@
 /* Modified for ARM Xen by Ian Campbell */
 
 #include <xen/cache.h>
+#include <xen/lib.h>
 #include <asm/page.h>
 #undef ENTRY
 #undef ALIGN
xen/arch/x86/xen.lds.S +1 -0
@@ -2,6 +2,7 @@
 /* Modified for i386/x86-64 Xen by Keir Fraser */
 
 #include <xen/cache.h>
+#include <xen/lib.h>
 #include <asm/page.h>
 #undef ENTRY
 #undef ALIGN
xen/include/xen/config.h +0 -5
@@ -82,11 +82,6 @@
 #define MB(_mb)     (_AC(_mb, ULL) << 20)
 #define GB(_gb)     (_AC(_gb, ULL) << 30)
 
-#define IS_ALIGNED(val, align) (((val) & ((align) - 1)) == 0)
-
-#define __STR(...) #__VA_ARGS__
-#define STR(...) __STR(__VA_ARGS__)
-
 /* allow existing code to work with Kconfig variable */
 #define NR_CPUS CONFIG_NR_CPUS
 
xen/include/xen/lib.h +5 -0
@@ -3,6 +3,8 @@
 
 #define ROUNDUP(x, a) (((x) + (a) - 1) & ~((a) - 1))
 
+#define IS_ALIGNED(val, align) (!((val) & ((align) - 1)))
+
 #define DIV_ROUND(n, d) (((n) + (d) / 2) / (d))
 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
 
@@ -17,6 +19,9 @@
 #define PASTE_(a, b) a ## b
 #define PASTE(a, b) PASTE_(a, b)
 
+#define __STR(...) #__VA_ARGS__
+#define STR(...) __STR(__VA_ARGS__)
+
 #ifndef __ASSEMBLY__
 
 #include <xen/inttypes.h>
Reviewed-by on v4 3/4
#7 lore raw

Re: [PATCH v4 3/4] include: move STR() and IS_ALIGNED()

Hi Jan,

Quoted 3 lines · Jan Beulich

lib.h is imo a better fit for them than config.h.

Cheers,

Quoted 62 lines

---
v4: New.
---
Originally I thought I'd also move KB() etc, but they're used in places where yet further adjustments (adding of #include) would be necessary.

xen/arch/arm/xen.lds.S +1 -0
@@ -3,6 +3,7 @@
  /* Modified for ARM Xen by Ian Campbell */
 
  #include <xen/cache.h>
+#include <xen/lib.h>
  #include <asm/page.h>
  #undef ENTRY
  #undef ALIGN
xen/arch/x86/xen.lds.S +1 -0
@@ -2,6 +2,7 @@
  /* Modified for i386/x86-64 Xen by Keir Fraser */
 
  #include <xen/cache.h>
+#include <xen/lib.h>
  #include <asm/page.h>
  #undef ENTRY
  #undef ALIGN
xen/include/xen/config.h +0 -5
@@ -82,11 +82,6 @@
  #define MB(_mb)     (_AC(_mb, ULL) << 20)
  #define GB(_gb)     (_AC(_gb, ULL) << 30)
 
-#define IS_ALIGNED(val, align) (((val) & ((align) - 1)) == 0)
-
-#define __STR(...) #__VA_ARGS__
-#define STR(...) __STR(__VA_ARGS__)
-
  /* allow existing code to work with Kconfig variable */
  #define NR_CPUS CONFIG_NR_CPUS
 
xen/include/xen/lib.h +5 -0
@@ -3,6 +3,8 @@
 
  #define ROUNDUP(x, a) (((x) + (a) - 1) & ~((a) - 1))
 
+#define IS_ALIGNED(val, align) (!((val) & ((align) - 1)))
+
  #define DIV_ROUND(n, d) (((n) + (d) / 2) / (d))
  #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
 
@@ -17,6 +19,9 @@
  #define PASTE_(a, b) a ## b
  #define PASTE(a, b) PASTE_(a, b)
 
+#define __STR(...) #__VA_ARGS__
+#define STR(...) __STR(__VA_ARGS__)
+
  #ifndef __ASSEMBLY__
 
  #include <xen/inttypes.h>
Signature · 1 line
Julien Grall
#9 lore raw

PATCH v4 4/4 x86/time: use fake read_tsc()

In reply to Jan Beulich

Go a step further than bed9ae54df44 ("x86/time: switch platform timer hooks to altcall") did and eliminate the "real" read_tsc() altogether:
It's not used except in pointer comparisons, and hence it looks overall more safe to simply poison plt_tsc's read_counter hook.

---
I wasn't really sure whether it would be better to use simply void * for the type of the expression, resulting in an undesirable data -> function pointer conversion, but making it impossible to mistakenly try and call the (fake) function directly.
---
v2: Comment wording.

xen/arch/x86/time.c +6 -4
@@ -607,10 +607,12 @@ static s64 __init cf_check init_tsc(stru
     return ret;
 }
 
-static uint64_t __init cf_check read_tsc(void)
-{
-    return rdtsc_ordered();
-}
+/*
+ * plt_tsc's read_counter hook is not (and should not be) invoked via the
+ * struct field. To avoid carrying an unused, indirectly reachable function,
+ * poison the field with an easily identifiable non-canonical pointer.
+ */
+#define read_tsc ((uint64_t(*)(void))0x75C75C75C75C75C0ul)
 
 static struct platform_timesource __initdata_cf_clobber plt_tsc =
 {
#10 lore raw

Re: [PATCH v4 4/4] x86/time: use fake read_tsc()

Quoted 11 lines · Jan Beulich

Go a step further than bed9ae54df44 ("x86/time: switch platform timer hooks to altcall") did and eliminate the "real" read_tsc() altogether:
It's not used except in pointer comparisons, and hence it looks overall more safe to simply poison plt_tsc's read_counter hook.

---
I wasn't really sure whether it would be better to use simply void * for the type of the expression, resulting in an undesirable data -> function pointer conversion, but making it impossible to mistakenly try and call the (fake) function directly.

I think it's slightly better to avoid being able to call the function, hence using void * would be my preference. What's wrong with the data -> function pointer conversion for the comparisons?

Quoted 9 lines

---
v2: Comment wording.

xen/arch/x86/time.c +0 -0
@@ -607,10 +607,12 @@ static s64 __init cf_check init_tsc(stru
     return ret;
 }
 

xen/arch/x86/time.c static s64 __init cf_check init_tsc(stru · line 615

Quoted 10 lines
xen/arch/x86/time.c +6 -4
-static uint64_t __init cf_check read_tsc(void)
-{
-    return rdtsc_ordered();
-}
+/*
+ * plt_tsc's read_counter hook is not (and should not be) invoked via the
+ * struct field. To avoid carrying an unused, indirectly reachable function,
+ * poison the field with an easily identifiable non-canonical pointer.
+ */
+#define read_tsc ((uint64_t(*)(void))0x75C75C75C75C75C0ul)

Instead of naming this like a suitable function, I would rather use READ_TSC_PTR_POISON or some such.

Thanks, Roger.

#11 lore raw

Re: [PATCH v4 4/4] x86/time: use fake read_tsc()

Quoted 13 lines · Roger Pau Monné
Quoted 11 lines · Jan Beulich

Go a step further than bed9ae54df44 ("x86/time: switch platform timer hooks to altcall") did and eliminate the "real" read_tsc() altogether:
It's not used except in pointer comparisons, and hence it looks overall more safe to simply poison plt_tsc's read_counter hook.

---
I wasn't really sure whether it would be better to use simply void * for the type of the expression, resulting in an undesirable data -> function pointer conversion, but making it impossible to mistakenly try and call the (fake) function directly.

Quoted 3 lines

I think it's slightly better to avoid being able to call the function, hence using void * would be my preference. What's wrong with the data -> function pointer conversion for the comparisons?

There's no data -> function pointer conversion for the comparisons; the situation there is even less pleasant. What I referred to was actually the initializer, where there would be a data -> function pointer conversion if I used void *.

Quoted 9 lines
Quoted 9 lines

---
v2: Comment wording.

xen/arch/x86/time.c +0 -0
@@ -607,10 +607,12 @@ static s64 __init cf_check init_tsc(stru
     return ret;
 }
 
Quoted 13 lines

xen/arch/x86/time.c static s64 __init cf_check init_tsc(stru · line 615

Quoted 10 lines
xen/arch/x86/time.c +6 -4
-static uint64_t __init cf_check read_tsc(void)
-{
-    return rdtsc_ordered();
-}
+/*
+ * plt_tsc's read_counter hook is not (and should not be) invoked via the
+ * struct field. To avoid carrying an unused, indirectly reachable function,
+ * poison the field with an easily identifiable non-canonical pointer.
+ */
+#define read_tsc ((uint64_t(*)(void))0x75C75C75C75C75C0ul)

Instead of naming this like a suitable function, I would rather use READ_TSC_PTR_POISON or some such.

I'll be happy to name it something like this; the primary thing to settle on is the type to use.

Jan

Reviewed-by
#12 lore raw

Re: [PATCH v4 4/4] x86/time: use fake read_tsc()

Quoted 14 lines · Jan Beulich
Quoted 13 lines · Roger Pau Monné
Quoted 11 lines · Jan Beulich

Go a step further than bed9ae54df44 ("x86/time: switch platform timer hooks to altcall") did and eliminate the "real" read_tsc() altogether:
It's not used except in pointer comparisons, and hence it looks overall more safe to simply poison plt_tsc's read_counter hook.

---
I wasn't really sure whether it would be better to use simply void * for the type of the expression, resulting in an undesirable data -> function pointer conversion, but making it impossible to mistakenly try and call the (fake) function directly.

Quoted 8 lines
Quoted 3 lines

I think it's slightly better to avoid being able to call the function, hence using void * would be my preference. What's wrong with the data -> function pointer conversion for the comparisons?

There's no data -> function pointer conversion for the comparisons; the situation there is even less pleasant. What I referred to was actually the initializer, where there would be a data -> function pointer conversion if I used void *.

I see, there are architectures with different sizes for function and data pointers. It's also not clear all compilers will be happy with the conversion.

Quoted 23 lines
Quoted 9 lines
Quoted 9 lines

---
v2: Comment wording.

xen/arch/x86/time.c +0 -0
@@ -607,10 +607,12 @@ static s64 __init cf_check init_tsc(stru
     return ret;
 }
 
Quoted 13 lines

xen/arch/x86/time.c static s64 __init cf_check init_tsc(stru · line 615

Quoted 10 lines
xen/arch/x86/time.c +6 -4
-static uint64_t __init cf_check read_tsc(void)
-{
-    return rdtsc_ordered();
-}
+/*
+ * plt_tsc's read_counter hook is not (and should not be) invoked via the
+ * struct field. To avoid carrying an unused, indirectly reachable function,
+ * poison the field with an easily identifiable non-canonical pointer.
+ */
+#define read_tsc ((uint64_t(*)(void))0x75C75C75C75C75C0ul)

Instead of naming this like a suitable function, I would rather use READ_TSC_PTR_POISON or some such.

Quoted 2 lines

I'll be happy to name it something like this; the primary thing to settle on is the type to use.

I think it's safer to use a function pointer type like you currently have from a correctness PoV, but in order to prevent stray calls to read_tsc() I would rename to READ_TSC_PTR_POISON. This was already static, so I guess it's hard anyway for any of such direct calls to appear without us realizing.

With that:

Thanks, Roger.