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