1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 /*
4 * Copyright (c) Zilogic Systems Pvt. Ltd., 2018
5 * Email: code@zilogic.com
6 */
7
8 /*
9 * Test: Validating memfd_create() with MFD_HUGETLB and MFD_HUGE_x flags.
10 *
11 * Test cases: Attempt to create files in the hugetlbfs filesystem using
12 * different huge page sizes.
13 *
14 * Test logic: memfd_create() should return non-negative value (fd)
15 * if the system supports that particular huge page size.
16 * On success, fd is returned.
17 * On failure, -1 is returned with ENODEV error.
18 */
19
20 #define _GNU_SOURCE
21
22 #include "tst_test.h"
23 #include "memfd_create_common.h"
24
25 #include <errno.h>
26 #include <stdio.h>
27
28 #define PATH_HUGEPAGES "/sys/kernel/mm/hugepages"
29
30 static struct test_flag {
31 int flag;
32 char *h_size;
33 int exp_err;
34 } test_flags[] = {
35 {.flag = MFD_HUGE_64KB, .h_size = "64kB"},
36 {.flag = MFD_HUGE_512KB, .h_size = "512kB"},
37 {.flag = MFD_HUGE_2MB, .h_size = "2048kB"},
38 {.flag = MFD_HUGE_8MB, .h_size = "8192kB"},
39 {.flag = MFD_HUGE_16MB, .h_size = "16384kB"},
40 {.flag = MFD_HUGE_256MB, .h_size = "262144kB"},
41 {.flag = MFD_HUGE_1GB, .h_size = "1048576kB"},
42 {.flag = MFD_HUGE_2GB, .h_size = "2097152kB"},
43 {.flag = MFD_HUGE_16GB, .h_size = "16777216kB"},
44 };
45
check_hugepage_support(struct test_flag * test_flags)46 static void check_hugepage_support(struct test_flag *test_flags)
47 {
48 char pattern[64];
49
50 sprintf(pattern, PATH_HUGEPAGES);
51 strcat(pattern, "/hugepages-");
52 strcat(pattern, test_flags->h_size);
53
54 if (access(pattern, F_OK))
55 test_flags->exp_err = ENODEV;
56 }
57
memfd_huge_x_controller(unsigned int n)58 static void memfd_huge_x_controller(unsigned int n)
59 {
60 int fd;
61 struct test_flag tflag;
62
63 tflag = test_flags[n];
64 check_hugepage_support(&tflag);
65 tst_res(TINFO,
66 "Attempt to create file using %s huge page size",
67 tflag.h_size);
68
69 fd = sys_memfd_create("tfile", MFD_HUGETLB | tflag.flag);
70 if (fd < 0) {
71 if (errno == tflag.exp_err)
72 tst_res(TPASS, "Test failed as expected");
73 else
74 tst_brk(TFAIL | TERRNO,
75 "memfd_create() failed unexpectedly");
76 return;
77 }
78
79 tst_res(TPASS,
80 "memfd_create succeeded for %s page size",
81 tflag.h_size);
82 }
83
setup(void)84 static void setup(void)
85 {
86 if (access(PATH_HUGEPAGES, F_OK))
87 tst_brk(TCONF, "Huge page is not supported");
88 }
89
90 static struct tst_test test = {
91 .setup = setup,
92 .test = memfd_huge_x_controller,
93 .tcnt = ARRAY_SIZE(test_flags),
94 .min_kver = "4.14",
95 };
96