2 * fstrim.c -- discard the part (or whole) of mounted filesystem.
4 * Copyright (C) 2010 Red Hat, Inc. All rights reserved.
5 * Written by Lukas Czerner <lczerner@redhat.com>
6 * Karel Zak <kzak@redhat.com>
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.
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.
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/>.
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.
36 #include <sys/ioctl.h>
43 #include "closestream.h"
44 #include "pathnames.h"
56 #define FITRIM _IOWR('X', 121, struct fstrim_range)
59 struct fstrim_control
{
60 struct fstrim_range range
;
62 unsigned int verbose
: 1,
67 /* returns: 0 = success, 1 = unsupported, < 0 = error */
68 static int fstrim_filesystem(struct fstrim_control
*ctl
, const char *path
, const char *devname
)
72 struct fstrim_range range
;
74 /* kernel modifies the range */
75 memcpy(&range
, &ctl
->range
, sizeof(range
));
77 fd
= open(path
, O_RDONLY
);
79 warn(_("cannot open %s"), path
);
83 if (fstat(fd
, &sb
) == -1) {
84 warn(_("stat of %s failed"), path
);
88 if (!S_ISDIR(sb
.st_mode
)) {
89 warnx(_("%s: not a directory"), path
);
96 printf(_("%s: 0 B (dry run) trimmed on %s\n"), path
, devname
);
98 printf(_("%s: 0 B (dry run) trimmed\n"), path
);
104 if (ioctl(fd
, FITRIM
, &range
)) {
105 rc
= errno
== EOPNOTSUPP
|| errno
== ENOTTY
? 1 : -errno
;
108 warn(_("%s: FITRIM ioctl failed"), path
);
113 char *str
= size_to_human_string(
114 SIZE_SUFFIX_3LETTER
| SIZE_SUFFIX_SPACE
,
115 (uint64_t) range
.len
);
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
);
121 /* TRANSLATORS: The standard value here is a very large number. */
122 printf(_("%s: %s (%" PRIu64
" bytes) trimmed\n"),
123 path
, str
, (uint64_t) range
.len
);
135 static int has_discard(const char *devname
, struct path_cxt
**wholedisk
)
137 struct path_cxt
*pc
= NULL
;
142 dev
= sysfs_devname_to_devno(devname
);
146 pc
= ul_new_sysfs_path(dev
, NULL
, NULL
);
151 * This is tricky to read the info from sys/, because the queue
152 * attributes are provided for whole devices (disk) only. We're trying
153 * to reuse the whole-disk sysfs context to optimize this stuff (as
154 * system usually have just one disk only).
156 rc
= sysfs_blkdev_get_wholedisk(pc
, NULL
, 0, &disk
);
157 if (rc
!= 0 || !disk
)
161 /* Partition, try reuse whole-disk context if valid for the
162 * current device, otherwise create new context for the
165 if (*wholedisk
&& sysfs_blkdev_get_devno(*wholedisk
) != disk
) {
166 ul_unref_path(*wholedisk
);
170 *wholedisk
= ul_new_sysfs_path(disk
, NULL
, NULL
);
174 sysfs_blkdev_set_parent(pc
, *wholedisk
);
177 rc
= ul_path_read_u64(pc
, &dg
, "queue/discard_granularity");
180 return rc
== 0 && dg
> 0;
187 static int uniq_fs_target_cmp(
188 struct libmnt_table
*tb
__attribute__((__unused__
)),
192 return !mnt_fs_streq_target(a
, mnt_fs_get_target(b
));
195 static int uniq_fs_source_cmp(
196 struct libmnt_table
*tb
__attribute__((__unused__
)),
200 if (mnt_fs_is_pseudofs(a
) || mnt_fs_is_netfs(a
) ||
201 mnt_fs_is_pseudofs(b
) || mnt_fs_is_netfs(b
))
204 return !mnt_fs_streq_srcpath(a
, mnt_fs_get_srcpath(b
));
208 * fstrim --all follows "mount -a" return codes:
212 * 64 = some failed, some success
214 static int fstrim_all(struct fstrim_control
*ctl
)
216 struct libmnt_fs
*fs
;
217 struct libmnt_iter
*itr
;
218 struct libmnt_table
*tab
;
219 struct libmnt_cache
*cache
= NULL
;
220 struct path_cxt
*wholedisk
= NULL
;
221 int cnt
= 0, cnt_err
= 0;
222 const char *filename
= _PATH_PROC_MOUNTINFO
;
225 ul_path_init_debug();
227 itr
= mnt_new_iter(MNT_ITER_BACKWARD
);
229 err(MNT_EX_FAIL
, _("failed to initialize libmount iterator"));
232 filename
= mnt_get_fstab_path();
234 tab
= mnt_new_table_from_file(filename
);
236 err(MNT_EX_FAIL
, _("failed to parse %s"), filename
);
238 /* de-duplicate by mountpoints */
239 mnt_table_uniq_fs(tab
, 0, uniq_fs_target_cmp
);
241 /* de-duplicate by source */
242 mnt_table_uniq_fs(tab
, MNT_UNIQ_FORWARD
, uniq_fs_source_cmp
);
245 cache
= mnt_new_cache();
247 err(MNT_EX_FAIL
, _("failed to initialize libmount cache"));
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
);
256 if (!tgt
|| mnt_fs_is_pseudofs(fs
) || mnt_fs_is_netfs(fs
))
260 /* convert LABEL= (etc.) from fstab to paths */
261 const char *spec
= mnt_fs_get_source(fs
);
265 src
= mnt_resolve_spec(spec
, cache
);
268 if (!src
|| *src
!= '/')
271 /* Is it really accessible mountpoint? Not all mountpoints are
272 * accessible (maybe over mounted by another filesystem) */
273 path
= mnt_get_mountpoint(tgt
);
274 if (path
&& strcmp(path
, tgt
) == 0)
278 continue; /* overlaying mount */
280 if (!has_discard(src
, &wholedisk
))
285 * We're able to detect that the device supports discard, but
286 * things also depend on filesystem or device mapping, for
287 * example LUKS (by default) does not support FSTRIM.
289 * This is reason why we ignore EOPNOTSUPP and ENOTTY errors
290 * from discard ioctl.
292 if (fstrim_filesystem(ctl
, tgt
, src
) < 0)
296 ul_unref_path(wholedisk
);
297 mnt_unref_table(tab
);
299 mnt_unref_cache(cache
);
301 if (cnt
&& cnt
== cnt_err
)
302 return MNT_EX_FAIL
; /* all failed */
304 return MNT_EX_SOMEOK
; /* some ok */
306 return MNT_EX_SUCCESS
;
309 static void __attribute__((__noreturn__
)) usage(void)
312 fputs(USAGE_HEADER
, out
);
314 _(" %s [options] <mount point>\n"), program_invocation_short_name
);
316 fputs(USAGE_SEPARATOR
, out
);
317 fputs(_("Discard unused blocks on a mounted filesystem.\n"), out
);
319 fputs(USAGE_OPTIONS
, out
);
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
);
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
);
325 fputs(_(" -v, --verbose print number of discarded bytes\n"), out
);
326 fputs(_(" -n, --dry-run does everything, but trim\n"), out
);
328 fputs(USAGE_SEPARATOR
, out
);
329 printf(USAGE_HELP_OPTIONS(21));
330 printf(USAGE_MAN_TAIL("fstrim(8)"));
334 int main(int argc
, char **argv
)
338 struct fstrim_control ctl
= {
339 .range
= { .len
= ULLONG_MAX
}
342 static const struct option longopts
[] = {
343 { "all", no_argument
, NULL
, 'a' },
344 { "fstab", no_argument
, NULL
, 'A' },
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' },
351 { "dry-run", no_argument
, NULL
, 'n' },
355 setlocale(LC_ALL
, "");
356 bindtextdomain(PACKAGE
, LOCALEDIR
);
358 atexit(close_stdout
);
360 while ((c
= getopt_long(argc
, argv
, "Aahl:m:no:Vv", longopts
, NULL
)) != -1) {
375 printf(UTIL_LINUX_VERSION
);
378 ctl
.range
.len
= strtosize_or_err(optarg
,
379 _("failed to parse length"));
382 ctl
.range
.start
= strtosize_or_err(optarg
,
383 _("failed to parse offset"));
386 ctl
.range
.minlen
= strtosize_or_err(optarg
,
387 _("failed to parse minimum extent length"));
393 errtryhelp(EXIT_FAILURE
);
400 errx(EXIT_FAILURE
, _("no mountpoint specified"));
401 path
= argv
[optind
++];
404 if (optind
!= argc
) {
405 warnx(_("unexpected number of arguments"));
406 errtryhelp(EXIT_FAILURE
);
410 return fstrim_all(&ctl
); /* MNT_EX_* codes */
412 rc
= fstrim_filesystem(&ctl
, path
, NULL
);
414 warnx(_("%s: the discard operation is not supported"), path
);
416 return rc
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;