xref: /aosp_15_r20/external/ltp/lib/tst_fill_file.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) Linux Test Project, 2014-2024
4  * Copyright (c) 2013 Oracle and/or its affiliates. All Rights Reserved.
5  * Author: Stanislav Kholmanskikh <[email protected]>
6  */
7 
8 #define _GNU_SOURCE
9 #include <stdlib.h>
10 #include <fcntl.h>
11 #include "lapi/fallocate.h"
12 #include "tst_fs.h"
13 
tst_fill_fd(int fd,char pattern,size_t bs,size_t bcount)14 int tst_fill_fd(int fd, char pattern, size_t bs, size_t bcount)
15 {
16 	size_t i;
17 	char *buf;
18 
19 	/* Filling a memory buffer with provided pattern */
20 	buf = malloc(bs);
21 	if (buf == NULL)
22 		return -1;
23 
24 	for (i = 0; i < bs; i++)
25 		buf[i] = pattern;
26 
27 	/* Filling the file */
28 	for (i = 0; i < bcount; i++) {
29 		if (write(fd, buf, bs) != (ssize_t)bs) {
30 			free(buf);
31 			return -1;
32 		}
33 	}
34 
35 	free(buf);
36 
37 	return 0;
38 }
39 
tst_prealloc_size_fd(int fd,size_t bs,size_t bcount)40 int tst_prealloc_size_fd(int fd, size_t bs, size_t bcount)
41 {
42 	int ret;
43 
44 	errno = 0;
45 	ret = fallocate(fd, 0, 0, bs * bcount);
46 
47 	if (ret && errno == ENOSPC)
48 		return ret;
49 
50 	if (ret)
51 		ret = tst_fill_fd(fd, 0, bs, bcount);
52 
53 	return ret;
54 }
55 
tst_fill_file(const char * path,char pattern,size_t bs,size_t bcount)56 int tst_fill_file(const char *path, char pattern, size_t bs, size_t bcount)
57 {
58 	int fd;
59 
60 	fd = open(path, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
61 	if (fd < 0)
62 		return -1;
63 
64 	if (tst_fill_fd(fd, pattern, bs, bcount)) {
65 		close(fd);
66 		unlink(path);
67 		return -1;
68 	}
69 
70 	if (close(fd) < 0) {
71 		unlink(path);
72 
73 		return -1;
74 	}
75 
76 	return 0;
77 }
78 
tst_prealloc_file(const char * path,size_t bs,size_t bcount)79 int tst_prealloc_file(const char *path, size_t bs, size_t bcount)
80 {
81 	int fd;
82 
83 	fd = open(path, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
84 	if (fd < 0)
85 		return -1;
86 
87 	if (tst_prealloc_size_fd(fd, bs, bcount)) {
88 		close(fd);
89 		unlink(path);
90 		return -1;
91 	}
92 
93 	if (close(fd) < 0) {
94 		unlink(path);
95 		return -1;
96 	}
97 
98 	return 0;
99 }
100