Debian Codegraph @

tests/run_tests.py

raw symbols SCIP
1 #! /usr/bin/python3
2
3 from __future__ import print_function
4 from __future__ import division
5
6 import subprocess
7 import types
8 import os
9 import sys
10 import getopt
11 import resource
12 import errno
13
14 # The superset of wordsizes that should be tested (default 32, 64)
15 wordsizes = set()
16
17 # The super set of page sizes that should be tested. Defaults to all supported
18 # huge page sizes with an active mount and at least one huge page allocated
19 pagesizes = set()
20
21 # Each page size may have a subset of valid wordsizes
22 # This is a dictionary (indexed by page size) of sets
23 wordsizes_by_pagesize = {}
24
25 # The linkhuge tests may only be valid on a subset of word sizes
26 # This set contains the wordsizes valid for linkhuge tests
27 linkhuge_wordsizes = set()
28
29 # A list of all discovered mountpoints that may be used by libhugetlbfs for
30 # this run of tests. This is used for cleaning up left-over share files.
31 mounts = []
32
33 # Results matrix: This 3-D dictionary is indexed as follows:
34 # [type] - Test results fall into one of the 'result_types' categories
35 # [pagesize] - a page size from the set 'pagesizes'
36 # [bits] - a word size from the set 'wordsizes'
37 # The indexed value is the number of tests matching the above traits
38 R = {}
39 result_types = ("total", "pass", "config", "fail", "xfail", "xpass",
40 "signal", "strange", "skip", "nofile")
41
42 def bash(cmd):
43 """
44 Run 'cmd' in the shell and return the exit code and output.
45 """
46 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
47 try:
48 rc = p.wait()
49 except KeyboardInterrupt:
50 # Abort and mark this a strange test result
51 return (127, "")
52 out = p.stdout.read().decode().strip()
53 return (rc, out)
54
55 def snapshot_pool_state():
56 l = []
57 for d in os.listdir("/sys/kernel/mm/hugepages"):
58 entries = os.listdir("/sys/kernel/mm/hugepages/%s" % d)
59 if "demote" in entries:
60 entries.remove("demote")
61 substate = [(f, int(open("/sys/kernel/mm/hugepages/%s/%s" % (d, f)).read().replace("kB","")))
62 for f in entries]
63 l.append((d, tuple(substate)))
64 return tuple(l)
65
66 def run_test_prog(bits, pagesize, cmd, output='stdout', **env):
67 if paranoid_pool_check:
68 beforepool = snapshot_pool_state()
69 print("Pool state: %s" % str(beforepool))
70
71 local_env = os.environ.copy()
72 local_env.update(env)
73 local_env["PATH"] = "./obj%d:../obj%d:%s" \
74 % (bits, bits, local_env.get("PATH", ""))
75 local_env["LD_LIBRARY_PATH"] = "../obj%d:obj%d:%s" \
76 % (bits, bits, local_env.get("LD_LIBRARY_PATH", ""))
77 local_env["HUGETLB_DEFAULT_PAGE_SIZE"] = repr(pagesize)
78
79 popen_args = {'env' : local_env, output : subprocess.PIPE}
80
81 try:
82 p = subprocess.Popen(cmd, **popen_args)
83 rc = p.wait()
84 except KeyboardInterrupt:
85 # Abort and mark this a strange test result
86 return (None, "")
87 except OSError as e:
88 return (-e.errno, "")
89 out = getattr(p, output).read().decode().strip()
90
91 if paranoid_pool_check:
92 afterpool = snapshot_pool_state()
93 if afterpool != beforepool:
94 print("Hugepage pool state not preserved!", file=sys.stderr)
95 print("BEFORE: %s" % str(beforepool), file=sys.stderr)
96 print("AFTER: %s" % str(afterpool), file=sys.stderr)
97 sys.exit(98)
98
99 return (rc, out)
100
101 def setup_env(override, defaults):
102 """
103 Set up the environment for running commands in the shell.
104 """
105 # All items in override are unconditionally set or unset
106 for (var, val) in override.items():
107 if val == None:
108 if var in os.environ:
109 del os.environ[var]
110 else:
111 os.environ[var] = val
112 # If not already set, these variables are given default values
113 for (var, val) in defaults.items():
114 if var not in os.environ or os.environ[var] == "":
115 os.environ[var] = val
116
117 def init_results():
118 """
119 Define the structure of the results matrix and initialize all results to 0.
120 """
121 global R
122
123 for t in result_types:
124 R[t] = {}
125 for p in pagesizes:
126 R[t][p] = {}
127 for bits in (32, 64):
128 R[t][p][bits] = 0
129
130 def pretty_page_size(size):
131 """
132 Convert a page size to a formatted string
133
134 Given a page size in bytes, return a string that expresses the size in
135 a sensible unit (K, M, or G).
136 """
137 factor = 0
138 while size > 1024:
139 factor += 1
140 size /= 1024
141
142 if factor == 0: return "%iB" % size
143 elif factor == 1: return "%iK" % size
144 elif factor == 2: return "%iM" % size
145 elif factor == 3: return "%iG" % size
146
147 def print_per_size(title, values):
148 """
149 Print one line of test results
150
151 Print the results of a given result type on one line. The results for all
152 page sizes and word sizes are written in a table format.
153 """
154 print("*%20s: " % title, end=" ")
155 for sz in pagesizes:
156 print("%4s %4s " % (values[sz][32], values[sz][64]), end="")
157 print()
158
159 def results_summary():
160 """
161 Display a summary of the test results
162 """
163 print("********** TEST SUMMARY")
164 print("*%21s" % "", end=" ")
165 for p in pagesizes:
166 print("%-13s " % pretty_page_size(p), end="")
167 print()
168 print("*%21s" % "", end=" ")
169 for p in pagesizes:
170 print("32-bit 64-bit ", end="")
171 print()
172
173 print_per_size("Total testcases", R["total"])
174 print_per_size("Skipped", R["skip"])
175 print_per_size("PASS", R["pass"])
176 print_per_size("FAIL", R["fail"])
177 print_per_size("Killed by signal", R["signal"])
178 print_per_size("Bad configuration", R["config"])
179 print_per_size("Expected FAIL", R["xfail"])
180 print_per_size("Unexpected PASS", R["xpass"])
181 print_per_size("Test not present", R["nofile"])
182 print_per_size("Strange test result", R["strange"])
183 print("**********")
184
185 def free_hpages(size=None):
186 """
187 Return the number of free huge pages for a given size. If size is not
188 passed, use the default huge page size.
189
190 Parse /sys/kernel/mm/hugepages/hugepages-<size-in-kB>/free_hugepages to
191 obtain the number of free huge pages for the given page size.
192 """
193 if size == None: size = system_default_hpage_size
194 size_kb = size / 1024
195 cmd = "cat /sys/kernel/mm/hugepages/hugepages-%dkB/free_hugepages" % size_kb
196 (rc, out) = bash(cmd)
197 return (rc, int(out))
198
199 def total_hpages(size=None):
200 """
201 Return the total number of huge pages in the pool for a given size. If
202 size is not passed, use the default huge page size.
203
204 Parse /sys/kernel/mm/hugepages/hugepages-<size-in-kB>/nr_hugepages to
205 obtain the number of huge pages for the given page size.
206 """
207 if size == None: size = system_default_hpage_size
208 size_kb = size / 1024
209 cmd = "cat /sys/kernel/mm/hugepages/hugepages-%dkB/nr_hugepages" % size_kb
210 (rc, out) = bash(cmd)
211 return (rc, int(out))
212
213 def hpage_size():
214 """
215 Return the size of the default huge page size in bytes.
216
217 Parse /proc/meminfo to obtain the default huge page size. This number is
218 reported in Kb so multiply it by 1024 to convert it to bytes.
219 XXX: This function is not multi-size aware yet.
220 """
221 (rc, out) = bash("grep 'Hugepagesize:' /proc/meminfo | awk '{print $2}'")
222 if out == "": out = 0
223 out = int(out) * 1024
224 return (rc, out)
225
226 def clear_hpages():
227 """
228 Remove stale hugetlbfs files after sharing tests.
229
230 Traverse the mount points that are in use during testing to find left-over
231 files that were created by the elflink sharing tests. These are not
232 cleaned up automatically and must be removed to free up the huge pages.
233 """
234 for mount in mounts:
235 dir = mount + "/elflink-uid-" + repr(os.getuid())
236 for root, dirs, files in os.walk(dir, topdown=False):
237 for name in files:
238 os.remove(os.path.join(root, name))
239 for name in dirs:
240 os.rmdir(os.path.join(root, name))
241 try:
242 os.rmdir(dir)
243 except OSError:
244 pass
245
246 def get_pagesizes():
247 """
248 Get a list of configured huge page sizes.
249
250 Use libhugetlbfs' hugeadm utility to get a list of page sizes that have
251 active mount points and at least one huge page allocated to the pool.
252 """
253 sizes = set()
254 out = ""
255 (rc, out) = bash("../obj/hugeadm --page-sizes")
256 if rc != 0 or out == "":
257 return sizes
258
259 for size in out.split("\n"):
260 sizes.add(int(size))
261 return sizes
262
263 def get_wordsizes():
264 """
265 Checks for obj32 and obj64 subdirs to determine valid word sizes.
266 """
267 sizes = set()
268 if os.path.isdir("./obj32"): sizes.add(32)
269 if os.path.isdir("./obj64"): sizes.add(64)
270
271 return sizes
272
273 def check_hugetlbfs_path():
274 """
275 Check each combination of page size and word size for validity.
276
277 Some word sizes may not be valid for all page sizes. For example, a 16G
278 page is too large to be used in a 32 bit process. Use a helper program to
279 weed out invalid combinations and print informational messages as required.
280 """
281 global wordsizes, pagesizes, mounts, wordsizes_by_pagesize
282
283 for p in pagesizes:
284 okbits = []
285 for b in wordsizes:
286 (rc, out) = run_test_prog(b, p, "get_hugetlbfs_path")
287 if rc == 0:
288 okbits.append(b)
289 mounts.append(out)
290 if len(okbits) == 0:
291 print("run_tests.py: No mountpoints available for page size %s" %
292 pretty_page_size(p))
293 wordsizes_by_pagesize[p] = set()
294 continue
295 for b in wordsizes - set(okbits):
296 print("run_tests.py: The %i bit word size is not compatible with " \
297 "%s pages" % (b, pretty_page_size(p)))
298 wordsizes_by_pagesize[p] = set(okbits)
299
300 def check_linkhuge_tests():
301 """
302 Check if the linkhuge tests are safe to run on this system.
303
304 Newer versions of binutils (>= 2.18) are known to be incompatible with the
305 linkhuge tests and running them may cause unreliable behavior. Determine
306 which word sizes can be tested with linkhuge. The others will be skipped.
307 NOTE: The linhuge_rw tests are always safe to run and will not be skipped.
308 """
309 okbits = set()
310
311 for bits in wordsizes:
312 script = open('obj%d/dummy.ldscript' % bits, 'r').read()
313 if script.count('SPECIAL') == 0:
314 okbits.add(bits)
315 return okbits
316
317 def check_morecore_disabled():
318 """
319 Check if support for morecore is available.
320
321 Newer glibc versions (>= 2.34) removed the __morecore malloc hook, so tests
322 relying on that functionality will not work as expected, and should be
323 disabled.
324 """
325 global morecore_disabled, wordsizes, pagesizes
326
327 # Quick and dirty way to get a word and page size. Which one doesn't really
328 # matter in this case.
329 for wsz in wordsizes:
330 b = wsz
331 break
332 for psz in pagesizes:
333 p = psz
334 break
335
336 # Run an arbitrary program and check stderr for the "morecore disabled"
337 # message
338 (rc, out) = run_test_prog(b, p, "gethugepagesize", output='stderr',
339 HUGETLB_MORECORE="yes",
340 HUGETLB_VERBOSE="3")
341
342 morecore_disabled = "Not setting up morecore" in out
343
344 def print_cmd(pagesize, bits, cmd, env):
345 if env:
346 print(' '.join(['%s=%s' % (k, v) for k, v in env.items()]), end=" ")
347 if not isinstance(cmd, str):
348 cmd = ' '.join(cmd)
349 print("%s (%s: %i):\t" % (cmd, pretty_page_size(pagesize), bits), end="")
350 sys.stdout.flush()
351
352 def run_test(pagesize, bits, cmd, **env):
353 """
354 Execute a test, print the output and log the result
355
356 Run a test using the specified page size and word size. The parameter
357 'pre' may contain additional environment settings and will be prepended to
358 cmd. A line showing info about the test is printed and after completion
359 the test output is printed. The result is recorded in the result matrix.
360 """
361 global R
362
363 objdir = "obj%i" % bits
364 if not os.path.isdir(objdir):
365 return
366
367 print_cmd(pagesize, bits, cmd, env)
368 (rc, out) = run_test_prog(bits, pagesize, cmd, **env)
369 print(out)
370
371 R["total"][pagesize][bits] += 1
372 if rc == 0: R["pass"][pagesize][bits] += 1
373 elif rc == 1: R["config"][pagesize][bits] += 1
374 elif rc == 2: R["fail"][pagesize][bits] += 1
375 elif rc == 3: R["xfail"][pagesize][bits] += 1
376 elif rc == 4: R["xpass"][pagesize][bits] += 1
377 elif rc == -errno.ENOENT:
378 R["nofile"][pagesize][bits] += 1
379 elif rc < 0: R["signal"][pagesize][bits] += 1
380 else: R["strange"][pagesize][bits] += 1
381
382 def skip_test(pagesize, bits, cmd, **env):
383 """
384 Skip a test, print test information, and log that it was skipped.
385 """
386 global tot_tests, tot_skip
387 R["total"][pagesize][bits] += 1
388 R["skip"][pagesize][bits] += 1
389 print_cmd(pagesize, bits, cmd, env)
390 print("SKIPPED")
391
392 def do_test(cmd, bits=None, skip=False, **env):
393 """
394 Run a test case, testing each page size and each indicated word size.
395 """
396 if bits == None: bits = wordsizes
397 for p in pagesizes:
398 for b in (set(bits) & wordsizes_by_pagesize[p]):
399 if skip:
400 skip_test(p, b, cmd, **env)
401 else:
402 run_test(p, b, cmd, **env)
403
404 def do_test_with_rlimit(rtype, limit, cmd, bits=None, **env):
405 """
406 Run a test case with a temporarily altered resource limit.
407 """
408 oldlimit = resource.getrlimit(rtype)
409 resource.setrlimit(rtype, (limit, limit))
410 do_test(cmd, bits, **env)
411 resource.setrlimit(rtype, oldlimit)
412
413 def do_test_with_pagesize(pagesize, cmd, bits=None, skip=False, **env):
414 """
415 Run a test case, testing with a specified huge page size and
416 each indicated word size.
417 """
418 if bits == None:
419 bits = wordsizes
420 for b in (set(bits) & wordsizes_by_pagesize[pagesize]):
421 if skip:
422 skip_test(pagesize, b, cmd, **env)
423 else:
424 run_test(pagesize, b, cmd, **env)
425
426 def do_elflink_test(cmd, **env):
427 """
428 Run an elflink test case, skipping known-bad configurations.
429 """
430 for b in wordsizes_by_pagesize[system_default_hpage_size]:
431 if b in linkhuge_wordsizes:
432 run_test(system_default_hpage_size, b, cmd, **env)
433 else:
434 skip_test(system_default_hpage_size, b, cmd, **env)
435
436 def elflink_test(cmd, **env):
437 """
438 Run an elflink test case with different configuration combinations.
439
440 Test various combinations of: preloading libhugetlbfs, B vs. BDT link
441 modes, minimal copying on or off, and disabling segment remapping.
442 """
443 do_test_with_pagesize(system_default_hpage_size, cmd, **env)
444 # Test we don't blow up if not linked for hugepage
445 do_test_with_pagesize(system_default_hpage_size, cmd,
446 LD_PRELOAD="libhugetlbfs.so", **env)
447
448 # Only run custom ldscript tests when -l option is set
449 if not custom_ldscripts:
450 return
451
452 do_elflink_test("xB." + cmd, **env)
453 do_elflink_test("xBDT." + cmd, **env)
454 # Test we don't blow up if HUGETLB_MINIMAL_COPY is diabled
455 do_elflink_test("xB." + cmd, HUGETLB_MINIMAL_COPY="no", **env)
456 do_elflink_test("xBDT." + cmd, HUGETLB_MINIMAL_COPY="no", **env)
457 # Test that HUGETLB_ELFMAP=no inhibits remapping as intended
458 do_elflink_test("xB." + cmd, HUGETLB_ELFMAP="no", **env)
459 do_elflink_test("xBDT." + cmd, HUGETLB_ELFMAP="no", **env)
460
461 def elflink_rw_test(cmd, **env):
462 """
463 Run the elflink_rw test with different configuration combinations.
464
465 Test various combinations of: remapping modes and minimal copy on or off.
466 """
467 # Basic tests: None, Read-only, Write-only, Read-Write, exlicit disable
468 do_test_with_pagesize(system_default_hpage_size, cmd, **env)
469 do_test_with_pagesize(system_default_hpage_size, cmd,
470 HUGETLB_ELFMAP="R", **env)
471 do_test_with_pagesize(system_default_hpage_size, cmd,
472 HUGETLB_ELFMAP="W", **env)
473 do_test_with_pagesize(system_default_hpage_size, cmd,
474 HUGETLB_ELFMAP="RW", **env)
475 do_test_with_pagesize(system_default_hpage_size, cmd,
476 HUGETLB_ELFMAP="no", **env)
477
478 # Test we don't blow up if HUGETLB_MINIMAL_COPY is disabled
479 do_test_with_pagesize(system_default_hpage_size, cmd,
480 HUGETLB_MINIMAL_COPY="no", HUGETLB_ELFMAP="R", **env)
481 do_test_with_pagesize(system_default_hpage_size, cmd,
482 HUGETLB_MINIMAL_COPY="no", HUGETLB_ELFMAP="W", **env)
483 do_test_with_pagesize(system_default_hpage_size, cmd,
484 HUGETLB_MINIMAL_COPY="no", HUGETLB_ELFMAP="RW", **env)
485
486 def elfshare_test(cmd, **env):
487 """
488 Test segment sharing with multiple configuration variations.
489 """
490 # Run each elfshare test invocation independently - clean up the
491 # sharefiles before and after in the first set of runs, but leave
492 # them there in the second:
493 clear_hpages()
494 do_elflink_test("xB." + cmd, HUGETLB_SHARE="1", **env)
495 clear_hpages()
496 do_elflink_test("xBDT." + cmd, HUGETLB_SHARE="1", **env)
497 clear_hpages()
498 do_elflink_test("xB." + cmd, HUGETLB_SHARE="1", **env)
499 do_elflink_test("xBDT." + cmd, HUGETLB_SHARE="1", **env)
500 clear_hpages()
501
502 def elflink_and_share_test(cmd, **env):
503 """
504 Run the ordinary linkhuge tests with sharing enabled
505 """
506 # Run each elflink test pair independently - clean up the sharefiles
507 # before and after each pair
508 clear_hpages()
509 for link_str in ("xB.", "xBDT."):
510 for i in range(2):
511 do_elflink_test(link_str + cmd, HUGETLB_SHARE=repr(i), **env)
512 clear_hpages()
513
514 def elflink_rw_and_share_test(cmd, **env):
515 """
516 Run the ordinary linkhuge_rw tests with sharing enabled
517 """
518 clear_hpages()
519 for mode in ("R", "W", "RW"):
520 for i in range(2):
521 do_test_with_pagesize(system_default_hpage_size, cmd,
522 HUGETLB_ELFMAP=mode, HUGETLB_SHARE=repr(i),
523 **env)
524 clear_hpages()
525
526 def setup_shm_sysctl(limit):
527 """
528 Adjust the kernel shared memory limits to accomodate a desired size.
529
530 The original values are returned in a dictionary that can be passed to
531 restore_shm_sysctl() to restore the system state.
532 """
533 if os.getuid() != 0: return {}
534 sysctls = {}
535 files = [ "/proc/sys/kernel/shmmax", "/proc/sys/kernel/shmall"]
536 for f in files:
537 fh = open(f, "r")
538 sysctls[f] = fh.read()
539 fh.close()
540 fh = open(f, "w")
541 fh.write(repr(limit))
542 fh.close()
543 print("set shmmax limit to %s" % limit)
544 return sysctls
545
546 def restore_shm_sysctl(sysctls):
547 """
548 Restore the sysctls named in 'sysctls' to the given values.
549 """
550 if os.getuid() != 0: return
551 for (file, val) in sysctls.items():
552 fh = open(file, "w")
553 fh.write(val)
554 fh.close()
555
556 def do_shm_test(cmd, limit=None, bits=None, **env):
557 """
558 Run a test case with temporarily expanded SysV shm limits, testing
559 each indicated word size.
560 """
561 if bits == None:
562 bits = wordsizes
563 if limit != None:
564 tmp = setup_shm_sysctl(limit)
565 for b in bits:
566 run_test(system_default_hpage_size, b, cmd, **env)
567 if limit != None:
568 restore_shm_sysctl(tmp)
569
570 def functional_tests():
571 """
572 Run the set of functional tests.
573 """
574 global linkhuge_wordsizes, morecore_disabled
575
576 # Kernel background tests not requiring hugepage support
577 do_test("zero_filesize_segment")
578
579 # Library background tests not requiring hugepage support
580 do_test("test_root")
581 do_test("meminfo_nohuge")
582
583 # Library tests requiring kernel hugepage support
584 do_test("gethugepagesize")
585 do_test("gethugepagesizes")
586 do_test("empty_mounts", HUGETLB_VERBOSE="1")
587 do_test("large_mounts", HUGETLB_VERBOSE="1")
588
589 # Tests requiring an active and usable hugepage mount
590 do_test("find_path")
591 do_test("unlinked_fd")
592 do_test("readback")
593 do_test("truncate")
594 do_test("shared")
595 do_test("mprotect")
596 do_test_with_rlimit(resource.RLIMIT_MEMLOCK, -1, "mlock")
597 do_test("misalign")
598 do_test("fallocate_basic.sh")
599 do_test("fallocate_align.sh")
600
601 # Specific kernel bug tests
602 do_test("ptrace-write-hugepage")
603 do_test("icache-hygiene")
604 do_test("slbpacaflush")
605 do_test("straddle_4GB_static", bits=(64,))
606 do_test("huge_at_4GB_normal_below_static", bits=(64,))
607 do_test("huge_below_4GB_normal_above_static", bits=(64,))
608 do_test("map_high_truncate_2")
609 do_test("misaligned_offset")
610 do_test("truncate_above_4GB")
611 do_test("brk_near_huge")
612 do_test("task-size-overrun")
613 do_test_with_rlimit(resource.RLIMIT_STACK, -1, "stack_grow_into_huge")
614 do_test("corrupt-by-cow-opt")
615 do_test("noresv-preserve-resv-page")
616 do_test("noresv-regarded-as-resv")
617
618 if dangerous == 1:
619 do_test("readahead_reserve")
620 do_test("madvise_reserve")
621 do_test("fadvise_reserve")
622 do_test("mremap-expand-slice-collision")
623 do_test("mremap-fixed-normal-near-huge")
624 do_test("mremap-fixed-huge-near-normal")
625 else:
626 do_test("readahead_reserve.sh")
627 do_test("madvise_reserve.sh")
628 do_test("fadvise_reserve.sh")
629 do_test("mremap-expand-slice-collision.sh")
630 do_test("mremap-fixed-normal-near-huge.sh")
631 do_test("mremap-fixed-huge-near-normal.sh")
632 do_shm_test("shm-perms", 64*1024*1024)
633
634 # Tests requiring an active mount and hugepage COW
635 do_test("private")
636 do_test("fork-cow")
637 do_test("direct")
638 do_test_with_pagesize(system_default_hpage_size, "malloc")
639
640 do_test_with_pagesize(system_default_hpage_size, "malloc",
641 skip=morecore_disabled,
642 LD_PRELOAD="libhugetlbfs.so",
643 HUGETLB_MORECORE="yes")
644 do_test_with_pagesize(system_default_hpage_size, "malloc",
645 skip=morecore_disabled,
646 LD_PRELOAD="libhugetlbfs.so",
647 HUGETLB_MORECORE="yes",
648 HUGETLB_RESTRICT_EXE="unknown:none")
649 do_test_with_pagesize(system_default_hpage_size, "malloc",
650 skip=morecore_disabled,
651 LD_PRELOAD="libhugetlbfs.so",
652 HUGETLB_MORECORE="yes",
653 HUGETLB_RESTRICT_EXE="unknown:malloc")
654 do_test_with_pagesize(system_default_hpage_size, "malloc_manysmall")
655 do_test_with_pagesize(system_default_hpage_size, "malloc_manysmall",
656 skip=morecore_disabled,
657 LD_PRELOAD="libhugetlbfs.so",
658 HUGETLB_MORECORE="yes")
659
660 # After upstream commit: (glibc-2.25.90-688-gd5c3fafc43) glibc has a
661 # new per-thread caching mechanism that will NOT allow heapshrink test to
662 # successfully measure if heap has shrunk or not due to the fact that
663 # heap won't have its sized reduced right away.
664 #
665 # In order to disable it, you need to have the tunable GLIBC in place.
666 # Unfortunately, it requires to be set before program is loaded, as an
667 # environment variable, since we can't re-initialize malloc() from the
668 # program context (not even with a constructor function), and the tunable
669 # is only evaluated during malloc() initialization.
670
671 do_test_with_pagesize(system_default_hpage_size, "heapshrink",
672 GLIBC_TUNABLES="glibc.malloc.tcache_count=0")
673 do_test_with_pagesize(system_default_hpage_size, "heapshrink",
674 GLIBC_TUNABLES="glibc.malloc.tcache_count=0",
675 LD_PRELOAD="libheapshrink.so")
676
677 do_test_with_pagesize(system_default_hpage_size, "heapshrink",
678 skip=morecore_disabled,
679 GLIBC_TUNABLES="glibc.malloc.tcache_count=0",
680 LD_PRELOAD="libhugetlbfs.so",
681 HUGETLB_MORECORE="yes")
682 do_test_with_pagesize(system_default_hpage_size, "heapshrink",
683 skip=morecore_disabled,
684 GLIBC_TUNABLES="glibc.malloc.tcache_count=0",
685 LD_PRELOAD="libhugetlbfs.so libheapshrink.so",
686 HUGETLB_MORECORE="yes")
687 do_test_with_pagesize(system_default_hpage_size, "heapshrink",
688 skip=morecore_disabled,
689 GLIBC_TUNABLES="glibc.malloc.tcache_count=0",
690 LD_PRELOAD="libheapshrink.so",
691 HUGETLB_MORECORE="yes",
692 HUGETLB_MORECORE_SHRINK="yes")
693 do_test_with_pagesize(system_default_hpage_size, "heapshrink",
694 skip=morecore_disabled,
695 GLIBC_TUNABLES="glibc.malloc.tcache_count=0",
696 LD_PRELOAD="libhugetlbfs.so libheapshrink.so",
697 HUGETLB_MORECORE="yes",
698 HUGETLB_MORECORE_SHRINK="yes")
699
700 do_test("heap-overflow", skip=morecore_disabled, HUGETLB_VERBOSE="1",
701 HUGETLB_MORECORE="yes")
702
703 # Run the remapping tests' up-front checks
704 linkhuge_wordsizes = check_linkhuge_tests()
705 # Original elflink tests
706 elflink_test("linkhuge_nofd", HUGETLB_VERBOSE="0")
707 elflink_test("linkhuge")
708
709 # Only run custom ldscript tests when -l option is set
710 if custom_ldscripts:
711 # Original elflink sharing tests
712 elfshare_test("linkshare")
713 elflink_and_share_test("linkhuge")
714
715 # elflink_rw tests
716 elflink_rw_test("linkhuge_rw")
717 # elflink_rw sharing tests
718 elflink_rw_and_share_test("linkhuge_rw")
719
720 # Accounting bug tests
721 # reset free hpages because sharing will have held some
722 # alternatively, use
723 do_test("chunk-overcommit")
724 do_test(("alloc-instantiate-race", "shared"))
725 do_test(("alloc-instantiate-race", "private"))
726 do_test("truncate_reserve_wraparound")
727 do_test("truncate_sigbus_versus_oom")
728
729 # Test direct allocation API
730 do_test("get_huge_pages")
731
732 # Test overriding of shmget()
733 do_shm_test("shmoverride_linked")
734 do_shm_test("shmoverride_linked", HUGETLB_SHM="yes")
735
736 #Since we use dlsym to hijack shmget, we can't use -static when using shm huge,
737 #as it will cause an error: 'ERROR: RTLD_NEXT used in code not dynamically loaded.
738 #do_shm_test("shmoverride_linked_static")
739 #do_shm_test("shmoverride_linked_static", HUGETLB_SHM="yes")
740 do_shm_test("shmoverride_unlinked", LD_PRELOAD="libhugetlbfs.so")
741 do_shm_test("shmoverride_unlinked", LD_PRELOAD="libhugetlbfs.so", HUGETLB_SHM="yes")
742
743 # Test hugetlbfs filesystem quota accounting
744 do_test("quota.sh")
745
746 # Test accounting of HugePages_{Total|Free|Resv|Surp}
747 # Alters the size of the hugepage pool so should probably be run last
748 do_test("counters.sh")
749
750 def stress_tests():
751 """
752 Run the set of stress tests.
753 """
754 iterations = 10 # Number of iterations for looping tests
755
756 # Don't update NRPAGES every time like above because we want to catch the
757 # failures that happen when the kernel doesn't release all of the huge pages
758 # after a stress test terminates
759 nr_pages = {p: free_hpages(p)[1] for p in pagesizes}
760
761 for p in pagesizes:
762 cmd = ("mmap-gettest", repr(iterations), repr(nr_pages[p]))
763 do_test_with_pagesize(p, cmd)
764
765 for p in pagesizes:
766 # mmap-cow needs a hugepage for each thread plus one extra
767 cmd = ("mmap-cow", repr(nr_pages[p]-1), repr(nr_pages[p]))
768 do_test_with_pagesize(p, cmd)
769
770 (rc, tot_pages) = total_hpages()
771 nr_pages = nr_pages[system_default_hpage_size]
772 limit = system_default_hpage_size * tot_pages
773 threads = 10 # Number of threads for shm-fork
774
775 # Run shm-fork once using half available hugepages, then once using all
776 # This is to catch off-by-ones or races in the kernel allocated that
777 # can make allocating all hugepages a problem
778 if nr_pages > 1:
779 do_shm_test(("shm-fork", repr(threads), repr(nr_pages // 2)), limit)
780 do_shm_test(("shm-fork", repr(threads), repr(nr_pages)), limit)
781
782 do_shm_test(("shm-getraw", repr(nr_pages), "/dev/full"), limit)
783
784 do_test("fallocate_stress.sh")
785
786 def print_help():
787 print("Usage: %s [options]" % sys.argv[0])
788 print("Options:")
789 print(" -v \t Verbose output.")
790 print(" -V \t Highly verbose output.")
791 print(" -f \t Force all tests.")
792 print(" -t <set> Run test set, allowed are func and stress.")
793 print(" -b <wordsize> Define wordsizes to be used. ")
794 print(" -p <pagesize> Define the page sizes to be used.")
795 print(" -c \t Do a paranoid pool check.")
796 print(" -l \t Use custom ld scripts.")
797 print(" -h \t This help.")
798 sys.exit(0)
799
800 def main():
801 global wordsizes, pagesizes, dangerous, paranoid_pool_check, system_default_hpage_size
802 global custom_ldscripts, morecore_disabled
803 testsets = set()
804 env_override = {"QUIET_TEST": "1", "HUGETLBFS_MOUNTS": "",
805 "HUGETLB_ELFMAP": None, "HUGETLB_MORECORE": None}
806 env_defaults = {"HUGETLB_VERBOSE": "0"}
807 dangerous = 0
808 paranoid_pool_check = False
809 custom_ldscripts = False
810
811 try:
812 opts, args = getopt.getopt(sys.argv[1:], "vVft:b:p:c:lh")
813 except getopt.GetoptError as err:
814 print(str(err))
815 sys.exit(1)
816 for opt, arg in opts:
817 if opt == "-v":
818 env_override["QUIET_TEST"] = None
819 env_defaults["HUGETLB_VERBOSE"] = "2"
820 elif opt == "-V":
821 env_defaults["HUGETLB_VERBOSE"] = "99"
822 elif opt == "-f":
823 dangerous = 1
824 elif opt == "-t":
825 for t in arg.split(): testsets.add(t)
826 elif opt == "-b":
827 for b in arg.split(): wordsizes.add(int(b))
828 elif opt == "-p":
829 for p in arg.split(): pagesizes.add(int(p))
830 elif opt == '-c':
831 paranoid_pool_check = True
832 elif opt == '-l':
833 custom_ldscripts = True
834 elif opt == '-h':
835 print_help()
836 else:
837 assert False, "unhandled option"
838 if len(testsets) == 0: testsets = set(["func", "stress"])
839 if len(wordsizes) == 0: wordsizes = get_wordsizes()
840 if len(pagesizes) == 0: pagesizes = get_pagesizes()
841
842 if len(pagesizes) == 0:
843 print("Unable to find available page sizes, are you sure hugetlbfs")
844 print("is mounted and there are available huge pages?")
845 return 1
846
847 setup_env(env_override, env_defaults)
848 init_results()
849
850 (rc, system_default_hpage_size) = hpage_size()
851 if rc != 0:
852 print("Unable to find system default hugepage size.")
853 print("Is hugepage supported included in this kernel?")
854 return 1
855
856 check_hugetlbfs_path()
857 check_morecore_disabled()
858
859 if "func" in testsets: functional_tests()
860 if "stress" in testsets: stress_tests()
861
862 results_summary()
863
864 if __name__ == "__main__":
865 main()