]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/fstrim.c
tests: Fix for misc/fallocate test build failure.
[thirdparty/util-linux.git] / sys-utils / fstrim.c
1 /*
2 * fstrim.c -- discard the part (or whole) of mounted filesystem.
3 *
4 * Copyright (C) 2010 Red Hat, Inc. All rights reserved.
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
24 * discarded, or simply discard whole filesystem.
25 */
26
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>
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"
42 #include "c.h"
43 #include "closestream.h"
44 #include "pathnames.h"
45 #include "sysfs.h"
46
47 #include <libmount.h>
48
49
50 #ifndef FITRIM
51 struct fstrim_range {
52 uint64_t start;
53 uint64_t len;
54 uint64_t minlen;
55 };
56 #define FITRIM _IOWR('X', 121, struct fstrim_range)
57 #endif
58
59 struct fstrim_control {
60 struct fstrim_range range;
61
62 unsigned int verbose : 1,
63 quiet : 1,
64 fstab : 1,
65 dryrun : 1;
66 };
67
68 static 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
85 /* returns: 0 = success, 1 = unsupported, < 0 = error */
86 static int fstrim_filesystem(struct fstrim_control *ctl, const char *path, const char *devname)
87 {
88 int fd = -1, rc;
89 struct fstrim_range range;
90 char *rpath = realpath(path, NULL);
91
92 if (!rpath) {
93 warn(_("cannot get realpath: %s"), path);
94 rc = -errno;
95 goto done;
96 }
97 /* kernel modifies the range */
98 memcpy(&range, &ctl->range, sizeof(range));
99
100 fd = open(rpath, O_RDONLY);
101 if (fd < 0) {
102 warn(_("cannot open %s"), path);
103 rc = -errno;
104 goto done;
105 }
106
107 if (ctl->dryrun) {
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);
112 rc = 0;
113 goto done;
114 }
115
116 errno = 0;
117 if (ioctl(fd, FITRIM, &range)) {
118 switch (errno) {
119 case EBADF:
120 case ENOTTY:
121 case EOPNOTSUPP:
122 rc = 1;
123 break;
124 default:
125 rc = -errno;
126 }
127 if (rc < 0)
128 warn(_("%s: FITRIM ioctl failed"), path);
129 goto done;
130 }
131
132 if (ctl->verbose) {
133 char *str = size_to_human_string(
134 SIZE_SUFFIX_3LETTER | SIZE_SUFFIX_SPACE,
135 (uint64_t) range.len);
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"),
143 path, str, (uint64_t) range.len);
144
145 free(str);
146 }
147
148 rc = 0;
149 done:
150 if (fd >= 0)
151 close(fd);
152 free(rpath);
153 return rc;
154 }
155
156 static int has_discard(const char *devname, struct path_cxt **wholedisk)
157 {
158 struct path_cxt *pc = NULL;
159 uint64_t dg = 0;
160 dev_t disk = 0, dev;
161 int rc = -1, rdonly = 0;
162
163 dev = sysfs_devname_to_devno(devname);
164 if (!dev)
165 goto fail;
166
167 pc = ul_new_sysfs_path(dev, NULL, NULL);
168 if (!pc)
169 goto fail;
170
171 /*
172 * This is tricky to read the info from sys/, because the queue
173 * attributes are provided for whole devices (disk) only. We're trying
174 * to reuse the whole-disk sysfs context to optimize this stuff (as
175 * system usually have just one disk only).
176 */
177 rc = sysfs_blkdev_get_wholedisk(pc, NULL, 0, &disk);
178 if (rc != 0 || !disk)
179 goto fail;
180
181 if (dev != disk) {
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;
194 }
195 sysfs_blkdev_set_parent(pc, *wholedisk);
196 }
197
198 rc = ul_path_read_u64(pc, &dg, "queue/discard_granularity");
199 if (!rc)
200 ul_path_scanf(pc, "ro", "%d", &rdonly);
201
202 ul_unref_path(pc);
203 return rc == 0 && dg > 0 && rdonly == 0;
204 fail:
205 ul_unref_path(pc);
206 return 1;
207 }
208
209
210 static 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
218 static int uniq_fs_source_cmp(
219 struct libmnt_table *tb __attribute__((__unused__)),
220 struct libmnt_fs *a,
221 struct libmnt_fs *b)
222 {
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
227 return !mnt_fs_streq_srcpath(a, mnt_fs_get_srcpath(b));
228 }
229
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 */
237 static int fstrim_all(struct fstrim_control *ctl)
238 {
239 struct libmnt_fs *fs;
240 struct libmnt_iter *itr;
241 struct libmnt_table *tab;
242 struct libmnt_cache *cache = NULL;
243 struct path_cxt *wholedisk = NULL;
244 int cnt = 0, cnt_err = 0;
245 const char *filename = _PATH_PROC_MOUNTINFO;
246
247 mnt_init_debug(0);
248 ul_path_init_debug();
249
250 if (ctl->fstab)
251 filename = mnt_get_fstab_path();
252
253 tab = mnt_new_table_from_file(filename);
254 if (!tab)
255 err(MNT_EX_FAIL, _("failed to parse %s"), filename);
256
257 /* de-duplicate by mountpoints */
258 mnt_table_uniq_fs(tab, 0, uniq_fs_target_cmp);
259
260 if (ctl->fstab) {
261 char *rootdev = NULL;
262
263 cache = mnt_new_cache();
264 if (!cache)
265 err(MNT_EX_FAIL, _("failed to initialize libmount cache"));
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 }
281 }
282
283 itr = mnt_new_iter(MNT_ITER_BACKWARD);
284 if (!itr)
285 err(MNT_EX_FAIL, _("failed to initialize libmount iterator"));
286
287 /* Remove useless entries and canonicalize the table */
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);
291
292 if (!tgt || mnt_fs_is_pseudofs(fs) || mnt_fs_is_netfs(fs)) {
293 mnt_table_remove_fs(tab, fs);
294 continue;
295 }
296
297 /* convert LABEL= (etc.) from fstab to paths */
298 if (!src && cache) {
299 const char *spec = mnt_fs_get_source(fs);
300
301 if (!spec) {
302 mnt_table_remove_fs(tab, fs);
303 continue;
304 }
305 src = mnt_resolve_spec(spec, cache);
306 mnt_fs_set_source(fs, src);
307 }
308
309 if (!src || *src != '/') {
310 mnt_table_remove_fs(tab, fs);
311 continue;
312 }
313 }
314
315 /* de-duplicate by source */
316 mnt_table_uniq_fs(tab, MNT_UNIQ_FORWARD, uniq_fs_source_cmp);
317
318 mnt_reset_iter(itr, MNT_ITER_BACKWARD);
319
320 /* Do FITRIM */
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;
326
327 /* Is it really accessible mountpoint? Not all mountpoints are
328 * accessible (maybe over mounted by another filesystem) */
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
336 /* FITRIM on read-only filesystem can fail, and it can fail */
337 if (access(tgt, W_OK) != 0) {
338 if (errno == EROFS)
339 continue;
340 if (errno == EACCES)
341 continue;
342 }
343
344 if (!is_directory(tgt, 1) ||
345 !has_discard(src, &wholedisk))
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
352 * example LUKS (by default) does not support FSTRIM.
353 *
354 * This is reason why we ignore EOPNOTSUPP and ENOTTY errors
355 * from discard ioctl.
356 */
357 rc = fstrim_filesystem(ctl, tgt, src);
358 if (rc < 0)
359 cnt_err++;
360 else if (rc == 1 && !ctl->quiet)
361 warnx(_("%s: the discard operation is not supported"), tgt);
362 }
363 mnt_free_iter(itr);
364
365 ul_unref_path(wholedisk);
366 mnt_unref_table(tab);
367 mnt_unref_cache(cache);
368
369 if (cnt && cnt == cnt_err)
370 return MNT_EX_FAIL; /* all failed */
371 if (cnt && cnt_err)
372 return MNT_EX_SOMEOK; /* some ok */
373
374 return MNT_EX_SUCCESS;
375 }
376
377 static void __attribute__((__noreturn__)) usage(void)
378 {
379 FILE *out = stdout;
380 fputs(USAGE_HEADER, out);
381 fprintf(out,
382 _(" %s [options] <mount point>\n"), program_invocation_short_name);
383
384 fputs(USAGE_SEPARATOR, out);
385 fputs(_("Discard unused blocks on a mounted filesystem.\n"), out);
386
387 fputs(USAGE_OPTIONS, out);
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);
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);
393 fputs(_(" -v, --verbose print number of discarded bytes\n"), out);
394 fputs(_(" --quiet suppress trim error messages\n"), out);
395 fputs(_(" -n, --dry-run does everything, but trim\n"), out);
396
397 fputs(USAGE_SEPARATOR, out);
398 printf(USAGE_HELP_OPTIONS(21));
399 printf(USAGE_MAN_TAIL("fstrim(8)"));
400 exit(EXIT_SUCCESS);
401 }
402
403 int main(int argc, char **argv)
404 {
405 char *path = NULL;
406 int c, rc, all = 0;
407 struct fstrim_control ctl = {
408 .range = { .len = ULLONG_MAX }
409 };
410 enum {
411 OPT_QUIET = CHAR_MAX + 1
412 };
413
414 static const struct option longopts[] = {
415 { "all", no_argument, NULL, 'a' },
416 { "fstab", no_argument, NULL, 'A' },
417 { "help", no_argument, NULL, 'h' },
418 { "version", no_argument, NULL, 'V' },
419 { "offset", required_argument, NULL, 'o' },
420 { "length", required_argument, NULL, 'l' },
421 { "minimum", required_argument, NULL, 'm' },
422 { "verbose", no_argument, NULL, 'v' },
423 { "quiet", no_argument, NULL, OPT_QUIET },
424 { "dry-run", no_argument, NULL, 'n' },
425 { NULL, 0, NULL, 0 }
426 };
427
428 setlocale(LC_ALL, "");
429 bindtextdomain(PACKAGE, LOCALEDIR);
430 textdomain(PACKAGE);
431 close_stdout_atexit();
432
433 while ((c = getopt_long(argc, argv, "Aahl:m:no:Vv", longopts, NULL)) != -1) {
434 switch(c) {
435 case 'A':
436 ctl.fstab = 1;
437 /* fallthrough */
438 case 'a':
439 all = 1;
440 break;
441 case 'n':
442 ctl.dryrun = 1;
443 break;
444 case 'l':
445 ctl.range.len = strtosize_or_err(optarg,
446 _("failed to parse length"));
447 break;
448 case 'o':
449 ctl.range.start = strtosize_or_err(optarg,
450 _("failed to parse offset"));
451 break;
452 case 'm':
453 ctl.range.minlen = strtosize_or_err(optarg,
454 _("failed to parse minimum extent length"));
455 break;
456 case 'v':
457 ctl.verbose = 1;
458 break;
459 case OPT_QUIET:
460 ctl.quiet = 1;
461 break;
462 case 'h':
463 usage();
464 case 'V':
465 print_version(EXIT_SUCCESS);
466 default:
467 errtryhelp(EXIT_FAILURE);
468 }
469 }
470
471 if (!all) {
472 if (optind == argc)
473 errx(EXIT_FAILURE, _("no mountpoint specified"));
474 path = argv[optind++];
475 }
476
477 if (optind != argc) {
478 warnx(_("unexpected number of arguments"));
479 errtryhelp(EXIT_FAILURE);
480 }
481
482 if (all)
483 return fstrim_all(&ctl); /* MNT_EX_* codes */
484
485 if (!is_directory(path, 0))
486 return EXIT_FAILURE;
487
488 rc = fstrim_filesystem(&ctl, path, NULL);
489 if (rc == 1 && !ctl.quiet)
490 warnx(_("%s: the discard operation is not supported"), path);
491
492 return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
493 }