1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Wayne Boyer, International Business Machines Corp., 2001
4 * Copyright (c) 2019 SUSE LLC, Jozef Pupava <jpupava@suse.com>
5 */
6
7 /*
8 * Test Description:
9 * Test fsync() return value on test file
10 * fsync() has to finish within TIME_LIMIT.
11 */
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <sys/types.h>
16 #include <sys/statvfs.h>
17 #include <fcntl.h>
18 #include <sys/resource.h>
19 #include <time.h>
20 #include "tst_test.h"
21
22 #define BLOCKSIZE 8192
23 #define MAXBLKS 65536
24 #define TIME_LIMIT 120
25 #define BUF_SIZE 2048
26
27 char tempfile[40] = "";
28 char pbuf[BUF_SIZE];
29 int fd;
30 off_t max_blks = MAXBLKS;
31
32 struct statvfs stat_buf;
33
setup(void)34 static void setup(void) {
35 /* free blocks avail to non-superuser */
36 unsigned long f_bavail;
37
38 fd = SAFE_OPEN("tempfile", O_RDWR | O_CREAT | O_TRUNC, 0777);
39
40 if (fstatvfs(fd, &stat_buf) != 0) {
41 tst_brk(TBROK, "fstatvfs failed");
42 }
43
44 f_bavail = (stat_buf.f_bavail * stat_buf.f_bsize) / BLOCKSIZE;
45 if (f_bavail && (f_bavail < MAXBLKS)) {
46 max_blks = f_bavail;
47 }
48
49 #ifdef LARGEFILE
50 SAFE_FCNTL(fd, F_SETFL, O_LARGEFILE);
51 SAFE_WRITE(1, fd, pbuf, BUF_SIZE);
52 #endif
53 }
54
run(void)55 static void run(void) {
56 off_t offset;
57 int i;
58 int max_block = 0;
59 int data_blocks = 0;
60 time_t time_start, time_end;
61 double time_delta;
62 long int random_number;
63
64 random_number = rand();
65 max_block = random_number % max_blks + 1;
66 data_blocks = random_number % max_block;
67
68 for (i = 1; i <= data_blocks; i++) {
69 offset = i * ((BLOCKSIZE * max_block) / data_blocks);
70 offset -= BUF_SIZE;
71 SAFE_LSEEK(fd, offset, SEEK_SET);
72 SAFE_WRITE(1, fd, pbuf, BUF_SIZE);
73 }
74 time_start = time(0);
75
76 TEST(fsync(fd));
77
78 time_end = time(0);
79
80 if (time_end == -1) {
81 tst_res(TFAIL | TTERRNO, "getting end time failed");
82 } else if (TST_RET == -1) {
83 tst_res(TFAIL | TTERRNO, "fsync failed");
84 } else if (TST_RET != 0) {
85 tst_res(TFAIL | TTERRNO,
86 "fsync failed with unexpected return value");
87 } else if (time_end < time_start) {
88 tst_res(TFAIL,
89 "timer broken end %ld < start %ld",
90 time_end, time_start);
91 } else if ((time_delta =
92 difftime(time_end, time_start)) > TIME_LIMIT) {
93 tst_res(TFAIL,
94 "fsync took too long: %lf seconds; "
95 "max_block: %d; data_blocks: %d",
96 time_delta, max_block, data_blocks);
97 } else {
98 tst_res(TPASS,
99 "fsync succeeded in an acceptable amount of time");
100 }
101 SAFE_FTRUNCATE(fd, 0);
102 }
103
cleanup(void)104 static void cleanup(void) {
105 SAFE_CLOSE(fd);
106 }
107
108 static struct tst_test test = {
109 .test_all = run,
110 .setup = setup,
111 .cleanup = cleanup,
112 .needs_tmpdir = 1
113 };
114