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