xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/swapon/swapon02.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) Wipro Technologies Ltd, 2002.  All Rights Reserved.
4  * Copyright (c) Linux Test Project, 2002-2023
5  */
6 
7 /*\
8  * [Description]
9  *
10  * This test case checks whether swapon(2) system call returns:
11  *
12  * - ENOENT when the path does not exist
13  * - EINVAL when the path exists but is invalid
14  * - EPERM when user is not a superuser
15  * - EBUSY when the specified path is already being used as a swap area
16  */
17 
18 #include <pwd.h>
19 
20 #include "tst_test.h"
21 #include "lapi/syscalls.h"
22 #include "libswap.h"
23 
24 #define MNTPOINT	"mntpoint"
25 #define TEST_FILE	MNTPOINT"/testswap"
26 #define NOTSWAP_FILE	MNTPOINT"/notswap"
27 #define SWAP_FILE	MNTPOINT"/swapfile"
28 #define USED_FILE	MNTPOINT"/alreadyused"
29 
30 static uid_t nobody_uid;
31 static int do_swapoff;
32 
33 static struct tcase {
34 	char *err_desc;
35 	int exp_errno;
36 	char *path;
37 } tcases[] = {
38 	{"Path does not exist", ENOENT, "./doesnotexist"},
39 	{"Invalid path", EINVAL, NOTSWAP_FILE},
40 	{"Permission denied", EPERM, SWAP_FILE},
41 	{"File already used", EBUSY, USED_FILE},
42 };
43 
setup(void)44 static void setup(void)
45 {
46 	struct passwd *nobody;
47 
48 	nobody = SAFE_GETPWNAM("nobody");
49 	nobody_uid = nobody->pw_uid;
50 
51 	is_swap_supported(TEST_FILE);
52 
53 	SAFE_TOUCH(NOTSWAP_FILE, 0777, NULL);
54 	MAKE_SMALL_SWAPFILE(SWAP_FILE);
55 	MAKE_SMALL_SWAPFILE(USED_FILE);
56 
57 	if (tst_syscall(__NR_swapon, USED_FILE, 0))
58 		tst_res(TWARN | TERRNO, "swapon(alreadyused) failed");
59 	else
60 		do_swapoff = 1;
61 }
62 
cleanup(void)63 static void cleanup(void)
64 {
65 	if (do_swapoff && tst_syscall(__NR_swapoff, USED_FILE))
66 		tst_res(TWARN | TERRNO, "swapoff(alreadyused) failed");
67 }
68 
verify_swapon(unsigned int i)69 static void verify_swapon(unsigned int i)
70 {
71 	struct tcase *tc = tcases + i;
72 	if (tc->exp_errno == EPERM)
73 		SAFE_SETEUID(nobody_uid);
74 
75 	TST_EXP_FAIL(tst_syscall(__NR_swapon, tc->path, 0), tc->exp_errno,
76 		     "swapon(2) fail with %s", tc->err_desc);
77 
78 	if (tc->exp_errno == EPERM)
79 		SAFE_SETEUID(0);
80 
81 	if (TST_RET != -1) {
82 		tst_res(TFAIL, "swapon(2) failed unexpectedly, expected: %s",
83 			tst_strerrno(tc->exp_errno));
84 	}
85 }
86 
87 static struct tst_test test = {
88 	.mntpoint = MNTPOINT,
89 	.mount_device = 1,
90 	.all_filesystems = 1,
91 	.needs_root = 1,
92 	.test = verify_swapon,
93 	.tcnt = ARRAY_SIZE(tcases),
94 	.setup = setup,
95 	.cleanup = cleanup
96 };
97