]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/fallocate.c
misc: consolidate version printing and close_stdout()
[thirdparty/util-linux.git] / sys-utils / fallocate.c
1 /*
2 * fallocate - utility to use the fallocate system call
3 *
4 * Copyright (C) 2008-2009 Red Hat, Inc. All rights reserved.
5 * Written by Eric Sandeen <sandeen@redhat.com>
6 * Karel Zak <kzak@redhat.com>
7 *
8 * cvtnum routine taken from xfsprogs,
9 * Copyright (c) 2003-2005 Silicon Graphics, Inc.
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License as
13 * published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it would be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 */
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <sys/mman.h>
27 #include <ctype.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <getopt.h>
34 #include <limits.h>
35 #include <string.h>
36
37 #ifndef HAVE_FALLOCATE
38 # include <sys/syscall.h>
39 #endif
40
41 #if defined(HAVE_LINUX_FALLOC_H) && \
42 (!defined(FALLOC_FL_KEEP_SIZE) || !defined(FALLOC_FL_PUNCH_HOLE) || \
43 !defined(FALLOC_FL_COLLAPSE_RANGE) || !defined(FALLOC_FL_ZERO_RANGE) || \
44 !defined(FALLOC_FL_INSERT_RANGE))
45 # include <linux/falloc.h> /* non-libc fallback for FALLOC_FL_* flags */
46 #endif
47
48
49 #ifndef FALLOC_FL_KEEP_SIZE
50 # define FALLOC_FL_KEEP_SIZE 0x1
51 #endif
52
53 #ifndef FALLOC_FL_PUNCH_HOLE
54 # define FALLOC_FL_PUNCH_HOLE 0x2
55 #endif
56
57 #ifndef FALLOC_FL_COLLAPSE_RANGE
58 # define FALLOC_FL_COLLAPSE_RANGE 0x8
59 #endif
60
61 #ifndef FALLOC_FL_ZERO_RANGE
62 # define FALLOC_FL_ZERO_RANGE 0x10
63 #endif
64
65 #ifndef FALLOC_FL_INSERT_RANGE
66 # define FALLOC_FL_INSERT_RANGE 0x20
67 #endif
68
69 #include "nls.h"
70 #include "strutils.h"
71 #include "c.h"
72 #include "closestream.h"
73 #include "xalloc.h"
74 #include "optutils.h"
75
76 static int verbose;
77 static char *filename;
78
79 static void __attribute__((__noreturn__)) usage(void)
80 {
81 FILE *out = stdout;
82 fputs(USAGE_HEADER, out);
83 fprintf(out,
84 _(" %s [options] <filename>\n"), program_invocation_short_name);
85
86 fputs(USAGE_SEPARATOR, out);
87 fputs(_("Preallocate space to, or deallocate space from a file.\n"), out);
88
89 fputs(USAGE_OPTIONS, out);
90 fputs(_(" -c, --collapse-range remove a range from the file\n"), out);
91 fputs(_(" -d, --dig-holes detect zeroes and replace with holes\n"), out);
92 fputs(_(" -i, --insert-range insert a hole at range, shifting existing data\n"), out);
93 fputs(_(" -l, --length <num> length for range operations, in bytes\n"), out);
94 fputs(_(" -n, --keep-size maintain the apparent size of the file\n"), out);
95 fputs(_(" -o, --offset <num> offset for range operations, in bytes\n"), out);
96 fputs(_(" -p, --punch-hole replace a range with a hole (implies -n)\n"), out);
97 fputs(_(" -z, --zero-range zero and ensure allocation of a range\n"), out);
98 #ifdef HAVE_POSIX_FALLOCATE
99 fputs(_(" -x, --posix use posix_fallocate(3) instead of fallocate(2)\n"), out);
100 #endif
101 fputs(_(" -v, --verbose verbose mode\n"), out);
102
103 fputs(USAGE_SEPARATOR, out);
104 printf(USAGE_HELP_OPTIONS(22));
105
106 printf(USAGE_MAN_TAIL("fallocate(1)"));
107
108 exit(EXIT_SUCCESS);
109 }
110
111 static loff_t cvtnum(char *s)
112 {
113 uintmax_t x;
114
115 if (strtosize(s, &x))
116 return -1LL;
117
118 return x;
119 }
120
121 static void xfallocate(int fd, int mode, off_t offset, off_t length)
122 {
123 int error;
124
125 #ifdef HAVE_FALLOCATE
126 error = fallocate(fd, mode, offset, length);
127 #else
128 error = syscall(SYS_fallocate, fd, mode, offset, length);
129 #endif
130 /*
131 * EOPNOTSUPP: The FALLOC_FL_KEEP_SIZE is unsupported
132 * ENOSYS: The filesystem does not support sys_fallocate
133 */
134 if (error < 0) {
135 if ((mode & FALLOC_FL_KEEP_SIZE) && errno == EOPNOTSUPP)
136 errx(EXIT_FAILURE, _("fallocate failed: keep size mode is unsupported"));
137 err(EXIT_FAILURE, _("fallocate failed"));
138 }
139 }
140
141 #ifdef HAVE_POSIX_FALLOCATE
142 static void xposix_fallocate(int fd, off_t offset, off_t length)
143 {
144 int error = posix_fallocate(fd, offset, length);
145 if (error < 0) {
146 err(EXIT_FAILURE, _("fallocate failed"));
147 }
148 }
149 #endif
150
151 /* The real buffer size has to be bufsize + sizeof(uintptr_t) */
152 static int is_nul(void *buf, size_t bufsize)
153 {
154 typedef uintptr_t word;
155 void const *vp;
156 char const *cbuf = buf, *cp;
157 word const *wp = buf;
158
159 /* set sentinel */
160 memset((char *) buf + bufsize, '\1', sizeof(word));
161
162 /* Find first nonzero *word*, or the word with the sentinel. */
163 while (*wp++ == 0)
164 continue;
165
166 /* Find the first nonzero *byte*, or the sentinel. */
167 vp = wp - 1;
168 cp = vp;
169
170 while (*cp++ == 0)
171 continue;
172
173 return cbuf + bufsize < cp;
174 }
175
176 static void dig_holes(int fd, off_t file_off, off_t len)
177 {
178 off_t file_end = len ? file_off + len : 0;
179 off_t hole_start = 0, hole_sz = 0;
180 uintmax_t ct = 0;
181 size_t bufsz;
182 char *buf;
183 struct stat st;
184 #if defined(POSIX_FADV_SEQUENTIAL) && defined(HAVE_POSIX_FADVISE)
185 off_t cache_start = file_off;
186 /*
187 * We don't want to call POSIX_FADV_DONTNEED to discard cached
188 * data in PAGE_SIZE steps. IMHO it's overkill (too many syscalls).
189 *
190 * Let's assume that 1MiB (on system with 4K page size) is just
191 * a good compromise.
192 * -- kzak Feb-2014
193 */
194 const size_t cachesz = getpagesize() * 256;
195 #endif
196
197 if (fstat(fd, &st) != 0)
198 err(EXIT_FAILURE, _("stat of %s failed"), filename);
199
200 bufsz = st.st_blksize;
201
202 if (lseek(fd, file_off, SEEK_SET) < 0)
203 err(EXIT_FAILURE, _("seek on %s failed"), filename);
204
205 /* buffer + extra space for is_nul() sentinel */
206 buf = xmalloc(bufsz + sizeof(uintptr_t));
207 while (file_end == 0 || file_off < file_end) {
208 /*
209 * Detect data area (skip holes)
210 */
211 off_t end, off;
212
213 off = lseek(fd, file_off, SEEK_DATA);
214 if ((off == -1 && errno == ENXIO) ||
215 (file_end && off >= file_end))
216 break;
217
218 end = lseek(fd, off, SEEK_HOLE);
219 if (file_end && end > file_end)
220 end = file_end;
221
222 #if defined(POSIX_FADV_SEQUENTIAL) && defined(HAVE_POSIX_FADVISE)
223 posix_fadvise(fd, off, end, POSIX_FADV_SEQUENTIAL);
224 #endif
225 /*
226 * Dig holes in the area
227 */
228 while (off < end) {
229 ssize_t rsz = pread(fd, buf, bufsz, off);
230 if (rsz < 0 && errno)
231 err(EXIT_FAILURE, _("%s: read failed"), filename);
232 if (end && rsz > 0 && off > end - rsz)
233 rsz = end - off;
234 if (rsz <= 0)
235 break;
236
237 if (is_nul(buf, rsz)) {
238 if (!hole_sz) /* new hole detected */
239 hole_start = off;
240 hole_sz += rsz;
241 } else if (hole_sz) {
242 xfallocate(fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE,
243 hole_start, hole_sz);
244 ct += hole_sz;
245 hole_sz = hole_start = 0;
246 }
247
248 #if defined(POSIX_FADV_DONTNEED) && defined(HAVE_POSIX_FADVISE)
249 /* discard cached data */
250 if (off - cache_start > (off_t) cachesz) {
251 size_t clen = off - cache_start;
252
253 clen = (clen / cachesz) * cachesz;
254 posix_fadvise(fd, cache_start, clen, POSIX_FADV_DONTNEED);
255 cache_start = cache_start + clen;
256 }
257 #endif
258 off += rsz;
259 }
260 if (hole_sz) {
261 xfallocate(fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE,
262 hole_start, hole_sz);
263 ct += hole_sz;
264 }
265 file_off = off;
266 }
267
268 free(buf);
269
270 if (verbose) {
271 char *str = size_to_human_string(SIZE_SUFFIX_3LETTER | SIZE_SUFFIX_SPACE, ct);
272 fprintf(stdout, _("%s: %s (%ju bytes) converted to sparse holes.\n"),
273 filename, str, ct);
274 free(str);
275 }
276 }
277
278 int main(int argc, char **argv)
279 {
280 int c;
281 int fd;
282 int mode = 0;
283 int dig = 0;
284 int posix = 0;
285 loff_t length = -2LL;
286 loff_t offset = 0;
287
288 static const struct option longopts[] = {
289 { "help", no_argument, NULL, 'h' },
290 { "version", no_argument, NULL, 'V' },
291 { "keep-size", no_argument, NULL, 'n' },
292 { "punch-hole", no_argument, NULL, 'p' },
293 { "collapse-range", no_argument, NULL, 'c' },
294 { "dig-holes", no_argument, NULL, 'd' },
295 { "insert-range", no_argument, NULL, 'i' },
296 { "zero-range", no_argument, NULL, 'z' },
297 { "offset", required_argument, NULL, 'o' },
298 { "length", required_argument, NULL, 'l' },
299 { "posix", no_argument, NULL, 'x' },
300 { "verbose", no_argument, NULL, 'v' },
301 { NULL, 0, NULL, 0 }
302 };
303
304 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
305 { 'c', 'd', 'p', 'z' },
306 { 'c', 'n' },
307 { 'x', 'c', 'd', 'i', 'n', 'p', 'z'},
308 { 0 }
309 };
310 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
311
312 setlocale(LC_ALL, "");
313 bindtextdomain(PACKAGE, LOCALEDIR);
314 textdomain(PACKAGE);
315 close_stdout_atexit();
316
317 while ((c = getopt_long(argc, argv, "hvVncpdizxl:o:", longopts, NULL))
318 != -1) {
319
320 err_exclusive_options(c, longopts, excl, excl_st);
321
322 switch(c) {
323 case 'c':
324 mode |= FALLOC_FL_COLLAPSE_RANGE;
325 break;
326 case 'd':
327 dig = 1;
328 break;
329 case 'i':
330 mode |= FALLOC_FL_INSERT_RANGE;
331 break;
332 case 'l':
333 length = cvtnum(optarg);
334 break;
335 case 'n':
336 mode |= FALLOC_FL_KEEP_SIZE;
337 break;
338 case 'o':
339 offset = cvtnum(optarg);
340 break;
341 case 'p':
342 mode |= FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
343 break;
344 case 'z':
345 mode |= FALLOC_FL_ZERO_RANGE;
346 break;
347 case 'x':
348 #ifdef HAVE_POSIX_FALLOCATE
349 posix = 1;
350 break;
351 #else
352 errx(EXIT_FAILURE, _("posix_fallocate support is not compiled"));
353 #endif
354 case 'v':
355 verbose++;
356 break;
357
358 case 'h':
359 usage();
360 case 'V':
361 print_version(EXIT_SUCCESS);
362 default:
363 errtryhelp(EXIT_FAILURE);
364 }
365 }
366
367 if (optind == argc)
368 errx(EXIT_FAILURE, _("no filename specified"));
369
370 filename = argv[optind++];
371
372 if (optind != argc)
373 errx(EXIT_FAILURE, _("unexpected number of arguments"));
374
375 if (dig) {
376 /* for --dig-holes the default is analyze all file */
377 if (length == -2LL)
378 length = 0;
379 if (length < 0)
380 errx(EXIT_FAILURE, _("invalid length value specified"));
381 } else {
382 /* it's safer to require the range specification (--length --offset) */
383 if (length == -2LL)
384 errx(EXIT_FAILURE, _("no length argument specified"));
385 if (length <= 0)
386 errx(EXIT_FAILURE, _("invalid length value specified"));
387 }
388 if (offset < 0)
389 errx(EXIT_FAILURE, _("invalid offset value specified"));
390
391 /* O_CREAT makes sense only for the default fallocate(2) behavior
392 * when mode is no specified and new space is allocated */
393 fd = open(filename, O_RDWR | (!dig && !mode ? O_CREAT : 0),
394 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
395 if (fd < 0)
396 err(EXIT_FAILURE, _("cannot open %s"), filename);
397
398 if (dig)
399 dig_holes(fd, offset, length);
400 #ifdef HAVE_POSIX_FALLOCATE
401 else if (posix)
402 xposix_fallocate(fd, offset, length);
403 #endif
404 else
405 xfallocate(fd, mode, offset, length);
406
407 if (close_fd(fd) != 0)
408 err(EXIT_FAILURE, _("write failed: %s"), filename);
409
410 return EXIT_SUCCESS;
411 }