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_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 dev_fd = SAFE_OPEN(dev_path, O_RDWR);
67 unlink("test.img");
68 attach_flag = 0;
69 }
70
setup(void)71 static void setup(void)
72 {
73 dev_num = tst_find_free_loopdev(dev_path, sizeof(dev_path));
74 if (dev_num < 0)
75 tst_brk(TBROK, "Failed to find free loop device");
76
77 wrbuf = SAFE_MALLOC(OLD_SIZE);
78 memset(wrbuf, 'x', OLD_SIZE);
79 sprintf(sys_loop_sizepath, "/sys/block/loop%d/size", dev_num);
80 dev_fd = SAFE_OPEN(dev_path, O_RDWR);
81 }
82
cleanup(void)83 static void cleanup(void)
84 {
85 if (dev_fd > 0)
86 SAFE_CLOSE(dev_fd);
87 if (file_fd > 0)
88 SAFE_CLOSE(file_fd);
89 if (wrbuf)
90 free(wrbuf);
91 if (attach_flag)
92 tst_detach_device(dev_path);
93 }
94
95 static struct tst_test test = {
96 .setup = setup,
97 .cleanup = cleanup,
98 .test_all = verify_ioctl_loop,
99 .needs_root = 1,
100 .needs_tmpdir = 1,
101 .needs_drivers = (const char *const []) {
102 "loop",
103 NULL
104 }
105 };
106