]> git.ipfire.org Git - thirdparty/util-linux.git/blame - sys-utils/fstrim.c
docs: improve size arguments description in --help output
[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>
061d1a51 38#include <linux/fs.h>
a0357292 39
d9e2d0dd
LC
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 48
43abda66 49
d9e2d0dd
LC
50#ifndef FITRIM
51struct fstrim_range {
52 uint64_t start;
53 uint64_t len;
54 uint64_t minlen;
55};
fce05e96 56#define FITRIM _IOWR('X', 121, struct fstrim_range)
d9e2d0dd
LC
57#endif
58
72213916
KZ
59struct fstrim_control {
60 struct fstrim_range range;
61
62 unsigned int verbose : 1,
374baa6f 63 quiet : 1,
c5b8909f 64 fstab : 1,
72213916
KZ
65 dryrun : 1;
66};
67
f227757c
KZ
68static int is_directory(const char *path, int silent)
69{
70 struct stat sb;
71
72 if (stat(path, &sb) == -1) {
73 if (!silent)
74 warn(_("stat of %s failed"), path);
75 return 0;
76 }
77 if (!S_ISDIR(sb.st_mode)) {
78 if (!silent)
79 warnx(_("%s: not a directory"), path);
80 return 0;
81 }
82 return 1;
83}
84
36c370cb 85/* returns: 0 = success, 1 = unsupported, < 0 = error */
c5b8909f 86static int fstrim_filesystem(struct fstrim_control *ctl, const char *path, const char *devname)
36c370cb 87{
8302b200 88 int fd = -1, rc;
36c370cb 89 struct fstrim_range range;
8302b200 90 char *rpath = realpath(path, NULL);
36c370cb 91
8302b200
WS
92 if (!rpath) {
93 warn(_("cannot get realpath: %s"), path);
94 rc = -errno;
95 goto done;
96 }
36c370cb 97 /* kernel modifies the range */
72213916 98 memcpy(&range, &ctl->range, sizeof(range));
36c370cb 99
8302b200 100 fd = open(rpath, O_RDONLY);
e612ead9
SK
101 if (fd < 0) {
102 warn(_("cannot open %s"), path);
289b1533
KZ
103 rc = -errno;
104 goto done;
e612ead9 105 }
fda0e2cf 106
72213916 107 if (ctl->dryrun) {
c5b8909f
KZ
108 if (devname)
109 printf(_("%s: 0 B (dry run) trimmed on %s\n"), path, devname);
110 else
111 printf(_("%s: 0 B (dry run) trimmed\n"), path);
fda0e2cf
KZ
112 rc = 0;
113 goto done;
114 }
115
36c370cb
KZ
116 errno = 0;
117 if (ioctl(fd, FITRIM, &range)) {
374baa6f
SK
118 switch (errno) {
119 case EBADF:
120 case ENOTTY:
121 case EOPNOTSUPP:
5fcdf204
KZ
122 rc = 1;
123 break;
374baa6f
SK
124 default:
125 rc = -errno;
126 }
127 if (rc < 0)
36c370cb 128 warn(_("%s: FITRIM ioctl failed"), path);
289b1533 129 goto done;
36c370cb
KZ
130 }
131
72213916 132 if (ctl->verbose) {
36c370cb
KZ
133 char *str = size_to_human_string(
134 SIZE_SUFFIX_3LETTER | SIZE_SUFFIX_SPACE,
135 (uint64_t) range.len);
c5b8909f
KZ
136 if (devname)
137 /* TRANSLATORS: The standard value here is a very large number. */
138 printf(_("%s: %s (%" PRIu64 " bytes) trimmed on %s\n"),
139 path, str, (uint64_t) range.len, devname);
140 else
141 /* TRANSLATORS: The standard value here is a very large number. */
142 printf(_("%s: %s (%" PRIu64 " bytes) trimmed\n"),
36c370cb 143 path, str, (uint64_t) range.len);
c5b8909f 144
36c370cb
KZ
145 free(str);
146 }
289b1533
KZ
147
148 rc = 0;
149done:
150 if (fd >= 0)
151 close(fd);
8302b200 152 free(rpath);
289b1533 153 return rc;
36c370cb
KZ
154}
155
c69bd2cb 156static int has_discard(const char *devname, struct path_cxt **wholedisk)
36c370cb 157{
c69bd2cb 158 struct path_cxt *pc = NULL;
36c370cb
KZ
159 uint64_t dg = 0;
160 dev_t disk = 0, dev;
fe7d6310 161 int rc = -1, rdonly = 0;
36c370cb 162
c69bd2cb 163 dev = sysfs_devname_to_devno(devname);
36c370cb 164 if (!dev)
c69bd2cb
KZ
165 goto fail;
166
167 pc = ul_new_sysfs_path(dev, NULL, NULL);
168 if (!pc)
169 goto fail;
170
36c370cb
KZ
171 /*
172 * This is tricky to read the info from sys/, because the queue
9e930041 173 * attributes are provided for whole devices (disk) only. We're trying
36c370cb 174 * to reuse the whole-disk sysfs context to optimize this stuff (as
0e65dcde 175 * system usually have just one disk only).
36c370cb 176 */
c69bd2cb
KZ
177 rc = sysfs_blkdev_get_wholedisk(pc, NULL, 0, &disk);
178 if (rc != 0 || !disk)
179 goto fail;
180
36c370cb 181 if (dev != disk) {
c69bd2cb
KZ
182 /* Partition, try reuse whole-disk context if valid for the
183 * current device, otherwise create new context for the
184 * whole-disk.
185 */
186 if (*wholedisk && sysfs_blkdev_get_devno(*wholedisk) != disk) {
187 ul_unref_path(*wholedisk);
188 *wholedisk = NULL;
189 }
190 if (!*wholedisk) {
191 *wholedisk = ul_new_sysfs_path(disk, NULL, NULL);
192 if (!*wholedisk)
193 goto fail;
36c370cb 194 }
c69bd2cb 195 sysfs_blkdev_set_parent(pc, *wholedisk);
36c370cb
KZ
196 }
197
c69bd2cb 198 rc = ul_path_read_u64(pc, &dg, "queue/discard_granularity");
fe7d6310
KZ
199 if (!rc)
200 ul_path_scanf(pc, "ro", "%d", &rdonly);
36c370cb 201
c69bd2cb 202 ul_unref_path(pc);
fe7d6310 203 return rc == 0 && dg > 0 && rdonly == 0;
c69bd2cb
KZ
204fail:
205 ul_unref_path(pc);
206 return 1;
36c370cb
KZ
207}
208
e05a3400
KZ
209
210static int uniq_fs_target_cmp(
211 struct libmnt_table *tb __attribute__((__unused__)),
212 struct libmnt_fs *a,
213 struct libmnt_fs *b)
214{
215 return !mnt_fs_streq_target(a, mnt_fs_get_target(b));
216}
217
8dd51c18
KZ
218static int uniq_fs_source_cmp(
219 struct libmnt_table *tb __attribute__((__unused__)),
220 struct libmnt_fs *a,
221 struct libmnt_fs *b)
222{
8dd51c18
KZ
223 if (mnt_fs_is_pseudofs(a) || mnt_fs_is_netfs(a) ||
224 mnt_fs_is_pseudofs(b) || mnt_fs_is_netfs(b))
225 return 1;
226
afa382f2 227 return !mnt_fs_streq_srcpath(a, mnt_fs_get_srcpath(b));
8dd51c18
KZ
228}
229
36c370cb
KZ
230/*
231 * fstrim --all follows "mount -a" return codes:
232 *
233 * 0 = all success
234 * 32 = all failed
235 * 64 = some failed, some success
236 */
72213916 237static int fstrim_all(struct fstrim_control *ctl)
36c370cb
KZ
238{
239 struct libmnt_fs *fs;
240 struct libmnt_iter *itr;
241 struct libmnt_table *tab;
c5b8909f 242 struct libmnt_cache *cache = NULL;
c69bd2cb 243 struct path_cxt *wholedisk = NULL;
36c370cb 244 int cnt = 0, cnt_err = 0;
c5b8909f 245 const char *filename = _PATH_PROC_MOUNTINFO;
36c370cb 246
e05a3400 247 mnt_init_debug(0);
fda0e2cf 248 ul_path_init_debug();
e05a3400 249
c5b8909f
KZ
250 if (ctl->fstab)
251 filename = mnt_get_fstab_path();
252
253 tab = mnt_new_table_from_file(filename);
36c370cb 254 if (!tab)
c5b8909f 255 err(MNT_EX_FAIL, _("failed to parse %s"), filename);
36c370cb 256
8dd51c18 257 /* de-duplicate by mountpoints */
e05a3400
KZ
258 mnt_table_uniq_fs(tab, 0, uniq_fs_target_cmp);
259
c5b8909f 260 if (ctl->fstab) {
410d12e5
KZ
261 char *rootdev = NULL;
262
c5b8909f
KZ
263 cache = mnt_new_cache();
264 if (!cache)
265 err(MNT_EX_FAIL, _("failed to initialize libmount cache"));
410d12e5
KZ
266
267 /* Make sure we trim also root FS on --fstab */
268 if (mnt_table_find_target(tab, "/", MNT_ITER_FORWARD) == NULL &&
269 mnt_guess_system_root(0, cache, &rootdev) == 0) {
270
271 fs = mnt_new_fs();
272 if (!fs)
273 err(MNT_EX_FAIL, _("failed to allocate FS handler"));
274 mnt_fs_set_target(fs, "/");
275 mnt_fs_set_source(fs, rootdev);
276 mnt_fs_set_fstype(fs, "auto");
277 mnt_table_add_fs(tab, fs);
278 mnt_unref_fs(fs);
279 fs = NULL;
280 }
c5b8909f
KZ
281 }
282
402006fa
SB
283 itr = mnt_new_iter(MNT_ITER_BACKWARD);
284 if (!itr)
285 err(MNT_EX_FAIL, _("failed to initialize libmount iterator"));
286
6466959d 287 /* Remove useless entries and canonicalize the table */
36c370cb
KZ
288 while (mnt_table_next_fs(tab, itr, &fs) == 0) {
289 const char *src = mnt_fs_get_srcpath(fs),
290 *tgt = mnt_fs_get_target(fs);
36c370cb 291
402006fa
SB
292 if (!tgt || mnt_fs_is_pseudofs(fs) || mnt_fs_is_netfs(fs)) {
293 mnt_table_remove_fs(tab, fs);
c5b8909f 294 continue;
402006fa 295 }
c5b8909f 296
4080be3d 297 /* convert LABEL= (etc.) from fstab to paths */
c5b8909f 298 if (!src && cache) {
c5b8909f
KZ
299 const char *spec = mnt_fs_get_source(fs);
300
402006fa
SB
301 if (!spec) {
302 mnt_table_remove_fs(tab, fs);
c5b8909f 303 continue;
402006fa 304 }
c5b8909f 305 src = mnt_resolve_spec(spec, cache);
402006fa 306 mnt_fs_set_source(fs, src);
c5b8909f
KZ
307 }
308
402006fa
SB
309 if (!src || *src != '/') {
310 mnt_table_remove_fs(tab, fs);
36c370cb 311 continue;
402006fa
SB
312 }
313 }
402006fa
SB
314
315 /* de-duplicate by source */
316 mnt_table_uniq_fs(tab, MNT_UNIQ_FORWARD, uniq_fs_source_cmp);
317
6466959d 318 mnt_reset_iter(itr, MNT_ITER_BACKWARD);
402006fa 319
6466959d 320 /* Do FITRIM */
402006fa
SB
321 while (mnt_table_next_fs(tab, itr, &fs) == 0) {
322 const char *src = mnt_fs_get_srcpath(fs),
323 *tgt = mnt_fs_get_target(fs);
324 char *path;
325 int rc = 1;
36c370cb
KZ
326
327 /* Is it really accessible mountpoint? Not all mountpoints are
9e930041 328 * accessible (maybe over mounted by another filesystem) */
36c370cb
KZ
329 path = mnt_get_mountpoint(tgt);
330 if (path && strcmp(path, tgt) == 0)
331 rc = 0;
332 free(path);
333 if (rc)
334 continue; /* overlaying mount */
335
6466959d 336 /* FITRIM on read-only filesystem can fail, and it can fail */
f227757c 337 if (access(tgt, W_OK) != 0) {
2d22ac64
SB
338 if (errno == EROFS)
339 continue;
340 if (errno == EACCES)
341 continue;
342 }
343
f227757c
KZ
344 if (!is_directory(tgt, 1) ||
345 !has_discard(src, &wholedisk))
36c370cb
KZ
346 continue;
347 cnt++;
348
349 /*
350 * We're able to detect that the device supports discard, but
351 * things also depend on filesystem or device mapping, for
e1086439 352 * example LUKS (by default) does not support FSTRIM.
36c370cb
KZ
353 *
354 * This is reason why we ignore EOPNOTSUPP and ENOTTY errors
355 * from discard ioctl.
356 */
5fcdf204
KZ
357 rc = fstrim_filesystem(ctl, tgt, src);
358 if (rc < 0)
36c370cb 359 cnt_err++;
5fcdf204
KZ
360 else if (rc == 1 && !ctl->quiet)
361 warnx(_("%s: the discard operation is not supported"), tgt);
36c370cb 362 }
402006fa 363 mnt_free_iter(itr);
36c370cb 364
c69bd2cb 365 ul_unref_path(wholedisk);
e05a3400 366 mnt_unref_table(tab);
c5b8909f 367 mnt_unref_cache(cache);
36c370cb
KZ
368
369 if (cnt && cnt == cnt_err)
8e9039af 370 return MNT_EX_FAIL; /* all failed */
36c370cb 371 if (cnt && cnt_err)
8e9039af 372 return MNT_EX_SOMEOK; /* some ok */
36c370cb 373
7afdbb6f 374 return MNT_EX_SUCCESS;
36c370cb
KZ
375}
376
6e1eda6f 377static void __attribute__((__noreturn__)) usage(void)
d9e2d0dd 378{
6e1eda6f 379 FILE *out = stdout;
47a9edbd 380 fputs(USAGE_HEADER, out);
fce05e96
KZ
381 fprintf(out,
382 _(" %s [options] <mount point>\n"), program_invocation_short_name);
451dbcfa
BS
383
384 fputs(USAGE_SEPARATOR, out);
385 fputs(_("Discard unused blocks on a mounted filesystem.\n"), out);
386
fce05e96 387 fputs(USAGE_OPTIONS, out);
c5b8909f
KZ
388 fputs(_(" -a, --all trim all supported mounted filesystems\n"), out);
389 fputs(_(" -A, --fstab trim all supported mounted filesystems from /etc/fstab\n"), out);
d6bbe804
BS
390 fputs(_(" -o, --offset <num> the offset in bytes to start discarding from\n"), out);
391 fputs(_(" -l, --length <num> the number of bytes to discard\n"), out);
392 fputs(_(" -m, --minimum <num> the minimum extent length to discard\n"), out);
a60fa93c 393 fputs(_(" -v, --verbose print number of discarded bytes\n"), out);
f227757c 394 fputs(_(" --quiet suppress trim error messages\n"), out);
f78f2983 395 fputs(_(" -n, --dry-run does everything, but trim\n"), out);
a60fa93c 396
47a9edbd 397 fputs(USAGE_SEPARATOR, out);
f45f3ec3 398 printf(USAGE_HELP_OPTIONS(21));
f1970cc5
KZ
399
400 fputs(USAGE_ARGUMENTS, out);
401 printf(USAGE_ARG_SIZE(_("<num>")));
402
f45f3ec3 403 printf(USAGE_MAN_TAIL("fstrim(8)"));
6e1eda6f 404 exit(EXIT_SUCCESS);
d9e2d0dd
LC
405}
406
c84ed54c
KZ
407int main(int argc, char **argv)
408{
b35c3727 409 char *path = NULL;
72213916
KZ
410 int c, rc, all = 0;
411 struct fstrim_control ctl = {
412 .range = { .len = ULLONG_MAX }
413 };
374baa6f
SK
414 enum {
415 OPT_QUIET = CHAR_MAX + 1
416 };
c84ed54c 417
fce05e96 418 static const struct option longopts[] = {
87918040 419 { "all", no_argument, NULL, 'a' },
c5b8909f 420 { "fstab", no_argument, NULL, 'A' },
87918040
SK
421 { "help", no_argument, NULL, 'h' },
422 { "version", no_argument, NULL, 'V' },
423 { "offset", required_argument, NULL, 'o' },
424 { "length", required_argument, NULL, 'l' },
425 { "minimum", required_argument, NULL, 'm' },
426 { "verbose", no_argument, NULL, 'v' },
374baa6f 427 { "quiet", no_argument, NULL, OPT_QUIET },
26b6525a 428 { "dry-run", no_argument, NULL, 'n' },
87918040 429 { NULL, 0, NULL, 0 }
d9e2d0dd
LC
430 };
431
432 setlocale(LC_ALL, "");
433 bindtextdomain(PACKAGE, LOCALEDIR);
434 textdomain(PACKAGE);
2c308875 435 close_stdout_atexit();
d9e2d0dd 436
26b6525a 437 while ((c = getopt_long(argc, argv, "Aahl:m:no:Vv", longopts, NULL)) != -1) {
d9e2d0dd 438 switch(c) {
c5b8909f
KZ
439 case 'A':
440 ctl.fstab = 1;
441 /* fallthrough */
36c370cb
KZ
442 case 'a':
443 all = 1;
444 break;
26b6525a 445 case 'n':
72213916 446 ctl.dryrun = 1;
fda0e2cf 447 break;
d9e2d0dd 448 case 'l':
72213916 449 ctl.range.len = strtosize_or_err(optarg,
28c71021 450 _("failed to parse length"));
d9e2d0dd
LC
451 break;
452 case 'o':
72213916 453 ctl.range.start = strtosize_or_err(optarg,
28c71021 454 _("failed to parse offset"));
d9e2d0dd
LC
455 break;
456 case 'm':
72213916 457 ctl.range.minlen = strtosize_or_err(optarg,
28c71021 458 _("failed to parse minimum extent length"));
d9e2d0dd
LC
459 break;
460 case 'v':
72213916 461 ctl.verbose = 1;
d9e2d0dd 462 break;
374baa6f
SK
463 case OPT_QUIET:
464 ctl.quiet = 1;
465 break;
2c308875
KZ
466 case 'h':
467 usage();
468 case 'V':
469 print_version(EXIT_SUCCESS);
d9e2d0dd 470 default:
677ec86c 471 errtryhelp(EXIT_FAILURE);
d9e2d0dd 472 }
fce05e96 473 }
d9e2d0dd 474
36c370cb
KZ
475 if (!all) {
476 if (optind == argc)
477 errx(EXIT_FAILURE, _("no mountpoint specified"));
478 path = argv[optind++];
479 }
d9e2d0dd
LC
480
481 if (optind != argc) {
482 warnx(_("unexpected number of arguments"));
6e1eda6f 483 errtryhelp(EXIT_FAILURE);
d9e2d0dd
LC
484 }
485
36c370cb 486 if (all)
72213916 487 return fstrim_all(&ctl); /* MNT_EX_* codes */
36c370cb 488
f227757c
KZ
489 if (!is_directory(path, 0))
490 return EXIT_FAILURE;
491
c5b8909f 492 rc = fstrim_filesystem(&ctl, path, NULL);
5fcdf204 493 if (rc == 1 && !ctl.quiet)
7afdbb6f
KZ
494 warnx(_("%s: the discard operation is not supported"), path);
495
496 return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
d9e2d0dd 497}