Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[libc++] use copy_file_range for fs::copy #109211

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Jannik2099
Copy link

Hi,

this optimizes std::filesystem::copy_file to use the copy_file_range syscall (Linux and FreeBSD) when available. It allows for reflinks on filesystems such as btrfs, zfs and xfs, and server-side copy for network filesystems such as NFS.

This behaviour is in line with Boost.Filesystem and libstdc++ (where I implemented this some time ago). It's also the default behaviour of the standard file copy operations in .NET Core, Java, and (hopefully) soon python, and in the cp program from GNU coreutils.

I don't have the opportunity to test this on FreeBSD, but I think the FreeBSD folks will want a look at this. Sadly I don't know any by name, perhaps someone could CC the relevant person(s).

As for the LIBCXX_USE_COPY_FILE_RANGE cmake check, I was unsure where to put it, and this is probably not the desired location.

Lastly I am not sure if the largefile handling (see usage of off_t) is correct.

@Jannik2099 Jannik2099 requested a review from a team as a code owner September 18, 2024 22:36
Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added the libc++ libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi. label Sep 18, 2024
@llvmbot
Copy link
Collaborator

llvmbot commented Sep 18, 2024

@llvm/pr-subscribers-libcxx

Author: Jannik Glückert (Jannik2099)

Changes

Hi,

this optimizes std::filesystem::copy_file to use the copy_file_range syscall (Linux and FreeBSD) when available. It allows for reflinks on filesystems such as btrfs, zfs and xfs, and server-side copy for network filesystems such as NFS.

This behaviour is in line with Boost.Filesystem and libstdc++ (where I implemented this some time ago). It's also the default behaviour of the standard file copy operations in .NET Core, Java, and (hopefully) soon python, and in the cp program from GNU coreutils.

I don't have the opportunity to test this on FreeBSD, but I think the FreeBSD folks will want a look at this. Sadly I don't know any by name, perhaps someone could CC the relevant person(s).

As for the LIBCXX_USE_COPY_FILE_RANGE cmake check, I was unsure where to put it, and this is probably not the desired location.

Lastly I am not sure if the largefile handling (see usage of off_t) is correct.


Full diff: https://github.com/llvm/llvm-project/pull/109211.diff

2 Files Affected:

  • (modified) libcxx/src/CMakeLists.txt (+6)
  • (modified) libcxx/src/filesystem/operations.cpp (+59-1)
diff --git a/libcxx/src/CMakeLists.txt b/libcxx/src/CMakeLists.txt
index 48c5111a0acbf6..3f97d3e730a42c 100644
--- a/libcxx/src/CMakeLists.txt
+++ b/libcxx/src/CMakeLists.txt
@@ -173,6 +173,12 @@ if (APPLE AND LLVM_USE_SANITIZER)
   endif()
 endif()
 
+include(CheckCXXSymbolExists)
+check_cxx_symbol_exists("copy_file_range" "unistd.h" LIBCXX_USE_COPY_FILE_RANGE)
+if(LIBCXX_USE_COPY_FILE_RANGE)
+  list(APPEND LIBCXX_COMPILE_FLAGS "-D_LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE")
+endif()
+
 split_list(LIBCXX_COMPILE_FLAGS)
 split_list(LIBCXX_LINK_FLAGS)
 
diff --git a/libcxx/src/filesystem/operations.cpp b/libcxx/src/filesystem/operations.cpp
index d771f200973528..42d16c0546ae10 100644
--- a/libcxx/src/filesystem/operations.cpp
+++ b/libcxx/src/filesystem/operations.cpp
@@ -32,6 +32,7 @@
 #  include <dirent.h>
 #  include <sys/stat.h>
 #  include <sys/statvfs.h>
+#  include <sys/types.h>
 #  include <unistd.h>
 #endif
 #include <fcntl.h> /* values for fchmodat */
