1 /* Simplified copy_file_range with cross-device copy.
2 Copyright (C) 2018-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
24 #include <sys/types.h>
26 #include <support/support.h>
29 support_copy_file_range (int infd, __off64_t *pinoff,
30 int outfd, __off64_t *poutoff,
31 size_t length, unsigned int flags)
40 struct stat64 outstat;
41 if (fstat64 (infd, &instat) != 0 || fstat64 (outfd, &outstat) != 0)
43 if (S_ISDIR (instat.st_mode) || S_ISDIR (outstat.st_mode))
48 if (!S_ISREG (instat.st_mode) || !S_ISREG (outstat.st_mode))
50 /* We need a regular input file so that the we can seek
51 backwards in case of a write failure. */
56 /* The output descriptor must not have O_APPEND set. */
57 if (fcntl (outfd, F_GETFL) & O_APPEND)
63 /* Avoid an overflow in the result. */
64 if (length > SSIZE_MAX)
67 /* Main copying loop. The buffer size is arbitrary and is a
68 trade-off between stack size consumption, cache usage, and
69 amortization of system call overhead. */
74 size_t to_read = length;
75 if (to_read > sizeof (buf))
76 to_read = sizeof (buf);
78 /* Fill the buffer. */
81 read_count = read (infd, buf, to_read);
83 read_count = pread64 (infd, buf, to_read, *pinoff);
85 /* End of file reached prematurely. */
90 /* Report the number of bytes copied so far. */
95 *pinoff += read_count;
97 /* Write the buffer part which was read to the destination. */
98 char *end = buf + read_count;
99 for (char *p = buf; p < end; )
103 write_count = write (outfd, p, end - p);
105 write_count = pwrite64 (outfd, p, end - p, *poutoff);
108 /* Adjust the input read position to match what we have
109 written, so that the caller can pick up after the
111 size_t written = p - buf;
112 /* NB: This needs to be signed so that we can form the
113 negative value below. */
114 ssize_t overread = read_count - written;
119 /* We are on an error recovery path, so we
120 cannot deal with failure here. */
121 int save_errno = errno;
122 (void) lseek64 (infd, -overread, SEEK_CUR);
126 else /* pinoff != NULL */
129 if (copied + written > 0)
130 /* Report the number of bytes copied so far. */
131 return copied + written;
136 *poutoff += write_count;
139 copied += read_count;
140 length -= read_count;