Skip to content

Commit d761c14

Browse files
committed
KVM: selftests: Extract guts of THP accessor to standalone sysfs helpers
Extract the guts of thp_configured() and get_trans_hugepagesz() to standalone helpers so that the core logic can be reused for other sysfs files, e.g. to query numa_balancing. Opportunistically assert that the initial fscanf() read at least one byte, and add a comment explaining the second call to fscanf(). Signed-off-by: Maxim Levitsky <[email protected]> Signed-off-by: James Houghton <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Sean Christopherson <[email protected]>
1 parent 5e9ac64 commit d761c14

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

tools/testing/selftests/kvm/lib/test_util.c

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -132,37 +132,50 @@ void print_skip(const char *fmt, ...)
132132
puts(", skipping test");
133133
}
134134

135-
bool thp_configured(void)
135+
static bool test_sysfs_path(const char *path)
136136
{
137-
int ret;
138137
struct stat statbuf;
138+
int ret;
139139

140-
ret = stat("/sys/kernel/mm/transparent_hugepage", &statbuf);
140+
ret = stat(path, &statbuf);
141141
TEST_ASSERT(ret == 0 || (ret == -1 && errno == ENOENT),
142-
"Error in stating /sys/kernel/mm/transparent_hugepage");
142+
"Error in stat()ing '%s'", path);
143143

144144
return ret == 0;
145145
}
146146

147-
size_t get_trans_hugepagesz(void)
147+
bool thp_configured(void)
148+
{
149+
return test_sysfs_path("/sys/kernel/mm/transparent_hugepage");
150+
}
151+
152+
static size_t get_sysfs_val(const char *path)
148153
{
149154
size_t size;
150155
FILE *f;
151156
int ret;
152157

153-
TEST_ASSERT(thp_configured(), "THP is not configured in host kernel");
154-
155-
f = fopen("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size", "r");
156-
TEST_ASSERT(f != NULL, "Error in opening transparent_hugepage/hpage_pmd_size");
158+
f = fopen(path, "r");
159+
TEST_ASSERT(f, "Error opening '%s'", path);
157160

158161
ret = fscanf(f, "%ld", &size);
162+
TEST_ASSERT(ret > 0, "Error reading '%s'", path);
163+
164+
/* Re-scan the input stream to verify the entire file was read. */
159165
ret = fscanf(f, "%ld", &size);
160-
TEST_ASSERT(ret < 1, "Error reading transparent_hugepage/hpage_pmd_size");
161-
fclose(f);
166+
TEST_ASSERT(ret < 1, "Error reading '%s'", path);
162167

168+
fclose(f);
163169
return size;
164170
}
165171

172+
size_t get_trans_hugepagesz(void)
173+
{
174+
TEST_ASSERT(thp_configured(), "THP is not configured in host kernel");
175+
176+
return get_sysfs_val("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size");
177+
}
178+
166179
size_t get_def_hugetlb_pagesz(void)
167180
{
168181
char buf[64];

0 commit comments

Comments
 (0)