1/*
2 * Copyright (c) 2013-2016 Cyril Hrubis <chrubis@suse.cz>
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "test.h"
19#include "ltp_priv.h"
20#include "tst_mkfs.h"
21
22#define OPTS_MAX 32
23
24void tst_mkfs(void (cleanup_fn)(void), const char *dev,
25              const char *fs_type, const char *const fs_opts[],
26              const char *extra_opt)
27{
28	int i, pos = 1, ret;
29	char mkfs[64];
30	const char *argv[OPTS_MAX] = {mkfs};
31	char fs_opts_str[1024] = "";
32
33	if (!dev)
34		tst_brkm(TBROK, cleanup_fn, "No device specified");
35
36	if (!fs_type)
37		tst_brkm(TBROK, cleanup_fn, "No fs_type specified");
38
39	snprintf(mkfs, sizeof(mkfs), "mkfs.%s", fs_type);
40
41	if (fs_opts) {
42		for (i = 0; fs_opts[i]; i++) {
43			argv[pos++] = fs_opts[i];
44
45			if (pos + 2 > OPTS_MAX) {
46				tst_brkm(TBROK, cleanup_fn,
47				         "Too much mkfs options");
48			}
49
50			if (i)
51				strcat(fs_opts_str, " ");
52			strcat(fs_opts_str, fs_opts[i]);
53		}
54	}
55
56	argv[pos++] = dev;
57
58	if (extra_opt) {
59		argv[pos++] = extra_opt;
60
61		if (pos + 1 > OPTS_MAX) {
62			tst_brkm(TBROK, cleanup_fn,
63			         "Too much mkfs options");
64		}
65	}
66
67	argv[pos] = NULL;
68
69	tst_resm(TINFO, "Formatting %s with %s opts='%s' extra opts='%s'",
70	         dev, fs_type, fs_opts_str, extra_opt ? extra_opt : "");
71	ret = tst_run_cmd(cleanup_fn, argv, "/dev/null", NULL, 1);
72
73	switch (ret) {
74	case 0:
75	break;
76	case 255:
77		tst_brkm(TCONF, cleanup_fn,
78			 "%s not found in $PATH", mkfs);
79	default:
80		tst_brkm(TBROK, cleanup_fn,
81			 "%s failed with %i", mkfs, ret);
82	}
83}
84
85const char *tst_dev_fs_type(void)
86{
87	const char *fs_type;
88
89	fs_type = getenv("LTP_DEV_FS_TYPE");
90
91	if (fs_type)
92		return fs_type;
93
94	return DEFAULT_FS_TYPE;
95}
96
97void safe_mkfs(const int lineno, const char *fname, const char *dev,
98               const char *fs_type, const char *const fs_opts[],
99               const char *extra_opt)
100{
101	/* ignore for now, will fix once all tst_mkfs() users are converted */
102	(void)lineno;
103	(void)fname;
104
105	tst_mkfs(NULL, dev, fs_type, fs_opts, extra_opt);
106}
107