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