]> git.ipfire.org Git - thirdparty/util-linux.git/blame - sys-utils/fstrim.c
Merge branch 'setpriv-example' of https://github.com/yrro/util-linux
[thirdparty/util-linux.git] / sys-utils / fstrim.c
CommitLineData
d9e2d0dd
LC
1/*
2 * fstrim.c -- discard the part (or whole) of mounted filesystem.
3 *
fce05e96 4 * Copyright (C) 2010 Red Hat, Inc. All rights reserved.
d9e2d0dd
LC
5 * Written by Lukas Czerner <lczerner@redhat.com>
6 * Karel Zak <kzak@redhat.com>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 *
22 * This program uses FITRIM ioctl to discard parts or the whole filesystem
23 * online (mounted). You can specify range (start and length) to be
e3d61a45 24 * discarded, or simply discard whole filesystem.
d9e2d0dd 25 */
fce05e96 26
d9e2d0dd
LC
27#include <string.h>
28#include <unistd.h>
29#include <stdlib.h>
30#include <stdio.h>
31#include <stdint.h>
32#include <fcntl.h>
33#include <limits.h>
34#include <getopt.h>
d9e2d0dd
LC
35
36#include <sys/ioctl.h>
37#include <sys/stat.h>
38#include <linux/fs.h>
39
40#include "nls.h"
41#include "strutils.h"
eb76ca98 42#include "c.h"
efb8854f 43#include "closestream.h"
36c370cb
KZ
44#include "pathnames.h"
45#include "sysfs.h"
36c370cb
KZ
46
47#include <libmount.h>
d9e2d0dd
LC
48
49#ifndef FITRIM
50struct fstrim_range {
51 uint64_t start;
52 uint64_t len;
53 uint64_t minlen;
54};
fce05e96 55#define FITRIM _IOWR('X', 121, struct fstrim_range)
d9e2d0dd
LC
56#endif
57
36c370cb
KZ
58/* returns: 0 = success, 1 = unsupported, < 0 = error */
59static int fstrim_filesystem(const char *path, struct fstrim_range *rangetpl,
60 int verbose)
61{
ee24ab6f 62 int fd, rc;
36c370cb
KZ
63 struct stat sb;
64 struct fstrim_range range;
65
66 /* kernel modifies the range */
67 memcpy(&range, rangetpl, sizeof(range));
68
e612ead9
SK
69 fd = open(path, O_RDONLY);
70 if (fd < 0) {
71 warn(_("cannot open %s"), path);
289b1533
KZ
72 rc = -errno;
73 goto done;
e612ead9
SK
74 }
75 if (fstat(fd, &sb) == -1) {
fc14ceba 76 warn(_("stat of %s failed"), path);
289b1533
KZ
77 rc = -errno;
78 goto done;
36c370cb
KZ
79 }
80 if (!S_ISDIR(sb.st_mode)) {
81 warnx(_("%s: not a directory"), path);
289b1533
KZ
82 rc = -EINVAL;
83 goto done;
36c370cb 84 }
36c370cb
KZ
85 errno = 0;
86 if (ioctl(fd, FITRIM, &range)) {
289b1533 87 rc = errno == EOPNOTSUPP || errno == ENOTTY ? 1 : -errno;
36c370cb
KZ
88
89 if (rc != 1)
90 warn(_("%s: FITRIM ioctl failed"), path);
289b1533 91 goto done;
36c370cb
KZ
92 }
93
94 if (verbose) {
95 char *str = size_to_human_string(
96 SIZE_SUFFIX_3LETTER | SIZE_SUFFIX_SPACE,
97 (uint64_t) range.len);
98 /* TRANSLATORS: The standard value here is a very large number. */
99 printf(_("%s: %s (%" PRIu64 " bytes) trimmed\n"),
100 path, str, (uint64_t) range.len);
101 free(str);
102 }
289b1533
KZ
103
104 rc = 0;
105done:
106 if (fd >= 0)
107 close(fd);
108 return rc;
36c370cb
KZ
109}
110
111static int has_discard(const char *devname, struct sysfs_cxt *wholedisk)
112{
113 struct sysfs_cxt cxt, *parent = NULL;
114 uint64_t dg = 0;
115 dev_t disk = 0, dev;
116 int rc;
117
118 dev = sysfs_devname_to_devno(devname, NULL);
119 if (!dev)
120 return 1;
121 /*
122 * This is tricky to read the info from sys/, because the queue
9e930041 123 * attributes are provided for whole devices (disk) only. We're trying
36c370cb 124 * to reuse the whole-disk sysfs context to optimize this stuff (as
0e65dcde 125 * system usually have just one disk only).
36c370cb
KZ
126 */
127 if (sysfs_devno_to_wholedisk(dev, NULL, 0, &disk) || !disk)
128 return 1;
129 if (dev != disk) {
130 if (wholedisk->devno != disk) {
131 sysfs_deinit(wholedisk);
132 if (sysfs_init(wholedisk, disk, NULL))
133 return 1;
134 }
135 parent = wholedisk;
136 }
137
138 rc = sysfs_init(&cxt, dev, parent);
139 if (!rc)
140 rc = sysfs_read_u64(&cxt, "queue/discard_granularity", &dg);
141
142 sysfs_deinit(&cxt);
143 return rc == 0 && dg > 0;
144}
145
e05a3400
KZ
146
147static int uniq_fs_target_cmp(
148 struct libmnt_table *tb __attribute__((__unused__)),
149 struct libmnt_fs *a,
150 struct libmnt_fs *b)
151{
152 return !mnt_fs_streq_target(a, mnt_fs_get_target(b));
153}
154
8dd51c18
KZ
155static int uniq_fs_source_cmp(
156 struct libmnt_table *tb __attribute__((__unused__)),
157 struct libmnt_fs *a,
158 struct libmnt_fs *b)
159{
8dd51c18
KZ
160 if (mnt_fs_is_pseudofs(a) || mnt_fs_is_netfs(a) ||
161 mnt_fs_is_pseudofs(b) || mnt_fs_is_netfs(b))
162 return 1;
163
afa382f2 164 return !mnt_fs_streq_srcpath(a, mnt_fs_get_srcpath(b));
8dd51c18
KZ
165}
166
36c370cb
KZ
167/*
168 * fstrim --all follows "mount -a" return codes:
169 *
170 * 0 = all success
171 * 32 = all failed
172 * 64 = some failed, some success
173 */
174static int fstrim_all(struct fstrim_range *rangetpl, int verbose)
175{
176 struct libmnt_fs *fs;
177 struct libmnt_iter *itr;
178 struct libmnt_table *tab;
179 struct sysfs_cxt wholedisk = UL_SYSFSCXT_EMPTY;
180 int cnt = 0, cnt_err = 0;
181
e05a3400
KZ
182 mnt_init_debug(0);
183
36c370cb
KZ
184 itr = mnt_new_iter(MNT_ITER_BACKWARD);
185 if (!itr)
8e9039af 186 err(MNT_EX_FAIL, _("failed to initialize libmount iterator"));
36c370cb
KZ
187
188 tab = mnt_new_table_from_file(_PATH_PROC_MOUNTINFO);
189 if (!tab)
8e9039af 190 err(MNT_EX_FAIL, _("failed to parse %s"), _PATH_PROC_MOUNTINFO);
36c370cb 191
8dd51c18 192 /* de-duplicate by mountpoints */
e05a3400
KZ
193 mnt_table_uniq_fs(tab, 0, uniq_fs_target_cmp);
194
c0b07485 195 /* de-duplicate by source */
155d48f5 196 mnt_table_uniq_fs(tab, MNT_UNIQ_FORWARD, uniq_fs_source_cmp);
8dd51c18 197
36c370cb
KZ
198 while (mnt_table_next_fs(tab, itr, &fs) == 0) {
199 const char *src = mnt_fs_get_srcpath(fs),
200 *tgt = mnt_fs_get_target(fs);
201 char *path;
202 int rc = 1;
203
204 if (!src || !tgt || *src != '/' ||
205 mnt_fs_is_pseudofs(fs) ||
206 mnt_fs_is_netfs(fs))
207 continue;
208
209 /* Is it really accessible mountpoint? Not all mountpoints are
9e930041 210 * accessible (maybe over mounted by another filesystem) */
36c370cb
KZ
211 path = mnt_get_mountpoint(tgt);
212 if (path && strcmp(path, tgt) == 0)
213 rc = 0;
214 free(path);
215 if (rc)
216 continue; /* overlaying mount */
217
218 if (!has_discard(src, &wholedisk))
219 continue;
220 cnt++;
221
222 /*
223 * We're able to detect that the device supports discard, but
224 * things also depend on filesystem or device mapping, for
225 * example vfat or LUKS (by default) does not support FSTRIM.
226 *
227 * This is reason why we ignore EOPNOTSUPP and ENOTTY errors
228 * from discard ioctl.
229 */
230 if (fstrim_filesystem(tgt, rangetpl, verbose) < 0)
231 cnt_err++;
232 }
233
234 sysfs_deinit(&wholedisk);
e05a3400 235 mnt_unref_table(tab);
df1a1ca0 236 mnt_free_iter(itr);
36c370cb
KZ
237
238 if (cnt && cnt == cnt_err)
8e9039af 239 return MNT_EX_FAIL; /* all failed */
36c370cb 240 if (cnt && cnt_err)
8e9039af 241 return MNT_EX_SOMEOK; /* some ok */
36c370cb
KZ
242
243 return EXIT_SUCCESS;
244}
245
6e1eda6f 246static void __attribute__((__noreturn__)) usage(void)
d9e2d0dd 247{
6e1eda6f 248 FILE *out = stdout;
47a9edbd 249 fputs(USAGE_HEADER, out);
fce05e96
KZ
250 fprintf(out,
251 _(" %s [options] <mount point>\n"), program_invocation_short_name);
451dbcfa
BS
252
253 fputs(USAGE_SEPARATOR, out);
254 fputs(_("Discard unused blocks on a mounted filesystem.\n"), out);
255
fce05e96 256 fputs(USAGE_OPTIONS, out);
d6bbe804
BS
257 fputs(_(" -a, --all trim all mounted filesystems that are supported\n"), out);
258 fputs(_(" -o, --offset <num> the offset in bytes to start discarding from\n"), out);
259 fputs(_(" -l, --length <num> the number of bytes to discard\n"), out);
260 fputs(_(" -m, --minimum <num> the minimum extent length to discard\n"), out);
a60fa93c
KZ
261 fputs(_(" -v, --verbose print number of discarded bytes\n"), out);
262
47a9edbd 263 fputs(USAGE_SEPARATOR, out);
f45f3ec3
RM
264 printf(USAGE_HELP_OPTIONS(21));
265 printf(USAGE_MAN_TAIL("fstrim(8)"));
6e1eda6f 266 exit(EXIT_SUCCESS);
d9e2d0dd
LC
267}
268
c84ed54c
KZ
269int main(int argc, char **argv)
270{
b35c3727 271 char *path = NULL;
36c370cb 272 int c, rc, verbose = 0, all = 0;
fce05e96 273 struct fstrim_range range;
c84ed54c 274
fce05e96 275 static const struct option longopts[] = {
87918040
SK
276 { "all", no_argument, NULL, 'a' },
277 { "help", no_argument, NULL, 'h' },
278 { "version", no_argument, NULL, 'V' },
279 { "offset", required_argument, NULL, 'o' },
280 { "length", required_argument, NULL, 'l' },
281 { "minimum", required_argument, NULL, 'm' },
282 { "verbose", no_argument, NULL, 'v' },
283 { NULL, 0, NULL, 0 }
d9e2d0dd
LC
284 };
285
286 setlocale(LC_ALL, "");
287 bindtextdomain(PACKAGE, LOCALEDIR);
288 textdomain(PACKAGE);
efb8854f 289 atexit(close_stdout);
d9e2d0dd 290
fce05e96
KZ
291 memset(&range, 0, sizeof(range));
292 range.len = ULLONG_MAX;
d9e2d0dd 293
36c370cb 294 while ((c = getopt_long(argc, argv, "ahVo:l:m:v", longopts, NULL)) != -1) {
d9e2d0dd 295 switch(c) {
36c370cb
KZ
296 case 'a':
297 all = 1;
298 break;
d9e2d0dd 299 case 'h':
6e1eda6f 300 usage();
d9e2d0dd 301 break;
47a9edbd
SK
302 case 'V':
303 printf(UTIL_LINUX_VERSION);
304 return EXIT_SUCCESS;
d9e2d0dd 305 case 'l':
fce05e96 306 range.len = strtosize_or_err(optarg,
28c71021 307 _("failed to parse length"));
d9e2d0dd
LC
308 break;
309 case 'o':
fce05e96 310 range.start = strtosize_or_err(optarg,
28c71021 311 _("failed to parse offset"));
d9e2d0dd
LC
312 break;
313 case 'm':
fce05e96 314 range.minlen = strtosize_or_err(optarg,
28c71021 315 _("failed to parse minimum extent length"));
d9e2d0dd
LC
316 break;
317 case 'v':
318 verbose = 1;
319 break;
320 default:
677ec86c 321 errtryhelp(EXIT_FAILURE);
d9e2d0dd
LC
322 break;
323 }
fce05e96 324 }
d9e2d0dd 325
36c370cb
KZ
326 if (!all) {
327 if (optind == argc)
328 errx(EXIT_FAILURE, _("no mountpoint specified"));
329 path = argv[optind++];
330 }
d9e2d0dd
LC
331
332 if (optind != argc) {
333 warnx(_("unexpected number of arguments"));
6e1eda6f 334 errtryhelp(EXIT_FAILURE);
d9e2d0dd
LC
335 }
336
36c370cb
KZ
337 if (all)
338 rc = fstrim_all(&range, verbose);
339 else {
340 rc = fstrim_filesystem(path, &range, verbose);
341 if (rc == 1) {
1d231190 342 warnx(_("%s: the discard operation is not supported"), path);
36c370cb
KZ
343 rc = EXIT_FAILURE;
344 }
fe98b180 345 }
36c370cb
KZ
346
347 return rc;
d9e2d0dd 348}