xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/mlock/mlock04.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2010  Red Hat, Inc.
4  */
5 
6 /*\
7  * [Description]
8  *
9  * This is a reproducer copied from one of LKML patch submission
10  * which subject is
11  *
12  * [PATCH] mlock: revert the optimization for dirtying pages and triggering writeback.
13  * url see https://www.spinics.net/lists/kernel/msg1141090.html
14  *
15  * "In 5ecfda0, we do some optimization in mlock, but it causes
16  * a very basic test case(attached below) of mlock to fail. So
17  * this patch revert it with some tiny modification so that it
18  * apply successfully with the lastest 38-rc2 kernel."
19  *
20  * This bug was fixed by kernel
21  * commit fdf4c587a7 ("mlock: operate on any regions with protection != PROT_NONE")
22  *
23  * As this case does, mmaps a file with PROT_WRITE permissions but without
24  * PROT_READ, so attempt to not unnecessarity break COW during mlock ended up
25  * causing mlock to fail with a permission problem on unfixed kernel.
26  */
27 
28 #include <sys/mman.h>
29 #include <stdio.h>
30 #include <sys/types.h>
31 #include "tst_test.h"
32 #include "tst_safe_macros.h"
33 
34 static int fd = -1, file_len = 40960;
35 static char *testfile = "test_mlock";
36 
verify_mlock(void)37 static void verify_mlock(void)
38 {
39 	char *buf;
40 
41 	buf = SAFE_MMAP(NULL, file_len, PROT_WRITE, MAP_SHARED, fd, 0);
42 	TST_EXP_PASS(mlock(buf, file_len), "mlock(%p, %d)", buf, file_len);
43 	SAFE_MUNLOCK(buf, file_len);
44 	SAFE_MUNMAP(buf, file_len);
45 }
46 
setup(void)47 static void setup(void)
48 {
49 	fd = SAFE_OPEN(testfile, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
50 	SAFE_FTRUNCATE(fd, file_len);
51 }
52 
cleanup(void)53 static void cleanup(void)
54 {
55 	if (fd > -1)
56 		SAFE_CLOSE(fd);
57 }
58 
59 static struct tst_test test = {
60 	.needs_tmpdir = 1,
61 	.setup = setup,
62 	.cleanup = cleanup,
63 	.test_all = verify_mlock,
64 	.tags = (const struct tst_tag[]) {
65 		{"linux-git", "fdf4c587a793"},
66 		{}
67 	}
68 };
69