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 <xuyang2018.jy@cn.jujitsu.com>
6  */
7 
8 /*\
9  * [Description]
10  *
11  * Tests ioctl() on loopdevice with LOOP_SET_CAPACITY flag.
12  *
13  * Tests whether LOOP_SET_CAPACITY can update a live
14  * loop device size after change the size of the underlying
15  * backing file. Also checks sysfs value.
16  */
17 
18 #include <stdio.h>
19 #include <unistd.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include "lapi/loop.h"
23 #include "tst_test.h"
24 
25 #define OLD_SIZE 10240
26 #define NEW_SIZE 5120
27 
28 static char dev_path[1024], sys_loop_sizepath[1024];
29 static char *wrbuf;
30 static int dev_num, dev_fd, file_fd, attach_flag;
31 
verify_ioctl_loop(void)32 static void verify_ioctl_loop(void)
33 {
34 	struct loop_info loopinfoget;
35 
36 	memset(&loopinfoget, 0, sizeof(loopinfoget));
37 	tst_fill_file("test.img", 0, 1024, OLD_SIZE/1024);
38 	tst_attach_device(dev_path, "test.img");
39 	attach_flag = 1;
40 
41 	TST_ASSERT_INT(sys_loop_sizepath, OLD_SIZE/512);
42 	file_fd = SAFE_OPEN("test.img", O_RDWR);
43 	SAFE_IOCTL(dev_fd, LOOP_GET_STATUS, &loopinfoget);
44 
45 	if (loopinfoget.lo_flags & LO_FLAGS_READ_ONLY)
46 		tst_brk(TCONF, "Current environment has unexpected LO_FLAGS_READ_ONLY flag");
47 
48 	SAFE_TRUNCATE("test.img", NEW_SIZE);
49 	SAFE_IOCTL(dev_fd, LOOP_SET_CAPACITY);
50 
51 	SAFE_LSEEK(dev_fd, 0, SEEK_SET);
52 
53 	/*check that we can't write data beyond 5K into loop device*/
54 	TEST(write(dev_fd, wrbuf, OLD_SIZE));
55 	if (TST_RET == NEW_SIZE) {
56 		tst_res(TPASS, "LOOP_SET_CAPACITY set loop size to %d", NEW_SIZE);
57 	} else {
58 		tst_res(TFAIL, "LOOP_SET_CAPACITY didn't set loop size to %d, its size is %ld",
59 				NEW_SIZE, TST_RET);
60 	}
61 
62 	TST_ASSERT_INT(sys_loop_sizepath, NEW_SIZE/512);
63 
64 	SAFE_CLOSE(file_fd);
65 	tst_detach_device_by_fd(dev_path, dev_fd);
66 	unlink("test.img");
67 	attach_flag = 0;
68 }
69 
setup(void)70 static void setup(void)
71 {
72 	dev_num = tst_find_free_loopdev(dev_path, sizeof(dev_path));
73 	if (dev_num < 0)
74 		tst_brk(TBROK, "Failed to find free loop device");
75 
76 	wrbuf = SAFE_MALLOC(OLD_SIZE);
77 	memset(wrbuf, 'x', OLD_SIZE);
78 	sprintf(sys_loop_sizepath, "/sys/block/loop%d/size", dev_num);
79 	dev_fd = SAFE_OPEN(dev_path, O_RDWR);
80 }
81 
cleanup(void)82 static void cleanup(void)
83 {
84 	if (dev_fd > 0)
85 		SAFE_CLOSE(dev_fd);
86 	if (file_fd > 0)
87 		SAFE_CLOSE(file_fd);
88 	if (wrbuf)
89 		free(wrbuf);
90 	if (attach_flag)
91 		tst_detach_device(dev_path);
92 }
93 
94 static struct tst_test test = {
95 	.setup = setup,
96 	.cleanup = cleanup,
97 	.test_all = verify_ioctl_loop,
98 	.needs_root = 1,
99 	.needs_tmpdir = 1,
100 	.needs_drivers = (const char *const []) {
101 		"loop",
102 		NULL
103 	}
104 };
105