summaryrefslogtreecommitdiffstats
path: root/src/kernel/tests/lib/tst_fill_fs.c
blob: 121dd2f2075ac100e1c8a2ab5bac99b8188f01a6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright (c) 2017 Cyril Hrubis <chrubis@suse.cz>
 */

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/statvfs.h>

#define TST_NO_DEFAULT_MAIN
#include "tst_test.h"
#include "tst_fs.h"

void tst_fill_fs(const char *path, int verbose)
{
	int i = 0;
	char file[PATH_MAX];
	char buf[4096];
	size_t len;
	ssize_t ret;
	int fd;
	struct statvfs fi;
	statvfs(path, &fi);

	for (;;) {
		len = random() % (1024 * 102400);

		snprintf(file, sizeof(file), "%s/file%i", path, i++);

		if (verbose)
			tst_res(TINFO, "Creating file %s size %zu", file, len);

		fd = open(file, O_WRONLY | O_CREAT, 0700);
		if (fd == -1) {
			if (errno != ENOSPC)
				tst_brk(TBROK | TERRNO, "open()");

			tst_res(TINFO | TERRNO, "open()");
			return;
		}

		while (len) {
			ret = write(fd, buf, MIN(len, sizeof(buf)));

			if (ret < 0) {
				/* retry on ENOSPC to make sure filesystem is really full */
				if (errno == ENOSPC && len >= fi.f_bsize/2) {
					SAFE_FSYNC(fd);
					len /= 2;
					continue;
				}

				SAFE_CLOSE(fd);

				if (errno != ENOSPC)
					tst_brk(TBROK | TERRNO, "write()");

				tst_res(TINFO | TERRNO, "write()");
				return;
			}

			len -= ret;
		}

		SAFE_CLOSE(fd);
	}
}