From 6d36c9b1273980cb8ff511f78b5c9b126e4577da Mon Sep 17 00:00:00 2001
From: May Shao <MayShao@zhaoxin.com>
Date: Tue, 27 Sep 2022 20:44:48 +0800
Subject: [PATCH 1/1] x86: Add the virtual machine detection in init_cacheinfo

Use CPUID.01H.ECX[31] to indicate guest status.

Set the default threads=1 to use non_temporal_threshold on
vm and hosts with a single processor.

Signed-off-by: May Shao <MayShao@zhaoxin.com>
---
 sysdeps/x86/cacheinfo.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/sysdeps/x86/cacheinfo.c b/sysdeps/x86/cacheinfo.c
index 7615334e..28bcf2f6 100644
--- a/sysdeps/x86/cacheinfo.c
+++ b/sysdeps/x86/cacheinfo.c
@@ -495,7 +495,8 @@ init_cacheinfo (void)
   long int data = -1;
   long int shared = -1;
   unsigned int level;
-  unsigned int threads = 0;
+  unsigned int threads = 1;
+  unsigned int is_vm = 0;
   const struct cpu_features *cpu_features = __get_cpu_features ();
   int max_cpuid = cpu_features->max_cpuid;
 
@@ -506,6 +507,9 @@ init_cacheinfo (void)
       long int core = handle_intel (_SC_LEVEL2_CACHE_SIZE, cpu_features);
       bool inclusive_cache = true;
 
+      is_vm = ((cpu_features->cpuid[COMMON_CPUID_INDEX_1].ecx 
+	        & (1 << 31)) >> 31);
+
       /* Try L3 first.  */
       level  = 3;
       shared = handle_intel (_SC_LEVEL3_CACHE_SIZE, cpu_features);
@@ -532,7 +536,7 @@ init_cacheinfo (void)
 
       /* A value of 0 for the HTT bit indicates there is only a single
 	 logical processor.  */
-      if (HAS_CPU_FEATURE (HTT))
+      if (HAS_CPU_FEATURE (HTT) && !is_vm)
 	{
 	  /* Figure out the number of logical threads that share the
 	     highest cache level.  */
@@ -692,7 +696,7 @@ intel_bug_no_cache_info:
 	    shared /= threads;
 	}
       else
-    threads = 1;
+    	threads = 1;
 
       /* Account for non-inclusive L2 and L3 caches.  */
       if (!inclusive_cache)
-- 
2.17.1

