]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/fstrim.c
fstrim: Remove commnet about vfat not supporting fstrim
[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 fstab : 1,
64 dryrun : 1;
65 };
66
67 /* returns: 0 = success, 1 = unsupported, < 0 = error */
68 static int fstrim_filesystem(struct fstrim_control *ctl, const char *path, const char *devname)
69 {
70 int fd, rc;
71 struct stat sb;
72 struct fstrim_range range;
73
74 /* kernel modifies the range */
75 memcpy(&range, &ctl->range, sizeof(range));
76
77 fd = open(path, O_RDONLY);
78 if (fd < 0) {
79 warn(_("cannot open %s"), path);
80 rc = -errno;
81 goto done;
82 }
83 if (fstat(fd, &sb) == -1) {
84 warn(_("stat of %s failed"), path);
85 rc = -errno;
86 goto done;
87 }
88 if (!S_ISDIR(sb.st_mode)) {
89 warnx(_("%s: not a directory"), path);
90 rc = -EINVAL;
91 goto done;
92 }
93
94 if (ctl->dryrun) {
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);
99 rc = 0;
100 goto done;
101 }
102
103 errno = 0;
104 if (ioctl(fd, FITRIM, &range)) {
105 rc = errno == EOPNOTSUPP || errno == ENOTTY ? 1 : -errno;
106
107 if (rc != 1)
108 warn(_("%s: FITRIM ioctl failed"), path);
109 goto done;
110 }
111
112 if (ctl->verbose) {
113 char *str = size_to_human_string(
114 SIZE_SUFFIX_3LETTER | SIZE_SUFFIX_SPACE,
115 (uint64_t) range.len);
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"),
123 path, str, (uint64_t) range.len);
124
125 free(str);
126 }
127
128 rc = 0;
129 done:
130 if (fd >= 0)
131 close(fd);
132 return rc;
133 }
134
135 static int has_discard(const char *devname, struct path_cxt **wholedisk)
136 {
137 struct path_cxt *pc = NULL;
138 uint64_t dg = 0;
139 dev_t disk = 0, dev;
140 int rc = -1;
141
142 dev = sysfs_devname_to_devno(devname);
143 if (!dev)
144 goto fail;
145
146 pc = ul_new_sysfs_path(dev, NULL, NULL);
147 if (!pc)
148 goto fail;
149
150 /*
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).
155 */
156 rc = sysfs_blkdev_get_wholedisk(pc, NULL, 0, &disk);
157 if (rc != 0 || !disk)
158 goto fail;
159
160 if (dev != disk) {
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;
173 }
174 sysfs_blkdev_set_parent(pc, *wholedisk);
175 }
176
177 rc = ul_path_read_u64(pc, &dg, "queue/discard_granularity");
178
179 ul_unref_path(pc);
180 return rc == 0 && dg > 0;
181 fail:
182 ul_unref_path(pc);
183 return 1;
184 }
185
186
187 static 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
195 static int uniq_fs_source_cmp(
196 struct libmnt_table *tb __attribute__((__unused__)),
197 struct libmnt_fs *a,
198 struct libmnt_fs *b)
199 {
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
204 return !mnt_fs_streq_srcpath(a, mnt_fs_get_srcpath(b));
205 }
206
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 */
214 static int fstrim_all(struct fstrim_control *ctl)
215 {
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;
223
224 mnt_init_debug(0);
225 ul_path_init_debug();
226
227 itr = mnt_new_iter(MNT_ITER_BACKWARD);
228 if (!itr)
229 err(MNT_EX_FAIL, _("failed to initialize libmount iterator"));
230
231 if (ctl->fstab)
232 filename = mnt_get_fstab_path();
233
234 tab = mnt_new_table_from_file(filename);
235 if (!tab)
236 err(MNT_EX_FAIL, _("failed to parse %s"), filename);
237
238 /* de-duplicate by mountpoints */
239 mnt_table_uniq_fs(tab, 0, uniq_fs_target_cmp);
240
241 /* de-duplicate by source */
242 mnt_table_uniq_fs(tab, MNT_UNIQ_FORWARD, uniq_fs_source_cmp);
243
244 if (ctl->fstab) {
245 cache = mnt_new_cache();
246 if (!cache)
247 err(MNT_EX_FAIL, _("failed to initialize libmount cache"));
248 }
249
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
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 != '/')
269 continue;
270
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)
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
287 * example LUKS (by default) does not support FSTRIM.
288 *
289 * This is reason why we ignore EOPNOTSUPP and ENOTTY errors
290 * from discard ioctl.
291 */
292 if (fstrim_filesystem(ctl, tgt, src) < 0)
293 cnt_err++;
294 }
295
296 ul_unref_path(wholedisk);
297 mnt_unref_table(tab);
298 mnt_free_iter(itr);
299 mnt_unref_cache(cache);
300
301 if (cnt && cnt == cnt_err)
302 return MNT_EX_FAIL; /* all failed */
303 if (cnt && cnt_err)
304 return MNT_EX_SOMEOK; /* some ok */
305
306 return MNT_EX_SUCCESS;
307 }
308
309 static void __attribute__((__noreturn__)) usage(void)
310 {
311 FILE *out = stdout;
312 fputs(USAGE_HEADER, out);
313 fprintf(out,
314 _(" %s [options] <mount point>\n"), program_invocation_short_name);
315
316 fputs(USAGE_SEPARATOR, out);
317 fputs(_("Discard unused blocks on a mounted filesystem.\n"), out);
318
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);
327
328 fputs(USAGE_SEPARATOR, out);
329 printf(USAGE_HELP_OPTIONS(21));
330 printf(USAGE_MAN_TAIL("fstrim(8)"));
331 exit(EXIT_SUCCESS);
332 }
333
334 int main(int argc, char **argv)
335 {
336 char *path = NULL;
337 int c, rc, all = 0;
338 struct fstrim_control ctl = {
339 .range = { .len = ULLONG_MAX }
340 };
341
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' },
352 { NULL, 0, NULL, 0 }
353 };
354
355 setlocale(LC_ALL, "");
356 bindtextdomain(PACKAGE, LOCALEDIR);
357 textdomain(PACKAGE);
358 atexit(close_stdout);
359
360 while ((c = getopt_long(argc, argv, "Aahl:m:no:Vv", longopts, NULL)) != -1) {
361 switch(c) {
362 case 'A':
363 ctl.fstab = 1;
364 /* fallthrough */
365 case 'a':
366 all = 1;
367 break;
368 case 'n':
369 ctl.dryrun = 1;
370 break;
371 case 'h':
372 usage();
373 break;
374 case 'V':
375 printf(UTIL_LINUX_VERSION);
376 return EXIT_SUCCESS;
377 case 'l':
378 ctl.range.len = strtosize_or_err(optarg,
379 _("failed to parse length"));
380 break;
381 case 'o':
382 ctl.range.start = strtosize_or_err(optarg,
383 _("failed to parse offset"));
384 break;
385 case 'm':
386 ctl.range.minlen = strtosize_or_err(optarg,
387 _("failed to parse minimum extent length"));
388 break;
389 case 'v':
390 ctl.verbose = 1;
391 break;
392 default:
393 errtryhelp(EXIT_FAILURE);
394 break;
395 }
396 }
397
398 if (!all) {
399 if (optind == argc)
400 errx(EXIT_FAILURE, _("no mountpoint specified"));
401 path = argv[optind++];
402 }
403
404 if (optind != argc) {
405 warnx(_("unexpected number of arguments"));
406 errtryhelp(EXIT_FAILURE);
407 }
408
409 if (all)
410 return fstrim_all(&ctl); /* MNT_EX_* codes */
411
412 rc = fstrim_filesystem(&ctl, path, NULL);
413 if (rc == 1)
414 warnx(_("%s: the discard operation is not supported"), path);
415
416 return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
417 }