xref: /aosp_15_r20/external/ltp/testcases/kernel/mem/hugetlb/hugemmap/hugemmap20.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3  * Copyright (C) 2005-2006 David Gibson & Adam Litke, IBM Corporation.
4  * Author: David Gibson & Adam Litke
5  */
6 
7 /*\
8  * [Description]
9  *
10  * The test checks that mlocking hugetlb areas works with all combinations
11  * of MAP_PRIVATE and MAP_SHARED with and without MAP_LOCKED specified.
12  */
13 
14 #include "hugetlb.h"
15 
16 #define MNTPOINT "hugetlbfs/"
17 #define FLAGS_DESC(x) .flags = x, .flags_str = #x
18 
19 static int fd = -1;
20 static unsigned long hpage_size;
21 
22 static struct tcase {
23 	int flags;
24 	char *flags_str;
25 } tcases[] = {
26 	{ FLAGS_DESC(MAP_PRIVATE) },
27 	{ FLAGS_DESC(MAP_SHARED) },
28 	{ FLAGS_DESC(MAP_PRIVATE | MAP_LOCKED) },
29 	{ FLAGS_DESC(MAP_SHARED | MAP_LOCKED) },
30 };
31 
run_test(unsigned int i)32 static void run_test(unsigned int i)
33 {
34 	int ret;
35 	void *p;
36 	struct tcase *tc = &tcases[i];
37 
38 	fd = tst_creat_unlinked(MNTPOINT, 0);
39 	p = SAFE_MMAP(0, hpage_size, PROT_READ|PROT_WRITE, tc->flags, fd, 0);
40 
41 	ret = mlock(p, hpage_size);
42 	if (ret) {
43 		tst_res(TFAIL|TERRNO, "mlock() failed (flags %s)", tc->flags_str);
44 		goto cleanup;
45 	}
46 
47 	ret = munlock(p, hpage_size);
48 	if (ret)
49 		tst_res(TFAIL|TERRNO, "munlock() failed (flags %s)", tc->flags_str);
50 	else
51 		tst_res(TPASS, "mlock/munlock with %s hugetlb mmap", tc->flags_str);
52 
53 cleanup:
54 	SAFE_MUNMAP(p, hpage_size);
55 	SAFE_CLOSE(fd);
56 }
57 
setup(void)58 static void setup(void)
59 {
60 	struct rlimit limit_info;
61 
62 	hpage_size = tst_get_hugepage_size();
63 
64 	SAFE_GETRLIMIT(RLIMIT_MEMLOCK, &limit_info);
65 	if (limit_info.rlim_cur < hpage_size) {
66 		limit_info.rlim_max = hpage_size;
67 		limit_info.rlim_cur = hpage_size;
68 		SAFE_SETRLIMIT(RLIMIT_MEMLOCK, &limit_info);
69 	}
70 }
71 
cleanup(void)72 static void cleanup(void)
73 {
74 	if (fd >= 0)
75 		SAFE_CLOSE(fd);
76 }
77 
78 static struct tst_test test = {
79 	.tcnt = ARRAY_SIZE(tcases),
80 	.needs_root = 1,
81 	.mntpoint = MNTPOINT,
82 	.needs_hugetlbfs = 1,
83 	.needs_tmpdir = 1,
84 	.setup = setup,
85 	.cleanup = cleanup,
86 	.test = run_test,
87 	.hugepages = {1, TST_NEEDS},
88 };
89