xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/ioctl/ioctl_loop03.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2020 FUJITSU LIMITED. All rights reserved.
4  * Copyright (c) Linux Test Project, 2022
5  * Author: Yang Xu <[email protected]>
6  */
7 
8 /*\
9  * [Description]
10  *
11  * Tests ioctl() on loopdevice with LOOP_CHANGE_FD flag.
12  *
13  * Tests whether LOOP_CHANGE_FD can not succeed (get EINVAL error)
14  * when loop_dev is not read only.
15  */
16 
17 #include <stdio.h>
18 #include <unistd.h>
19 #include <string.h>
20 #include "lapi/loop.h"
21 #include "tst_test.h"
22 
23 static char dev_path[1024];
24 static int dev_num, dev_fd, file_fd, attach_flag;
25 
verify_ioctl_loop(void)26 static void verify_ioctl_loop(void)
27 {
28 	TEST(ioctl(dev_fd, LOOP_CHANGE_FD, file_fd));
29 	if (TST_RET == 0) {
30 		tst_res(TFAIL, "LOOP_CHANGE_FD succeeded unexpectedly");
31 		return;
32 	}
33 	if (TST_ERR == EINVAL)
34 		tst_res(TPASS | TTERRNO, "LOOP_CHANGE_FD failed as expected");
35 	else
36 		tst_res(TFAIL | TTERRNO, "LOOP_CHANGE_FD failed expected EINVAL got");
37 }
38 
setup(void)39 static void setup(void)
40 {
41 	struct loop_info loopinfoget;
42 
43 	memset(&loopinfoget, 0, sizeof(loopinfoget));
44 	dev_num = tst_find_free_loopdev(dev_path, sizeof(dev_path));
45 	if (dev_num < 0)
46 		tst_brk(TBROK, "Failed to find free loop device");
47 
48 	tst_fill_file("test.img", 0, 1024, 10);
49 	tst_attach_device(dev_path, "test.img");
50 	attach_flag = 1;
51 
52 	dev_fd = SAFE_OPEN(dev_path, O_RDWR);
53 	file_fd = SAFE_OPEN("test.img", O_RDWR);
54 	SAFE_IOCTL(dev_fd, LOOP_GET_STATUS, &loopinfoget);
55 
56 	if (loopinfoget.lo_flags & LO_FLAGS_READ_ONLY)
57 		tst_brk(TCONF, "Current environment has unexpected LO_FLAGS_READ_ONLY flag");
58 }
59 
cleanup(void)60 static void cleanup(void)
61 {
62 	if (dev_fd > 0)
63 		SAFE_CLOSE(dev_fd);
64 	if (file_fd > 0)
65 		SAFE_CLOSE(file_fd);
66 	if (attach_flag)
67 		tst_detach_device(dev_path);
68 }
69 
70 static struct tst_test test = {
71 	.setup = setup,
72 	.cleanup = cleanup,
73 	.test_all = verify_ioctl_loop,
74 	.needs_root = 1,
75 	.needs_tmpdir = 1,
76 	.needs_drivers = (const char *const []) {
77 		"loop",
78 		NULL
79 	}
80 };
81