1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2004
4 * Copyright (c) Linux Test Project, 2004-2017
5 *
6 * Test Name: hugemmap01
7 *
8 * Test Description:
9 * Verify that, mmap() succeeds when used to map a file in a hugetlbfs.
10 *
11 * Expected Result:
12 * mmap() should succeed returning the address of the hugetlb mapped region.
13 * The number of free huge pages should decrease.
14 *
15 * Test:
16 * Loop if the proper options are given.
17 * Execute system call
18 * Check return code, if system call failed (return=-1)
19 * Log the errno and Issue a FAIL message.
20 *
21 * HISTORY
22 * 04/2004 Written by Robbie Williamson
23 */
24
25 #include <stdio.h>
26 #include <sys/mount.h>
27 #include <limits.h>
28 #include <sys/param.h>
29 #include "hugetlb.h"
30
31 static long *addr;
32 static int fildes;
33 static long beforetest;
34 static long aftertest;
35 static long hugepagesmapped;
36 static char TEMPFILE[MAXPATHLEN];
37
test_hugemmap(void)38 static void test_hugemmap(void)
39 {
40 long page_sz = 0;
41
42 fildes = SAFE_OPEN(TEMPFILE, O_RDWR | O_CREAT, 0666);
43
44 beforetest = SAFE_READ_MEMINFO("HugePages_Free:");
45
46 page_sz = SAFE_READ_MEMINFO("Hugepagesize:") * 1024;
47
48 addr = mmap(NULL, page_sz, PROT_READ | PROT_WRITE,
49 MAP_SHARED, fildes, 0);
50
51 if (addr == MAP_FAILED) {
52 tst_res(TFAIL | TERRNO, "mmap() Failed on %s",
53 TEMPFILE);
54 } else {
55 tst_res(TPASS, "call succeeded");
56
57 /* force to allocate page and change HugePages_Free */
58 *(int *)addr = 0;
59 /* Make sure the number of free huge pages AFTER testing decreased */
60 aftertest = SAFE_READ_MEMINFO("HugePages_Free:");
61 hugepagesmapped = beforetest - aftertest;
62 if (hugepagesmapped < 1)
63 tst_res(TWARN, "Number of HUGEPAGES_FREE stayed the"
64 " same. Okay if multiple copies running due"
65 " to test collision.");
66 munmap(addr, page_sz);
67 }
68
69 close(fildes);
70 }
71
setup(void)72 void setup(void)
73 {
74 if (tst_hugepages == 0)
75 tst_brk(TCONF, "Not enough hugepages for testing.");
76
77 if (!Hopt)
78 Hopt = tst_get_tmpdir();
79 SAFE_MOUNT("none", Hopt, "hugetlbfs", 0, NULL);
80
81 snprintf(TEMPFILE, sizeof(TEMPFILE), "%s/mmapfile%d", Hopt, getpid());
82 }
83
cleanup(void)84 void cleanup(void)
85 {
86 unlink(TEMPFILE);
87 umount(Hopt);
88 }
89
90 static struct tst_test test = {
91 .needs_root = 1,
92 .needs_tmpdir = 1,
93 .options = (struct tst_option[]) {
94 {"H:", &Hopt, "Location of hugetlbfs, i.e. -H /var/hugetlbfs"},
95 {"s:", &nr_opt, "Set the number of the been allocated hugepages"},
96 {}
97 },
98 .setup = setup,
99 .cleanup = cleanup,
100 .test_all = test_hugemmap,
101 .request_hugepages = 128,
102 };
103