[LTP] [PATCH v3 1/4] lib: Add tst_bind_to_current_cpu() helper
Wei Gao
wegao@suse.com
Fri Nov 13 05:11:30 CET 2026
Add tst_bind_to_cpu() and tst_bind_to_current_cpu() to the core LTP
CPU library (include/tst_cpu.h, lib/tst_cpu.c). This allows tests to
pin the test process to a specific or current CPU, which is useful
for avoiding multi-CPU migration artifacts and per-CPU charge/counter
batching variations.
Also add a fallback definition for sched_getcpu() in include/lapi/sched.h
via getcpu() for older C libraries without sched_getcpu().
Signed-off-by: Wei Gao <wegao@suse.com>
---
include/lapi/sched.h | 10 ++++++++++
include/tst_cpu.h | 11 +++++++++++
lib/tst_cpu.c | 34 ++++++++++++++++++++++++++++++++++
3 files changed, 55 insertions(+)
diff --git a/include/lapi/sched.h b/include/lapi/sched.h
index 4fa6e7c5f..ea828664c 100644
--- a/include/lapi/sched.h
+++ b/include/lapi/sched.h
@@ -115,6 +115,16 @@ static inline int getcpu(unsigned *cpu, unsigned *node)
}
#endif
+#ifndef HAVE_SCHED_GETCPU
+static inline int sched_getcpu(void)
+{
+ unsigned int cpu;
+ int ret = getcpu(&cpu, NULL);
+
+ return ret == 0 ? (int)cpu : ret;
+}
+#endif
+
#ifndef SCHED_DEADLINE
# define SCHED_DEADLINE 6
#endif
diff --git a/include/tst_cpu.h b/include/tst_cpu.h
index 340d0f3c7..7c6089379 100644
--- a/include/tst_cpu.h
+++ b/include/tst_cpu.h
@@ -36,4 +36,15 @@ const char *tst_cpu_vendor(void);
int tst_is_virt(int virt_type);
+/**
+ * tst_bind_to_cpu() - Pin calling process to the specified CPU.
+ * @cpu: CPU index to bind to.
+ */
+void tst_bind_to_cpu(int cpu);
+
+/**
+ * tst_bind_to_current_cpu() - Pin calling process to the current CPU.
+ */
+void tst_bind_to_current_cpu(void);
+
#endif /* TST_CPU_H__ */
diff --git a/lib/tst_cpu.c b/lib/tst_cpu.c
index 241bd3347..2f0e2f8ee 100644
--- a/lib/tst_cpu.c
+++ b/lib/tst_cpu.c
@@ -22,6 +22,7 @@
#include <stdlib.h>
#include <unistd.h>
#include "test.h"
+#include "lapi/sched.h"
#include "tso_safe_macros.h"
#include "tso_safe_file_ops.h"
#include "tso_safe_stdio.h"
@@ -139,3 +140,36 @@ const char *tst_cpu_vendor(void)
return cpu_vendor;
}
+
+void tst_bind_to_cpu(int cpu)
+{
+ size_t mask_size;
+ cpu_set_t *mask;
+
+ tst_resm(TINFO, "Binding test process to CPU %d", cpu);
+
+ mask = CPU_ALLOC(cpu + 1);
+ if (!mask)
+ tst_brkm(TBROK | TERRNO, NULL, "CPU_ALLOC() failed");
+
+ mask_size = CPU_ALLOC_SIZE(cpu + 1);
+ CPU_ZERO_S(mask_size, mask);
+ CPU_SET_S(cpu, mask_size, mask);
+
+ if (sched_setaffinity(0, mask_size, mask) < 0) {
+ CPU_FREE(mask);
+ tst_brkm(TBROK | TERRNO, NULL, "sched_setaffinity() failed");
+ }
+
+ CPU_FREE(mask);
+}
+
+void tst_bind_to_current_cpu(void)
+{
+ int cpu = sched_getcpu();
+
+ if (cpu < 0)
+ tst_brkm(TBROK | TERRNO, NULL, "sched_getcpu() failed");
+
+ tst_bind_to_cpu(cpu);
+}
--
2.55.0
More information about the ltp
mailing list