934b340a98a23a363909f0d228378a36a36bc068
[rsync-patches.git] / preallocate.diff
1 This patch adds the --preallocate option that asks rsync to preallocate the
2 copied files.  This slows down the copy, but should reduce fragmentation on
3 systems that need that.
4
5 To use this patch, run these commands for a successful build:
6
7     patch -p1 <patches/preallocate.diff
8     ./prepare-source
9     ./configure
10     make
11
12 based-on: 2cad2e975c16725a8406c35979ea772c1661824c
13 diff --git a/compat.c b/compat.c
14 --- a/compat.c
15 +++ b/compat.c
16 @@ -34,6 +34,7 @@ extern int inplace;
17  extern int recurse;
18  extern int use_qsort;
19  extern int allow_inc_recurse;
20 +extern int preallocate_files;
21  extern int append_mode;
22  extern int fuzzy_basis;
23  extern int read_batch;
24 @@ -189,6 +190,14 @@ void setup_protocol(int f_out,int f_in)
25         if (read_batch)
26                 check_batch_flags();
27  
28 +#ifndef SUPPORT_PREALLOCATION
29 +       if (preallocate_files && !am_sender) {
30 +               rprintf(FERROR, "preallocation is not supported on this %s\n",
31 +                       am_server ? "Server" : "Client");
32 +               exit_cleanup(RERR_SYNTAX);
33 +       }
34 +#endif
35 +
36         if (protocol_version < 30) {
37                 if (append_mode == 1)
38                         append_mode = 2;
39 diff --git a/configure.ac b/configure.ac
40 --- a/configure.ac
41 +++ b/configure.ac
42 @@ -589,13 +589,49 @@ AC_CHECK_FUNCS(waitpid wait4 getcwd strdup chown chmod lchmod mknod mkfifo \
43      setlocale setmode open64 lseek64 mkstemp64 mtrace va_copy __va_copy \
44      seteuid strerror putenv iconv_open locale_charset nl_langinfo getxattr \
45      extattr_get_link sigaction sigprocmask setattrlist getgrouplist \
46 -    initgroups utimensat)
47 +    initgroups utimensat posix_fallocate)
48  
49  dnl cygwin iconv.h defines iconv_open as libiconv_open
50  if test x"$ac_cv_func_iconv_open" != x"yes"; then
51      AC_CHECK_FUNC(libiconv_open, [ac_cv_func_iconv_open=yes; AC_DEFINE(HAVE_ICONV_OPEN, 1)])
52  fi
53  
54 +dnl Preallocation stuff (also fallocate, posix_fallocate function tests above):
55 +
56 +AC_CACHE_CHECK([for useable fallocate],rsync_cv_have_fallocate,[
57 +AC_TRY_LINK([#include <fcntl.h>
58 +#include <sys/types.h>],
59 +[fallocate(0, 0, 0, 0);],
60 +rsync_cv_have_fallocate=yes,rsync_cv_have_fallocate=no)])
61 +if test x"$rsync_cv_have_fallocate" = x"yes"; then
62 +    AC_DEFINE(HAVE_FALLOCATE, 1, [Define to 1 if you have the fallocate function and it compiles and links without error])
63 +fi
64 +
65 +AC_CACHE_CHECK([for SYS_fallocate],rsync_cv_have_sys_fallocate,[
66 +AC_TRY_COMPILE([#include <sys/syscall.h>
67 +#include <sys/types.h>],
68 +[syscall(SYS_fallocate, 0, 0, (loff_t)0, (loff_t)0);],
69 +rsync_cv_have_sys_fallocate=yes,rsync_cv_have_sys_fallocate=no)])
70 +if test x"$rsync_cv_have_sys_fallocate" = x"yes"; then
71 +    AC_DEFINE(HAVE_SYS_FALLOCATE, 1, [Define to 1 if you have the SYS_fallocate syscall number])
72 +fi
73 +
74 +if test x"$ac_cv_func_posix_fallocate" = x"yes"; then
75 +    AC_MSG_CHECKING([whether posix_fallocate is efficient])
76 +    case $host_os in
77 +    *cygwin*)
78 +       AC_MSG_RESULT(yes)
79 +       AC_DEFINE(HAVE_EFFICIENT_POSIX_FALLOCATE, 1,
80 +                 [Define if posix_fallocate is efficient (Cygwin)])
81 +       ;;
82 +    *)
83 +       AC_MSG_RESULT(no)
84 +       ;;
85 +    esac
86 +fi
87 +
88 +dnl End of preallocation stuff
89 +
90  AC_CHECK_FUNCS(getpgrp tcgetpgrp)
91  if test $ac_cv_func_getpgrp = yes; then
92      AC_FUNC_GETPGRP
93 diff --git a/options.c b/options.c
94 --- a/options.c
95 +++ b/options.c
96 @@ -73,6 +73,7 @@ int remove_source_files = 0;
97  int one_file_system = 0;
98  int protocol_version = PROTOCOL_VERSION;
99  int sparse_files = 0;
100 +int preallocate_files = 0;
101  int do_compression = 0;
102  int def_compress_level = Z_DEFAULT_COMPRESSION;
103  int am_root = 0; /* 0 = normal, 1 = root, 2 = --super, -1 = --fake-super */
104 @@ -568,6 +569,7 @@ static void print_rsync_version(enum logcode f)
105         char const *links = "no ";
106         char const *iconv = "no ";
107         char const *ipv6 = "no ";
108 +       char const *preallocation = "no ";
109         STRUCT_STAT *dumstat;
110  
111  #if SUBPROTOCOL_VERSION != 0
112 @@ -601,6 +603,9 @@ static void print_rsync_version(enum logcode f)
113  #ifdef CAN_SET_SYMLINK_TIMES
114         symtimes = "";
115  #endif
116 +#ifdef SUPPORT_PREALLOCATION
117 +       preallocation = "";
118 +#endif
119  
120         rprintf(f, "%s  version %s  protocol version %d%s\n",
121                 RSYNC_NAME, RSYNC_VERSION, PROTOCOL_VERSION, subprotocol);
122 @@ -614,8 +619,8 @@ static void print_rsync_version(enum logcode f)
123                 (int)(sizeof (int64) * 8));
124         rprintf(f, "    %ssocketpairs, %shardlinks, %ssymlinks, %sIPv6, batchfiles, %sinplace,\n",
125                 got_socketpair, hardlinks, links, ipv6, have_inplace);
126 -       rprintf(f, "    %sappend, %sACLs, %sxattrs, %siconv, %ssymtimes\n",
127 -               have_inplace, acls, xattrs, iconv, symtimes);
128 +       rprintf(f, "    %sappend, %sACLs, %sxattrs, %siconv, %ssymtimes, %spreallocation\n",
129 +               have_inplace, acls, xattrs, iconv, symtimes, preallocation);
130  
131  #ifdef MAINTAINER_MODE
132         rprintf(f, "Panic Action: \"%s\"\n", get_panic_action());
133 @@ -706,6 +711,11 @@ void usage(enum logcode F)
134    rprintf(F,"     --fake-super            store/recover privileged attrs using xattrs\n");
135  #endif
136    rprintf(F," -S, --sparse                handle sparse files efficiently\n");
137 +#ifdef SUPPORT_PREALLOCATION
138 +  rprintf(F,"     --preallocate           allocate dest files before writing them\n");
139 +#else
140 +  rprintf(F,"     --preallocate           pre-allocate dest files on remote receiver\n");
141 +#endif
142    rprintf(F," -n, --dry-run               perform a trial run with no changes made\n");
143    rprintf(F," -W, --whole-file            copy files whole (without delta-xfer algorithm)\n");
144    rprintf(F," -x, --one-file-system       don't cross filesystem boundaries\n");
145 @@ -905,6 +915,7 @@ static struct poptOption long_options[] = {
146    {"sparse",          'S', POPT_ARG_VAL,    &sparse_files, 1, 0, 0 },
147    {"no-sparse",        0,  POPT_ARG_VAL,    &sparse_files, 0, 0, 0 },
148    {"no-S",             0,  POPT_ARG_VAL,    &sparse_files, 0, 0, 0 },
149 +  {"preallocate",      0,  POPT_ARG_NONE,   &preallocate_files, 0, 0, 0},
150    {"inplace",          0,  POPT_ARG_VAL,    &inplace, 1, 0, 0 },
151    {"no-inplace",       0,  POPT_ARG_VAL,    &inplace, 0, 0, 0 },
152    {"append",           0,  POPT_ARG_NONE,   0, OPT_APPEND, 0, 0 },
153 @@ -2674,6 +2685,9 @@ void server_options(char **args, int *argc_p)
154         else if (remove_source_files)
155                 args[ac++] = "--remove-sent-files";
156  
157 +       if (preallocate_files && am_sender)
158 +               args[ac++] = "--preallocate";
159 +
160         if (ac > MAX_SERVER_ARGS) { /* Not possible... */
161                 rprintf(FERROR, "argc overflow in server_options().\n");
162                 exit_cleanup(RERR_MALLOC);
163 diff --git a/receiver.c b/receiver.c
164 --- a/receiver.c
165 +++ b/receiver.c
166 @@ -44,6 +44,7 @@ extern int cleanup_got_literal;
167  extern int remove_source_files;
168  extern int append_mode;
169  extern int sparse_files;
170 +extern int preallocate_files;
171  extern int keep_partial;
172  extern int checksum_len;
173  extern int checksum_seed;
174 @@ -208,6 +209,22 @@ static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
175         char *data;
176         int32 i;
177         char *map = NULL;
178 +#ifdef SUPPORT_PREALLOCATION
179 +#ifdef PREALLOCATE_NEEDS_TRUNCATE
180 +       OFF_T preallocated_len = 0;
181 +#endif
182 +
183 +       if (preallocate_files && fd != -1 && total_size > 0) {
184 +               /* Try to preallocate enough space for file's eventual length.  Can
185 +                * reduce fragmentation on filesystems like ext4, xfs, and NTFS. */
186 +               if (do_fallocate(fd, 0, total_size) == 0) {
187 +#ifdef PREALLOCATE_NEEDS_TRUNCATE
188 +                       preallocated_len = total_size;
189 +#endif
190 +               } else
191 +                       rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(fname));
192 +       }
193 +#endif
194  
195         read_sum_head(f_in, &sum);
196  
197 @@ -322,7 +339,14 @@ static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
198                 goto report_write_error;
199  
200  #ifdef HAVE_FTRUNCATE
201 -       if (inplace && fd != -1 && do_ftruncate(fd, offset) < 0) {
202 +       /* inplace: New data could be shorter than old data.
203 +        * preallocate_files: total_size could have been an overestimate.
204 +        *     Cut off any extra preallocated zeros from dest file. */
205 +       if ((inplace
206 +#ifdef PREALLOCATE_NEEDS_TRUNCATE
207 +         || preallocated_len > offset
208 +#endif
209 +         ) && fd != -1 && do_ftruncate(fd, offset) < 0) {
210                 rsyserr(FERROR_XFER, errno, "ftruncate failed on %s",
211                         full_fname(fname));
212         }
213 diff --git a/rsync.h b/rsync.h
214 --- a/rsync.h
215 +++ b/rsync.h
216 @@ -652,6 +652,21 @@ struct ht_int64_node {
217  #define ACLS_NEED_MASK 1
218  #endif
219  
220 +#if defined HAVE_FALLOCATE || HAVE_SYS_FALLOCATE
221 +#include <linux/falloc.h>
222 +#ifdef FALLOC_FL_KEEP_SIZE
223 +#define SUPPORT_PREALLOCATION 1
224 +#elif defined HAVE_FTRUNCATE
225 +#define SUPPORT_PREALLOCATION 1
226 +#define PREALLOCATE_NEEDS_TRUNCATE 1
227 +#endif
228 +#else /* !fallocate */
229 +#if defined HAVE_EFFICIENT_POSIX_FALLOCATE && defined HAVE_FTRUNCATE
230 +#define SUPPORT_PREALLOCATION 1
231 +#define PREALLOCATE_NEEDS_TRUNCATE 1
232 +#endif
233 +#endif
234 +
235  union file_extras {
236         int32 num;
237         uint32 unum;
238 diff --git a/rsync.yo b/rsync.yo
239 --- a/rsync.yo
240 +++ b/rsync.yo
241 @@ -360,6 +360,7 @@ to the detailed description below for a complete description.  verb(
242       --super                 receiver attempts super-user activities
243       --fake-super            store/recover privileged attrs using xattrs
244   -S, --sparse                handle sparse files efficiently
245 +     --preallocate           allocate dest files before writing
246   -n, --dry-run               perform a trial run with no changes made
247   -W, --whole-file            copy files whole (w/o delta-xfer algorithm)
248   -x, --one-file-system       don't cross filesystem boundaries
249 @@ -1167,6 +1168,17 @@ NOTE: Don't use this option when the destination is a Solaris "tmpfs"
250  filesystem. It seems to have problems seeking over null regions,
251  and ends up corrupting the files.
252  
253 +dit(bf(--preallocate)) This tells the receiver to allocate each destination
254 +file to its eventual size before writing data to the file.  Rsync will only use
255 +the real filesystem-level preallocation support provided by Linux's
256 +bf(fallocate)(2) system call or Cygwin's bf(posix_fallocate)(3), not the slow
257 +glibc implementation that writes a zero byte into each block.
258 +
259 +Without this option, larger files may not be entirely contiguous on the
260 +filesystem, but with this option rsync will probably copy more slowly.  If the
261 +destination is not an extent-supporting filesystem (such as ext4, xfs, NTFS,
262 +etc.), this option may have no positive effect at all.
263 +
264  dit(bf(-n, --dry-run)) This makes rsync perform a trial run that doesn't
265  make any changes (and produces mostly the same output as a real run).  It
266  is most commonly used in combination with the bf(-v, --verbose) and/or
267 diff --git a/syscall.c b/syscall.c
268 --- a/syscall.c
269 +++ b/syscall.c
270 @@ -29,6 +29,10 @@
271  #include <sys/attr.h>
272  #endif
273  
274 +#if defined HAVE_SYS_FALLOCATE && !defined HAVE_FALLOCATE
275 +#include <sys/syscall.h>
276 +#endif
277 +
278  extern int dry_run;
279  extern int am_root;
280  extern int am_sender;
281 @@ -417,3 +421,25 @@ int do_utime(const char *fname, time_t modtime, UNUSED(uint32 mod_nsec))
282  #else
283  #error Need utimes or utime function.
284  #endif
285 +
286 +#ifdef SUPPORT_PREALLOCATION
287 +int do_fallocate(int fd, OFF_T offset, OFF_T length)
288 +{
289 +#ifdef FALLOC_FL_KEEP_SIZE
290 +#define DO_FALLOC_OPTIONS FALLOC_FL_KEEP_SIZE
291 +#else
292 +#define DO_FALLOC_OPTIONS 0
293 +#endif
294 +       RETURN_ERROR_IF(dry_run, 0);
295 +       RETURN_ERROR_IF_RO_OR_LO;
296 +#if defined HAVE_FALLOCATE
297 +       return fallocate(fd, DO_FALLOC_OPTIONS, offset, length);
298 +#elif defined HAVE_SYS_FALLOCATE
299 +       return syscall(SYS_fallocate, fd, DO_FALLOC_OPTIONS, (loff_t)offset, (loff_t)length);
300 +#elif defined HAVE_EFFICIENT_POSIX_FALLOCATE
301 +       return posix_fallocate(fd, offset, length);
302 +#else
303 +#error Coding error in SUPPORT_PREALLOCATION logic.
304 +#endif
305 +}
306 +#endif
307 diff --git a/t_stub.c b/t_stub.c
308 --- a/t_stub.c
309 +++ b/t_stub.c
310 @@ -22,6 +22,7 @@
311  #include "rsync.h"
312  
313  int modify_window = 0;
314 +int preallocate_files = 0;
315  int module_id = -1;
316  int relative_paths = 0;
317  int module_dirlen = 0;
318 diff --git a/util.c b/util.c
319 --- a/util.c
320 +++ b/util.c
321 @@ -30,6 +30,7 @@ extern int modify_window;
322  extern int relative_paths;
323  extern int preserve_times;
324  extern int preserve_xattrs;
325 +extern int preallocate_files;
326  extern char *module_dir;
327  extern unsigned int module_dirlen;
328  extern char *partial_dir;
329 @@ -315,6 +316,9 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
330         int ifd;
331         char buf[1024 * 8];
332         int len;   /* Number of bytes read into `buf'. */
333 +#ifdef PREALLOCATE_NEEDS_TRUNCATE
334 +       OFF_T preallocated_len = 0, offset = 0;
335 +#endif
336  
337         if ((ifd = do_open(source, O_RDONLY, 0)) < 0) {
338                 int save_errno = errno;
339 @@ -345,6 +349,25 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
340                 }
341         }
342  
343 +#ifdef SUPPORT_PREALLOCATION
344 +       if (preallocate_files) {
345 +               STRUCT_STAT srcst;
346 +
347 +               /* Try to preallocate enough space for file's eventual length.  Can
348 +                * reduce fragmentation on filesystems like ext4, xfs, and NTFS. */
349 +               if (do_fstat(ifd, &srcst) < 0)
350 +                       rsyserr(FWARNING, errno, "fstat %s", full_fname(source));
351 +               else if (srcst.st_size > 0) {
352 +                       if (do_fallocate(ofd, 0, srcst.st_size) == 0) {
353 +#ifdef PREALLOCATE_NEEDS_TRUNCATE
354 +                               preallocated_len = srcst.st_size;
355 +#endif
356 +                       } else
357 +                               rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(dest));
358 +               }
359 +       }
360 +#endif
361 +
362         while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
363                 if (full_write(ofd, buf, len) < 0) {
364                         int save_errno = errno;
365 @@ -354,6 +377,9 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
366                         errno = save_errno;
367                         return -1;
368                 }
369 +#ifdef PREALLOCATE_NEEDS_TRUNCATE
370 +               offset += len;
371 +#endif
372         }
373  
374         if (len < 0) {
375 @@ -370,6 +396,16 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
376                         full_fname(source));
377         }
378  
379 +#ifdef PREALLOCATE_NEEDS_TRUNCATE
380 +       /* Source file might have shrunk since we fstatted it.
381 +        * Cut off any extra preallocated zeros from dest file. */
382 +       if (offset < preallocated_len && ftruncate(ofd, offset) < 0) {
383 +               /* If we fail to truncate, the dest file may be wrong, so we
384 +                * must trigger the "partial transfer" error. */
385 +               rsyserr(FERROR_XFER, errno, "ftruncate %s", full_fname(dest));
386 +       }
387 +#endif
388 +
389         if (close(ofd) < 0) {
390                 int save_errno = errno;
391                 rsyserr(FERROR_XFER, errno, "close failed on %s",