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