summaryrefslogtreecommitdiffstats
path: root/sys-utils/fstrim.c
blob: 7634a5337e897716ae8c8433d7cd621d35e0b0ba (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*
 * fstrim.c -- discard the part (or whole) of mounted filesystem.
 *
 * Copyright (C) 2010 Red Hat, Inc. All rights reserved.
 * Written by Lukas Czerner <lczerner@redhat.com>
 *            Karel Zak <kzak@redhat.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * This program uses FITRIM ioctl to discard parts or the whole filesystem
 * online (mounted). You can specify range (start and length) to be
 * discarded, or simply discard whole filesystem.
 */

#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <limits.h>
#include <getopt.h>

#include <sys/ioctl.h>
#include <sys/stat.h>
#include <linux/fs.h>

#include "nls.h"
#include "strutils.h"
#include "c.h"
#include "closestream.h"
#include "pathnames.h"
#include "sysfs.h"
#include "exitcodes.h"

#include <libmount.h>

#ifndef FITRIM
struct fstrim_range {
	uint64_t start;
	uint64_t len;
	uint64_t minlen;
};
#define FITRIM		_IOWR('X', 121, struct fstrim_range)
#endif

/* returns: 0 = success, 1 = unsupported, < 0 = error */
static int fstrim_filesystem(const char *path, struct fstrim_range *rangetpl,
			    int verbose)
{
	int fd;
	struct stat sb;
	struct fstrim_range range;

	/* kernel modifies the range */
	memcpy(&range, rangetpl, sizeof(range));

	fd = open(path, O_RDONLY);
	if (fd < 0) {
		warn(_("cannot open %s"), path);
		return -1;
	}
	if (fstat(fd, &sb) == -1) {
		warn(_("stat failed %s"), path);
		return -1;
	}
	if (!S_ISDIR(sb.st_mode)) {
		warnx(_("%s: not a directory"), path);
		return -1;
	}
	errno = 0;
	if (ioctl(fd, FITRIM, &range)) {
		int rc = errno == EOPNOTSUPP || errno == ENOTTY ? 1 : -1;

		if (rc != 1)
			warn(_("%s: FITRIM ioctl failed"), path);
		close(fd);
		return rc;
	}

	if (verbose) {
		char *str = size_to_human_string(
				SIZE_SUFFIX_3LETTER | SIZE_SUFFIX_SPACE,
				(uint64_t) range.len);
		/* TRANSLATORS: The standard value here is a very large number. */
		printf(_("%s: %s (%" PRIu64 " bytes) trimmed\n"),
				path, str, (uint64_t) range.len);
		free(str);
	}
	close(fd);
	return 0;
}

static int has_discard(const char *devname, struct sysfs_cxt *wholedisk)
{
	struct sysfs_cxt cxt, *parent = NULL;
	uint64_t dg = 0;
	dev_t disk = 0, dev;
	int rc;

	dev = sysfs_devname_to_devno(devname, NULL);
	if (!dev)
		return 1;
	/*
	 * This is tricky to read the info from sys/, because the queue
	 * atrributes are provided for whole devices (disk) only. We're trying
	 * to reuse the whole-disk sysfs context to optimize this stuff (as
	 * system usually have just one disk only).
	 */
	if (sysfs_devno_to_wholedisk(dev, NULL, 0, &disk) || !disk)
		return 1;
	if (dev != disk) {
		if (wholedisk->devno != disk) {
			sysfs_deinit(wholedisk);
			if (sysfs_init(wholedisk, disk, NULL))
				return 1;
		}
		parent = wholedisk;
	}

	rc = sysfs_init(&cxt, dev, parent);
	if (!rc)
		rc = sysfs_read_u64(&cxt, "queue/discard_granularity", &dg);

	sysfs_deinit(&cxt);
	return rc == 0 && dg > 0;
}


static int uniq_fs_target_cmp(
		struct libmnt_table *tb __attribute__((__unused__)),
		struct libmnt_fs *a,
		struct libmnt_fs *b)
{
	return !mnt_fs_streq_target(a, mnt_fs_get_target(b));
}

/*
 * fstrim --all follows "mount -a" return codes:
 *
 * 0  = all success
 * 32 = all failed
 * 64 = some failed, some success
 */
static int fstrim_all(struct fstrim_range *rangetpl, int verbose)
{
	struct libmnt_fs *fs;
	struct libmnt_iter *itr;
	struct libmnt_table *tab;
	struct sysfs_cxt wholedisk = UL_SYSFSCXT_EMPTY;
	int cnt = 0, cnt_err = 0;

	mnt_init_debug(0);

	itr = mnt_new_iter(MNT_ITER_BACKWARD);
	if (!itr)
		err(MOUNT_EX_FAIL, _("failed to initialize libmount iterator"));

	tab = mnt_new_table_from_file(_PATH_PROC_MOUNTINFO);
	if (!tab)
		err(MOUNT_EX_FAIL, _("failed to parse %s"), _PATH_PROC_MOUNTINFO);

	/* de-duplicate the table */
	mnt_table_uniq_fs(tab, 0, uniq_fs_target_cmp);

	while (mnt_table_next_fs(tab, itr, &fs) == 0) {
		const char *src = mnt_fs_get_srcpath(fs),
			   *tgt = mnt_fs_get_target(fs);
		char *path;
		int rc = 1;

		if (!src || !tgt || *src != '/' ||
		    mnt_fs_is_pseudofs(fs) ||
		    mnt_fs_is_netfs(fs))
			continue;

		/* Is it really accessible mountpoint? Not all mountpoints are
		 * accessible (maybe over mounted by another fylesystem) */
		path = mnt_get_mountpoint(tgt);
		if (path && strcmp(path, tgt) == 0)
			rc = 0;
		free(path);
		if (rc)
			continue;	/* overlaying mount */

		if (!has_discard(src, &wholedisk))
			continue;
		cnt++;

		/*
		 * We're able to detect that the device supports discard, but
		 * things also depend on filesystem or device mapping, for
		 * example vfat or LUKS (by default) does not support FSTRIM.
		 *
		 * This is reason why we ignore EOPNOTSUPP and ENOTTY errors
		 * from discard ioctl.
		 */
		if (fstrim_filesystem(tgt, rangetpl, verbose) < 0)
		       cnt_err++;
	}

	sysfs_deinit(&wholedisk);
	mnt_unref_table(tab);
	mnt_free_iter(itr);

	if (cnt && cnt == cnt_err)
		return MOUNT_EX_FAIL;		/* all failed */
	if (cnt && cnt_err)
		return MOUNT_EX_SOMEOK;		/* some ok */

	return EXIT_SUCCESS;
}

static void __attribute__((__noreturn__)) usage(FILE *out)
{
	fputs(USAGE_HEADER, out);
	fprintf(out,
	      _(" %s [options] <mount point>\n"), program_invocation_short_name);
	fputs(USAGE_OPTIONS, out);
	fputs(_(" -a, --all           trim all mounted filesystems that are supported\n"), out);
	fputs(_(" -o, --offset <num>  the offset in bytes to start discarding from\n"), out);
	fputs(_(" -l, --length <num>  the number of bytes to discard\n"), out);
	fputs(_(" -m, --minimum <num> the minimum extent length to discard\n"), out);
	fputs(_(" -v, --verbose       print number of discarded bytes\n"), out);

	fputs(USAGE_SEPARATOR, out);
	fputs(USAGE_HELP, out);
	fputs(USAGE_VERSION, out);
	fprintf(out, USAGE_MAN_TAIL("fstrim(8)"));
	exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
}

int main(int argc, char **argv)
{
	char *path;
	int c, rc, verbose = 0, all = 0;
	struct fstrim_range range;

	static const struct option longopts[] = {
	    { "all",       0, 0, 'a' },
	    { "help",      0, 0, 'h' },
	    { "version",   0, 0, 'V' },
	    { "offset",    1, 0, 'o' },
	    { "length",    1, 0, 'l' },
	    { "minimum",   1, 0, 'm' },
	    { "verbose",   0, 0, 'v' },
	    { NULL,        0, 0, 0 }
	};

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	memset(&range, 0, sizeof(range));
	range.len = ULLONG_MAX;

	while ((c = getopt_long(argc, argv, "ahVo:l:m:v", longopts, NULL)) != -1) {
		switch(c) {
		case 'a':
			all = 1;
			break;
		case 'h':
			usage(stdout);
			break;
		case 'V':
			printf(UTIL_LINUX_VERSION);
			return EXIT_SUCCESS;
		case 'l':
			range.len = strtosize_or_err(optarg,
					_("failed to parse length"));
			break;
		case 'o':
			range.start = strtosize_or_err(optarg,
					_("failed to parse offset"));
			break;
		case 'm':
			range.minlen = strtosize_or_err(optarg,
					_("failed to parse minimum extent length"));
			break;
		case 'v':
			verbose = 1;
			break;
		default:
			usage(stderr);
			break;
		}
	}

	if (!all) {
		if (optind == argc)
			errx(EXIT_FAILURE, _("no mountpoint specified"));
		path = argv[optind++];
	}

	if (optind != argc) {
		warnx(_("unexpected number of arguments"));
		usage(stderr);
	}

	if (all)
		rc = fstrim_all(&range, verbose);
	else {
		rc = fstrim_filesystem(path, &range, verbose);
		if (rc == 1) {
			warnx(_("%s: discard operation not supported."), path);
			rc = EXIT_FAILURE;
		}
	}

	return rc;
}