@@ -178,8 +179,35 @@ void __copy(const path& from, const path& to, copy_options options, error_code*
 namespace detail {
 namespace {
 
+#if defined(_LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE)
+bool copy_file_impl_copy_file_range(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
+  size_t count = read_fd.get_stat().st_size;
+  // a zero-length file is either empty, or not copyable by this syscall
+  // return early to avoid the syscall cost
+  if (count == 0) {
+    ec = {EINVAL, generic_category()};
+    return false;
+  }
+  do {
+    ssize_t res;
+    // do not modify the fd positions as copy_file_impl_sendfile may be called after a partial copy
+    off_t off_in  = 0;
+    off_t off_out = 0;
+
+    if ((res = ::copy_file_range(read_fd.fd, &off_in, write_fd.fd, &off_out, count, 0)) == -1) {
+      ec = capture_errno();
+      return false;
+    }
+    count -= res;
+  } while (count > 0);
+
+  ec.clear();
+
+  return true;
+}
+#endif
 #if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
-bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
+bool copy_file_impl_sendfile(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
   size_t count = read_fd.get_stat().st_size;
   do {
     ssize_t res;
@@ -194,6 +222,36 @@ bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_cod
 
   return true;
 }
+#endif
+
+#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
+bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
+  bool has_copied = false;
+#  if defined(_LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE)
+  has_copied = copy_file_impl_copy_file_range(read_fd, write_fd, ec);
+  if (has_copied) {
+    return true;
+  }
+  // EINVAL: src and dst are the same file (this is not cheaply
+  // detectable from userspace)
+  // EINVAL: copy_file_range is unsupported for this file type by the
+  // underlying filesystem
+  // ENOTSUP: undocumented, can arise with old kernels and NFS
+  // EOPNOTSUPP: filesystem does not implement copy_file_range
+  // ETXTBSY: src or dst is an active swapfile (nonsensical, but allowed
+  // with normal copying)
+  // EXDEV: src and dst are on different filesystems that do not support
+  // cross-fs copy_file_range
+  // ENOENT: undocumented, can arise with CIFS
+  // ENOSYS: unsupported by kernel or blocked by seccomp
+  if (ec.value() != EINVAL && ec.value() != ENOTSUP && ec.value() != EOPNOTSUPP && ec.value() != ETXTBSY &&
+      ec.value() != EXDEV && ec.value() != ENOENT && ec.value() != ENOSYS) {
+    return false;
+  }
+  ec.clear();
+#  endif
+  return copy_file_impl_sendfile(read_fd, write_fd, ec);
+}
 #elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
   struct CopyFileState {

@mstorsjo
Copy link
Member

I don't have the opportunity to test this on FreeBSD, but I think the FreeBSD folks will want a look at this. Sadly I don't know any by name, perhaps someone could CC the relevant person(s).

CC @emaste

@Jannik2099 Note that the CI environment does contain a FreeBSD setup, which shows a failure (a somewhat boring one):

/home/buildkite/.buildkite-agent/builds/freebsd-test-1/llvm-project/libcxx-ci/libcxx/src/filesystem/operations.cpp:183:6: error: unused function 'copy_file_impl_copy_file_range' [-Werror,-Wunused-function]
  183 | bool copy_file_impl_copy_file_range(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
      |      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

(There are also a couple other similar failing cases in the same CI run on buildkite.)

@Jannik2099
Copy link
Author

Thanks!

Yeah, I forgot to slap on -Werror yesterday, will fix later.

Another note, how TOCTOU-safe should this be? Right now I fstat both in the copy_file_range and in the sendfile impl. If the file size changes inbetween and copy_file_range fails halfway through, this may lead to inconsistent output.

@Jannik2099
Copy link
Author

So I looked at the FreeBSD failure again...

FreeBSD does have sendfile, but it does NOT have sys/sendfile.h, which means libc++ has been doing userspace copies on FreeBSD all this time!

I'll think of a more robust check.

@Jannik2099
Copy link
Author

FreeBSD does have sendfile, but it does NOT have sys/sendfile.h, which means libc++ has been doing userspace copies on FreeBSD all this time!

so turns out that was on purpose, because FreeBSD sendfile cannot send to files - I had assumed it was one of those "ancient unix syscalls that made it's way into every OS".

I'll have to restructure this a bit then.

Unrelated, I also took the opportunity to support copying special zero-length files on linux (such as those in /proc). Funnily enough, we discovered the same deficiency in libstdc++ when I was adding copy_file_range support there.

opportunistically use copy_file_range (Linux, FreeBSD) where possible.
This allows for fast copies via reflinks,
and server side copies for network filesystems.
Fall back to sendfile if not supported.

Signed-off-by: Jannik Glückert <jannik.glueckert@gmail.com>
Virtual linux filesystems such as /proc and /sys
may contain files that appear as zero length,
but do contain data.
These require a traditional userspace read + write loop.

Signed-off-by: Jannik Glückert <jannik.glueckert@gmail.com>
@Jannik2099
Copy link
Author

Ok, I think this is ready for review now.

To summarize:

Add copy_file_range support on Linux and FreeBSD. fs::copy_file will first try copy_file_range, if unavailable and on linux sendfile, and finally the generic fstream.

This covers the following scenarios:

  • copy_file_range is not implemented by the filesystem or the OS
  • copy_file_range and/or sendfile are unable to copy to/from the source/dest in question
  • fs::copy_file is used on a special linux zero-length file, such as those in /proc - this was previously unsupported.

I have also added a test for the /proc case, there are no such files on FreeBSD to my rudimentary knowledge, so the test is linux exclusive.

I am not super happy with how copy_file_impl looks now - it's stuck halfway between doing #ifdef on (effectively) the target OS, and halfway between doing it on the available syscalls. Feel free to tear apart.

@ldionne
Copy link
Member

ldionne commented Sep 25, 2024

Please rebase onto main to re-trigger CI. The CI instability should be resolved now.

@ldionne
Copy link
Member

ldionne commented Sep 25, 2024

(I'll get to this review in my queue, for now just trying to get CI back on track)

Copy link
Member

@ldionne ldionne left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the patch and sorry for the delay! I have some comments and questions, but overall this patch looks quite good and this is definitely a nice optimization.

#include "test_macros.h"
#include "filesystem_test_helper.h"

using namespace std::filesystem;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use namespace fs = std::filesystem instead. We generally discourage using namespace foo; (I know some places in the test suite don't follow that).

// This is because the to-be-read data is usually generated ad-hoc by the reading syscall
// These files can not be copied with kernel-side copies like copy_file_range or sendfile,
// and must instead be copied via a traditional userspace read + write loop.
int main(int, char**) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: main must always explicitly return 0; in our tests, because that otherwise breaks tests under -ffreestanding (since under that flag main is not treated as a special function).

// <filesystem>

// bool copy_file(const path& from, const path& to);
// bool copy_file(const path& from, const path& to, error_code& ec) noexcept;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now, you're only testing this overload of the function. Could you update the test to test the other variants as well?

// error_code& ec) noexcept;

#include <filesystem>
#include <cassert>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing #include <system_error>.

Comment on lines +47 to +49
// a tad fragile if lit ever changes the output name,
// but the easiest way to assert that the correct data was copied.
assert(file_size(dest) == sizeof("t.tmp.exe"));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you instead derive something from argv[0]?

Comment on lines +276 to +313
#if defined(_LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE) || defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
# if defined(_LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE)
if (copy_file_impl_copy_file_range(read_fd, write_fd, ec)) {
return true;
}
// EINVAL: src and dst are the same file (this is not cheaply
// detectable from userspace)
// EINVAL: copy_file_range is unsupported for this file type by the
// underlying filesystem
// ENOTSUP: undocumented, can arise with old kernels and NFS
// EOPNOTSUPP: filesystem does not implement copy_file_range
// ETXTBSY: src or dst is an active swapfile (nonsensical, but allowed
// with normal copying)
// EXDEV: src and dst are on different filesystems that do not support
// cross-fs copy_file_range
// ENOENT: undocumented, can arise with CIFS
// ENOSYS: unsupported by kernel or blocked by seccomp
if (ec.value() != EINVAL && ec.value() != ENOTSUP && ec.value() != EOPNOTSUPP && ec.value() != ETXTBSY &&
ec.value() != EXDEV && ec.value() != ENOENT && ec.value() != ENOSYS) {
return false;
}
ec.clear();
# endif

# if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
if (copy_file_impl_sendfile(read_fd, write_fd, ec)) {
return true;
}
// EINVAL: unsupported file type
if (ec.value() != EINVAL) {
return false;
}
ec.clear();
# endif

return copy_file_impl_fstream(read_fd, write_fd, ec);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rewrite this as follows, I think that makes it easier to understand and we duplicate very little code:

#if defined(_LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE)

bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
  if (copy_file_impl_copy_file_range(read_fd, write_fd, ec)) {
    return true;
  }
  // EINVAL: src and dst are the same file (this is not cheaply
  // detectable from userspace)
  // EINVAL: copy_file_range is unsupported for this file type by the
  // underlying filesystem
  // ENOTSUP: undocumented, can arise with old kernels and NFS
  // EOPNOTSUPP: filesystem does not implement copy_file_range
  // ETXTBSY: src or dst is an active swapfile (nonsensical, but allowed
  // with normal copying)
  // EXDEV: src and dst are on different filesystems that do not support
  // cross-fs copy_file_range
  // ENOENT: undocumented, can arise with CIFS
  // ENOSYS: unsupported by kernel or blocked by seccomp
  if (ec.value() != EINVAL && ec.value() != ENOTSUP && ec.value() != EOPNOTSUPP && ec.value() != ETXTBSY &&
      ec.value() != EXDEV && ec.value() != ENOENT && ec.value() != ENOSYS) {
    return false;
  }
  ec.clear();

  return copy_file_impl_fstream(read_fd, write_fd, ec);
}

#elif defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)

bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
  if (copy_file_impl_sendfile(read_fd, write_fd, ec)) {
    return true;
  }
  // EINVAL: unsupported file type
  if (ec.value() != EINVAL) {
    return false;
  }
  ec.clear();

  return copy_file_impl_fstream(read_fd, write_fd, ec);
}
 
#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)

...

And once you rewrite like that, you could also consider inlining copy_file_impl_copy_file_range and copy_file_impl_sendfile into their respective copy_file_impl. IDK if that would simplify the code but it might.

Copy link
Author

@Jannik2099 Jannik2099 Oct 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That doesn't work, copy_file_range will (usually) fail on cross-fs copy, and we'd want to fall back to sendfile in that case, and not abandon ship and do a userspace copy.

Since only Linux and FreeBSD support copy_file_range, and only linux supports sendfile on files, perhaps something like:

#ifdef __linux__ || __FreeBSD__
copy_file_impl() {
    #ifdef HAS_COPY_FILE_RANGE
    if(copy_file_range()) { return; }
    #endif
    #ifdef HAS_SENDFILE
    if(sendfile()) { return; }
    #endif
    fstream();
}
#endif

Of course, this will get procedually more messy when another Unix platform implements any combination of copy_file_range and sendfile.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is something I don't understand. _LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE, _LIBCPP_FILESYSTEM_USE_SENDFILE and _LIBCPP_FILESYSTEM_USE_COPYFILE are mutually exclusive (right?). My rewriting didn't change any logic at all, it only reorganized the code a bit to define the whole function inside each #if branch. Unless I missed something and my "refactoring" actually changed the logic?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, _LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE and _LIBCPP_FILESYSTEM_USE_SENDFILE are not mutually exclusive. The intent is to attempt copy_file_range, and fall back to sendfile otherwise.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see what I missed now.

I would suggest something like this (which is basically what you wrote above IIUC):

#if HAS_SENDFILE
copy_file_impl_sendfile() { ... }
#endif

#if HAS_COPY_FILE_RANGE
copy_file_impl_copy_file_range() { ... }
#endif

#if HAS_COPY_FILE
copy_file_impl_copyfile() { ... }
#endif

copy_file_impl_fstream() { ... }


copy_file_impl() {
#if something
  full implementation
#elif something
  full implementation
#else
  full implementation
#endif
}

Does that make sense? Decouple the implementation of the different functions and the place where you compose them together, so that we can see at a glance what copy_file_impl does when looking at it.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you want the full implementation inlined into copy_file_impl, then what's the point of defining e.g. copy_file_impl_sendfile above?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By "full implementation", I simply meant that you wouldn't interleave code within the #ifdef and code outside the #ifdefs, I didn't mean that you would inline everything recursively into copy_file_impl.

Comment on lines +176 to +180
include(CheckCXXSymbolExists)
check_cxx_symbol_exists("copy_file_range" "unistd.h" LIBCXX_USE_COPY_FILE_RANGE)
if(LIBCXX_USE_COPY_FILE_RANGE)
list(APPEND LIBCXX_COMPILE_FLAGS "-D_LIBCPP_FILESYSTEM_USE_COPY_FILE_RANGE")
endif()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Linux versions don't provide copy_file_range? I'd rather assume support from the OS or test for something general like #ifdef __linux__ in operations.cpp than add a CMake check for a single OS feature like this.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since linux 4.5, according to the man page. RHEL 8 is at linux 4.18, for comparison. I don't think any still supported distro uses < 4.5
On FreeBSD, it has been added in FreeBSD 13, and FreeBSD 12.x went EoL on 31. December 2023

So yeah, if you want I'll just drop this and do an #ifdef __linux__ || __FreeBSD__

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
libc++ libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi. performance
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants