xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/mincore/mincore03.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) Zilogic Systems Pvt. Ltd., 2020
4  * Email: [email protected]
5  */
6 
7 /*
8  * mincore03
9  * Testcase 1: Test shows that pages mapped as anonymous and
10  * not faulted, are reported as not resident in memory by mincore().
11  * Testcase 2: Test shows that pages mapped as anonymous and faulted,
12  * are reported as resident in memory by mincore().
13  */
14 
15 #include <stdbool.h>
16 #include <unistd.h>
17 #include <sys/mman.h>
18 #include "tst_test.h"
19 #include "pgsize_helpers.h"
20 
21 #define NUM_PAGES 3
22 
23 static struct tcase {
24 	bool mlock;
25 	int expected_pages;
26 	char *desc;
27 } tcases[] = {
28 	{ false, 0, "untouched pages are not resident"},
29 	{ true, NUM_PAGES, "locked pages are resident"},
30 };
31 
32 static int size, page_size;
33 static void *ptr;
34 
cleanup(void)35 static void cleanup(void)
36 {
37 	if (ptr)
38 		SAFE_MUNMAP(ptr, size);
39 }
40 
setup(void)41 static void setup(void)
42 {
43 	page_size = getpagesize();
44 	size = page_size * NUM_PAGES;
45 }
46 
test_mincore(unsigned int test_nr)47 static void test_mincore(unsigned int test_nr)
48 {
49 	const struct tcase *tc = &tcases[test_nr];
50 	DECLARE_MINCORE_VECTOR(vec, NUM_PAGES);
51 	int locked_pages;
52 	int count, mincore_ret;
53 
54 	ptr = SAFE_MMAP(NULL, size,  PROT_WRITE | PROT_READ, MAP_PRIVATE |  MAP_ANONYMOUS, 0, 0);
55 	if (tc->mlock)
56 		SAFE_MLOCK(ptr, size);
57 
58 	mincore_ret = mincore(ptr, size, vec);
59 	if (mincore_ret == -1)
60 		tst_brk(TBROK | TERRNO, "mincore failed");
61 	locked_pages = 0;
62 	for (count = 0; count < nr_pgs_to_nr_kernel_pgs(NUM_PAGES); count++)
63 		if (vec[count] & 1)
64 			locked_pages++;
65 	locked_pages = nr_kernel_pgs_to_nr_pgs(locked_pages);
66 
67 	if (locked_pages == tc->expected_pages)
68 		tst_res(TPASS, "mincore() reports %s", tc->desc);
69 	else
70 		tst_res(TFAIL, "mincore reports resident pages as %d, but expected %d",
71 			locked_pages, tc->expected_pages);
72 
73 	if (tc->mlock)
74 		SAFE_MUNLOCK(ptr, size);
75 	SAFE_MUNMAP(ptr, size);
76 	ptr = NULL;
77 }
78 
79 static struct tst_test test = {
80 	.tcnt = ARRAY_SIZE(tcases),
81 	.setup = setup,
82 	.cleanup = cleanup,
83 	.test = test_mincore,
84 };
85 
86