]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/kernel_copy.rs
drive-by: Fix path spans
[rust.git] / library / std / src / sys / unix / kernel_copy.rs
1 //! This module contains specializations that can offload `io::copy()` operations on file descriptor
2 //! containing types (`File`, `TcpStream`, etc.) to more efficient syscalls than `read(2)` and `write(2)`.
3 //!
4 //! Specialization is only applied to wholly std-owned types so that user code can't observe
5 //! that the `Read` and `Write` traits are not used.
6 //!
7 //! Since a copy operation involves a reader and writer side where each can consist of different types
8 //! and also involve generic wrappers (e.g. `Take`, `BufReader`) it is not practical to specialize
9 //! a single method on all possible combinations.
10 //!
11 //! Instead readers and writers are handled separately by the `CopyRead` and `CopyWrite` specialization
12 //! traits and then specialized on by the `Copier::copy` method.
13 //!
14 //! `Copier` uses the specialization traits to unpack the underlying file descriptors and
15 //! additional prerequisites and constraints imposed by the wrapper types.
16 //!
17 //! Once it has obtained all necessary pieces and brought any wrapper types into a state where they
18 //! can be safely bypassed it will attempt to use the `copy_file_range(2)`,
19 //! `sendfile(2)` or `splice(2)` syscalls to move data directly between file descriptors.
20 //! Since those syscalls have requirements that cannot be fully checked in advance and
21 //! gathering additional information about file descriptors would require additional syscalls
22 //! anyway it simply attempts to use them one after another (guided by inaccurate hints) to
23 //! figure out which one works and falls back to the generic read-write copy loop if none of them
24 //! does.
25 //! Once a working syscall is found for a pair of file descriptors it will be called in a loop
26 //! until the copy operation is completed.
27 //!
28 //! Advantages of using these syscalls:
29 //!
30 //! * fewer context switches since reads and writes are coalesced into a single syscall
31 //!   and more bytes are transferred per syscall. This translates to higher throughput
32 //!   and fewer CPU cycles, at least for sufficiently large transfers to amortize the initial probing.
33 //! * `copy_file_range` creates reflink copies on CoW filesystems, thus moving less data and
34 //!   consuming less disk space
35 //! * `sendfile` and `splice` can perform zero-copy IO under some circumstances while
36 //!   a naive copy loop would move every byte through the CPU.
37 //!
38 //! Drawbacks:
39 //!
40 //! * copy operations smaller than the default buffer size can under some circumstances, especially
41 //!   on older kernels, incur more syscalls than the naive approach would. As mentioned above
42 //!   the syscall selection is guided by hints to minimize this possibility but they are not perfect.
43 //! * optimizations only apply to std types. If a user adds a custom wrapper type, e.g. to report
44 //!   progress, they can hit a performance cliff.
45 //! * complexity
46
47 use crate::cmp::min;
48 use crate::fs::{File, Metadata};
49 use crate::io::copy::generic_copy;
50 use crate::io::{
51     BufRead, BufReader, BufWriter, Error, Read, Result, StderrLock, StdinLock, StdoutLock, Take,
52     Write,
53 };
54 use crate::mem::ManuallyDrop;
55 use crate::net::TcpStream;
56 use crate::os::unix::fs::FileTypeExt;
57 use crate::os::unix::io::{AsRawFd, FromRawFd, RawFd};
58 use crate::os::unix::net::UnixStream;
59 use crate::process::{ChildStderr, ChildStdin, ChildStdout};
60 use crate::ptr;
61 use crate::sync::atomic::{AtomicBool, AtomicU8, Ordering};
62 use crate::sys::cvt;
63 use crate::sys::weak::syscall;
64 use libc::{EBADF, EINVAL, ENOSYS, EOPNOTSUPP, EOVERFLOW, EPERM, EXDEV};
65
66 #[cfg(test)]
67 mod tests;
68
69 pub(crate) fn copy_spec<R: Read + ?Sized, W: Write + ?Sized>(
70     read: &mut R,
71     write: &mut W,
72 ) -> Result<u64> {
73     let copier = Copier { read, write };
74     SpecCopy::copy(copier)
75 }
76
77 /// This type represents either the inferred `FileType` of a `RawFd` based on the source
78 /// type from which it was extracted or the actual metadata
79 ///
80 /// The methods on this type only provide hints, due to `AsRawFd` and `FromRawFd` the inferred
81 /// type may be wrong.
82 enum FdMeta {
83     /// We obtained the FD from a type that can contain any type of `FileType` and queried the metadata
84     /// because it is cheaper than probing all possible syscalls (reader side)
85     Metadata(Metadata),
86     Socket,
87     Pipe,
88     /// We don't have any metadata, e.g. because the original type was `File` which can represent
89     /// any `FileType` and we did not query the metadata either since it did not seem beneficial
90     /// (writer side)
91     NoneObtained,
92 }
93
94 impl FdMeta {
95     fn maybe_fifo(&self) -> bool {
96         match self {
97             FdMeta::Metadata(meta) => meta.file_type().is_fifo(),
98             FdMeta::Socket => false,
99             FdMeta::Pipe => true,
100             FdMeta::NoneObtained => true,
101         }
102     }
103
104     fn potential_sendfile_source(&self) -> bool {
105         match self {
106             // procfs erroneously shows 0 length on non-empty readable files.
107             // and if a file is truly empty then a `read` syscall will determine that and skip the write syscall
108             // thus there would be benefit from attempting sendfile
109             FdMeta::Metadata(meta)
110                 if meta.file_type().is_file() && meta.len() > 0
111                     || meta.file_type().is_block_device() =>
112             {
113                 true
114             }
115             _ => false,
116         }
117     }
118
119     fn copy_file_range_candidate(&self) -> bool {
120         match self {
121             // copy_file_range will fail on empty procfs files. `read` can determine whether EOF has been reached
122             // without extra cost and skip the write, thus there is no benefit in attempting copy_file_range
123             FdMeta::Metadata(meta) if meta.is_file() && meta.len() > 0 => true,
124             FdMeta::NoneObtained => true,
125             _ => false,
126         }
127     }
128 }
129
130 struct CopyParams(FdMeta, Option<RawFd>);
131
132 struct Copier<'a, 'b, R: Read + ?Sized, W: Write + ?Sized> {
133     read: &'a mut R,
134     write: &'b mut W,
135 }
136
137 trait SpecCopy {
138     fn copy(self) -> Result<u64>;
139 }
140
141 impl<R: Read + ?Sized, W: Write + ?Sized> SpecCopy for Copier<'_, '_, R, W> {
142     default fn copy(self) -> Result<u64> {
143         generic_copy(self.read, self.write)
144     }
145 }
146
147 impl<R: CopyRead, W: CopyWrite> SpecCopy for Copier<'_, '_, R, W> {
148     fn copy(self) -> Result<u64> {
149         let (reader, writer) = (self.read, self.write);
150         let r_cfg = reader.properties();
151         let w_cfg = writer.properties();
152
153         // before direct operations on file descriptors ensure that all source and sink buffers are empty
154         let mut flush = || -> crate::io::Result<u64> {
155             let bytes = reader.drain_to(writer, u64::MAX)?;
156             // BufWriter buffered bytes have already been accounted for in earlier write() calls
157             writer.flush()?;
158             Ok(bytes)
159         };
160
161         let mut written = 0u64;
162
163         if let (CopyParams(input_meta, Some(readfd)), CopyParams(output_meta, Some(writefd))) =
164             (r_cfg, w_cfg)
165         {
166             written += flush()?;
167             let max_write = reader.min_limit();
168
169             if input_meta.copy_file_range_candidate() && output_meta.copy_file_range_candidate() {
170                 let result = copy_regular_files(readfd, writefd, max_write);
171                 result.update_take(reader);
172
173                 match result {
174                     CopyResult::Ended(bytes_copied) => return Ok(bytes_copied + written),
175                     CopyResult::Error(e, _) => return Err(e),
176                     CopyResult::Fallback(bytes) => written += bytes,
177                 }
178             }
179
180             // on modern kernels sendfile can copy from any mmapable type (some but not all regular files and block devices)
181             // to any writable file descriptor. On older kernels the writer side can only be a socket.
182             // So we just try and fallback if needed.
183             // If current file offsets + write sizes overflow it may also fail, we do not try to fix that and instead
184             // fall back to the generic copy loop.
185             if input_meta.potential_sendfile_source() {
186                 let result = sendfile_splice(SpliceMode::Sendfile, readfd, writefd, max_write);
187                 result.update_take(reader);
188
189                 match result {
190                     CopyResult::Ended(bytes_copied) => return Ok(bytes_copied + written),
191                     CopyResult::Error(e, _) => return Err(e),
192                     CopyResult::Fallback(bytes) => written += bytes,
193                 }
194             }
195
196             if input_meta.maybe_fifo() || output_meta.maybe_fifo() {
197                 let result = sendfile_splice(SpliceMode::Splice, readfd, writefd, max_write);
198                 result.update_take(reader);
199
200                 match result {
201                     CopyResult::Ended(bytes_copied) => return Ok(bytes_copied + written),
202                     CopyResult::Error(e, _) => return Err(e),
203                     CopyResult::Fallback(0) => { /* use the fallback below */ }
204                     CopyResult::Fallback(_) => {
205                         unreachable!("splice should not return > 0 bytes on the fallback path")
206                     }
207                 }
208             }
209         }
210
211         // fallback if none of the more specialized syscalls wants to work with these file descriptors
212         match generic_copy(reader, writer) {
213             Ok(bytes) => Ok(bytes + written),
214             err => err,
215         }
216     }
217 }
218
219 #[rustc_specialization_trait]
220 trait CopyRead: Read {
221     /// Implementations that contain buffers (i.e. `BufReader`) must transfer data from their internal
222     /// buffers into `writer` until either the buffers are emptied or `limit` bytes have been
223     /// transferred, whichever occurs sooner.
224     /// If nested buffers are present the outer buffers must be drained first.
225     ///
226     /// This is necessary to directly bypass the wrapper types while preserving the data order
227     /// when operating directly on the underlying file descriptors.
228     fn drain_to<W: Write>(&mut self, _writer: &mut W, _limit: u64) -> Result<u64> {
229         Ok(0)
230     }
231
232     /// Updates `Take` wrappers to remove the number of bytes copied.
233     fn taken(&mut self, _bytes: u64) {}
234
235     /// The minimum of the limit of all `Take<_>` wrappers, `u64::MAX` otherwise.
236     /// This method does not account for data `BufReader` buffers and would underreport
237     /// the limit of a `Take<BufReader<Take<_>>>` type. Thus its result is only valid
238     /// after draining the buffers via `drain_to`.
239     fn min_limit(&self) -> u64 {
240         u64::MAX
241     }
242
243     /// Extracts the file descriptor and hints/metadata, delegating through wrappers if necessary.
244     fn properties(&self) -> CopyParams;
245 }
246
247 #[rustc_specialization_trait]
248 trait CopyWrite: Write {
249     /// Extracts the file descriptor and hints/metadata, delegating through wrappers if necessary.
250     fn properties(&self) -> CopyParams;
251 }
252
253 impl<T> CopyRead for &mut T
254 where
255     T: CopyRead,
256 {
257     fn drain_to<W: Write>(&mut self, writer: &mut W, limit: u64) -> Result<u64> {
258         (**self).drain_to(writer, limit)
259     }
260
261     fn taken(&mut self, bytes: u64) {
262         (**self).taken(bytes);
263     }
264
265     fn min_limit(&self) -> u64 {
266         (**self).min_limit()
267     }
268
269     fn properties(&self) -> CopyParams {
270         (**self).properties()
271     }
272 }
273
274 impl<T> CopyWrite for &mut T
275 where
276     T: CopyWrite,
277 {
278     fn properties(&self) -> CopyParams {
279         (**self).properties()
280     }
281 }
282
283 impl CopyRead for File {
284     fn properties(&self) -> CopyParams {
285         CopyParams(fd_to_meta(self), Some(self.as_raw_fd()))
286     }
287 }
288
289 impl CopyRead for &File {
290     fn properties(&self) -> CopyParams {
291         CopyParams(fd_to_meta(*self), Some(self.as_raw_fd()))
292     }
293 }
294
295 impl CopyWrite for File {
296     fn properties(&self) -> CopyParams {
297         CopyParams(FdMeta::NoneObtained, Some(self.as_raw_fd()))
298     }
299 }
300
301 impl CopyWrite for &File {
302     fn properties(&self) -> CopyParams {
303         CopyParams(FdMeta::NoneObtained, Some(self.as_raw_fd()))
304     }
305 }
306
307 impl CopyRead for TcpStream {
308     fn properties(&self) -> CopyParams {
309         // avoid the stat syscall since we can be fairly sure it's a socket
310         CopyParams(FdMeta::Socket, Some(self.as_raw_fd()))
311     }
312 }
313
314 impl CopyRead for &TcpStream {
315     fn properties(&self) -> CopyParams {
316         // avoid the stat syscall since we can be fairly sure it's a socket
317         CopyParams(FdMeta::Socket, Some(self.as_raw_fd()))
318     }
319 }
320
321 impl CopyWrite for TcpStream {
322     fn properties(&self) -> CopyParams {
323         // avoid the stat syscall since we can be fairly sure it's a socket
324         CopyParams(FdMeta::Socket, Some(self.as_raw_fd()))
325     }
326 }
327
328 impl CopyWrite for &TcpStream {
329     fn properties(&self) -> CopyParams {
330         // avoid the stat syscall since we can be fairly sure it's a socket
331         CopyParams(FdMeta::Socket, Some(self.as_raw_fd()))
332     }
333 }
334
335 impl CopyRead for UnixStream {
336     fn properties(&self) -> CopyParams {
337         // avoid the stat syscall since we can be fairly sure it's a socket
338         CopyParams(FdMeta::Socket, Some(self.as_raw_fd()))
339     }
340 }
341
342 impl CopyRead for &UnixStream {
343     fn properties(&self) -> CopyParams {
344         // avoid the stat syscall since we can be fairly sure it's a socket
345         CopyParams(FdMeta::Socket, Some(self.as_raw_fd()))
346     }
347 }
348
349 impl CopyWrite for UnixStream {
350     fn properties(&self) -> CopyParams {
351         // avoid the stat syscall since we can be fairly sure it's a socket
352         CopyParams(FdMeta::Socket, Some(self.as_raw_fd()))
353     }
354 }
355
356 impl CopyWrite for &UnixStream {
357     fn properties(&self) -> CopyParams {
358         // avoid the stat syscall since we can be fairly sure it's a socket
359         CopyParams(FdMeta::Socket, Some(self.as_raw_fd()))
360     }
361 }
362
363 impl CopyWrite for ChildStdin {
364     fn properties(&self) -> CopyParams {
365         CopyParams(FdMeta::Pipe, Some(self.as_raw_fd()))
366     }
367 }
368
369 impl CopyRead for ChildStdout {
370     fn properties(&self) -> CopyParams {
371         CopyParams(FdMeta::Pipe, Some(self.as_raw_fd()))
372     }
373 }
374
375 impl CopyRead for ChildStderr {
376     fn properties(&self) -> CopyParams {
377         CopyParams(FdMeta::Pipe, Some(self.as_raw_fd()))
378     }
379 }
380
381 impl CopyRead for StdinLock<'_> {
382     fn drain_to<W: Write>(&mut self, writer: &mut W, outer_limit: u64) -> Result<u64> {
383         let buf_reader = self.as_mut_buf();
384         let buf = buf_reader.buffer();
385         let buf = &buf[0..min(buf.len(), outer_limit.try_into().unwrap_or(usize::MAX))];
386         let bytes_drained = buf.len();
387         writer.write_all(buf)?;
388         buf_reader.consume(bytes_drained);
389
390         Ok(bytes_drained as u64)
391     }
392
393     fn properties(&self) -> CopyParams {
394         CopyParams(fd_to_meta(self), Some(self.as_raw_fd()))
395     }
396 }
397
398 impl CopyWrite for StdoutLock<'_> {
399     fn properties(&self) -> CopyParams {
400         CopyParams(FdMeta::NoneObtained, Some(self.as_raw_fd()))
401     }
402 }
403
404 impl CopyWrite for StderrLock<'_> {
405     fn properties(&self) -> CopyParams {
406         CopyParams(FdMeta::NoneObtained, Some(self.as_raw_fd()))
407     }
408 }
409
410 impl<T: CopyRead> CopyRead for Take<T> {
411     fn drain_to<W: Write>(&mut self, writer: &mut W, outer_limit: u64) -> Result<u64> {
412         let local_limit = self.limit();
413         let combined_limit = min(outer_limit, local_limit);
414         let bytes_drained = self.get_mut().drain_to(writer, combined_limit)?;
415         // update limit since read() was bypassed
416         self.set_limit(local_limit - bytes_drained);
417
418         Ok(bytes_drained)
419     }
420
421     fn taken(&mut self, bytes: u64) {
422         self.set_limit(self.limit() - bytes);
423         self.get_mut().taken(bytes);
424     }
425
426     fn min_limit(&self) -> u64 {
427         min(Take::limit(self), self.get_ref().min_limit())
428     }
429
430     fn properties(&self) -> CopyParams {
431         self.get_ref().properties()
432     }
433 }
434
435 impl<T: CopyRead> CopyRead for BufReader<T> {
436     fn drain_to<W: Write>(&mut self, writer: &mut W, outer_limit: u64) -> Result<u64> {
437         let buf = self.buffer();
438         let buf = &buf[0..min(buf.len(), outer_limit.try_into().unwrap_or(usize::MAX))];
439         let bytes = buf.len();
440         writer.write_all(buf)?;
441         self.consume(bytes);
442
443         let remaining = outer_limit - bytes as u64;
444
445         // in case of nested bufreaders we also need to drain the ones closer to the source
446         let inner_bytes = self.get_mut().drain_to(writer, remaining)?;
447
448         Ok(bytes as u64 + inner_bytes)
449     }
450
451     fn taken(&mut self, bytes: u64) {
452         self.get_mut().taken(bytes);
453     }
454
455     fn min_limit(&self) -> u64 {
456         self.get_ref().min_limit()
457     }
458
459     fn properties(&self) -> CopyParams {
460         self.get_ref().properties()
461     }
462 }
463
464 impl<T: CopyWrite> CopyWrite for BufWriter<T> {
465     fn properties(&self) -> CopyParams {
466         self.get_ref().properties()
467     }
468 }
469
470 fn fd_to_meta<T: AsRawFd>(fd: &T) -> FdMeta {
471     let fd = fd.as_raw_fd();
472     let file: ManuallyDrop<File> = ManuallyDrop::new(unsafe { File::from_raw_fd(fd) });
473     match file.metadata() {
474         Ok(meta) => FdMeta::Metadata(meta),
475         Err(_) => FdMeta::NoneObtained,
476     }
477 }
478
479 pub(super) enum CopyResult {
480     Ended(u64),
481     Error(Error, u64),
482     Fallback(u64),
483 }
484
485 impl CopyResult {
486     fn update_take(&self, reader: &mut impl CopyRead) {
487         match *self {
488             CopyResult::Fallback(bytes)
489             | CopyResult::Ended(bytes)
490             | CopyResult::Error(_, bytes) => reader.taken(bytes),
491         }
492     }
493 }
494
495 /// Invalid file descriptor.
496 ///
497 /// Valid file descriptors are guaranteed to be positive numbers (see `open()` manpage)
498 /// while negative values are used to indicate errors.
499 /// Thus -1 will never be overlap with a valid open file.
500 const INVALID_FD: RawFd = -1;
501
502 /// Linux-specific implementation that will attempt to use copy_file_range for copy offloading.
503 /// As the name says, it only works on regular files.
504 ///
505 /// Callers must handle fallback to a generic copy loop.
506 /// `Fallback` may indicate non-zero number of bytes already written
507 /// if one of the files' cursor +`max_len` would exceed u64::MAX (`EOVERFLOW`).
508 pub(super) fn copy_regular_files(reader: RawFd, writer: RawFd, max_len: u64) -> CopyResult {
509     use crate::cmp;
510
511     const NOT_PROBED: u8 = 0;
512     const UNAVAILABLE: u8 = 1;
513     const AVAILABLE: u8 = 2;
514
515     // Kernel prior to 4.5 don't have copy_file_range
516     // We store the availability in a global to avoid unnecessary syscalls
517     static HAS_COPY_FILE_RANGE: AtomicU8 = AtomicU8::new(NOT_PROBED);
518
519     syscall! {
520         fn copy_file_range(
521             fd_in: libc::c_int,
522             off_in: *mut libc::loff_t,
523             fd_out: libc::c_int,
524             off_out: *mut libc::loff_t,
525             len: libc::size_t,
526             flags: libc::c_uint
527         ) -> libc::ssize_t
528     }
529
530     match HAS_COPY_FILE_RANGE.load(Ordering::Relaxed) {
531         NOT_PROBED => {
532             // EPERM can indicate seccomp filters or an immutable file.
533             // To distinguish these cases we probe with invalid file descriptors which should result in EBADF if the syscall is supported
534             // and some other error (ENOSYS or EPERM) if it's not available
535             let result = unsafe {
536                 cvt(copy_file_range(INVALID_FD, ptr::null_mut(), INVALID_FD, ptr::null_mut(), 1, 0))
537             };
538
539             if matches!(result.map_err(|e| e.raw_os_error()), Err(Some(EBADF))) {
540                 HAS_COPY_FILE_RANGE.store(AVAILABLE, Ordering::Relaxed);
541             } else {
542                 HAS_COPY_FILE_RANGE.store(UNAVAILABLE, Ordering::Relaxed);
543                 return CopyResult::Fallback(0);
544             }
545         }
546         UNAVAILABLE => return CopyResult::Fallback(0),
547         _ => {}
548     };
549
550     let mut written = 0u64;
551     while written < max_len {
552         let bytes_to_copy = cmp::min(max_len - written, usize::MAX as u64);
553         // cap to 1GB chunks in case u64::MAX is passed as max_len and the file has a non-zero seek position
554         // this allows us to copy large chunks without hitting EOVERFLOW,
555         // unless someone sets a file offset close to u64::MAX - 1GB, in which case a fallback would be required
556         let bytes_to_copy = cmp::min(bytes_to_copy as usize, 0x4000_0000usize);
557         let copy_result = unsafe {
558             // We actually don't have to adjust the offsets,
559             // because copy_file_range adjusts the file offset automatically
560             cvt(copy_file_range(reader, ptr::null_mut(), writer, ptr::null_mut(), bytes_to_copy, 0))
561         };
562
563         match copy_result {
564             Ok(0) if written == 0 => {
565                 // fallback to work around several kernel bugs where copy_file_range will fail to
566                 // copy any bytes and return 0 instead of an error if
567                 // - reading virtual files from the proc filesystem which appear to have 0 size
568                 //   but are not empty. noted in coreutils to affect kernels at least up to 5.6.19.
569                 // - copying from an overlay filesystem in docker. reported to occur on fedora 32.
570                 return CopyResult::Fallback(0);
571             }
572             Ok(0) => return CopyResult::Ended(written), // reached EOF
573             Ok(ret) => written += ret as u64,
574             Err(err) => {
575                 return match err.raw_os_error() {
576                     // when file offset + max_length > u64::MAX
577                     Some(EOVERFLOW) => CopyResult::Fallback(written),
578                     Some(ENOSYS | EXDEV | EINVAL | EPERM | EOPNOTSUPP | EBADF) if written == 0 => {
579                         // Try fallback io::copy if either:
580                         // - Kernel version is < 4.5 (ENOSYS¹)
581                         // - Files are mounted on different fs (EXDEV)
582                         // - copy_file_range is broken in various ways on RHEL/CentOS 7 (EOPNOTSUPP)
583                         // - copy_file_range file is immutable or syscall is blocked by seccomp¹ (EPERM)
584                         // - copy_file_range cannot be used with pipes or device nodes (EINVAL)
585                         // - the writer fd was opened with O_APPEND (EBADF²)
586                         // and no bytes were written successfully yet.  (All these errnos should
587                         // not be returned if something was already written, but they happen in
588                         // the wild, see #91152.)
589                         //
590                         // ¹ these cases should be detected by the initial probe but we handle them here
591                         //   anyway in case syscall interception changes during runtime
592                         // ² actually invalid file descriptors would cause this too, but in that case
593                         //   the fallback code path is expected to encounter the same error again
594                         CopyResult::Fallback(0)
595                     }
596                     _ => CopyResult::Error(err, written),
597                 };
598             }
599         }
600     }
601     CopyResult::Ended(written)
602 }
603
604 #[derive(PartialEq)]
605 enum SpliceMode {
606     Sendfile,
607     Splice,
608 }
609
610 /// performs splice or sendfile between file descriptors
611 /// Does _not_ fall back to a generic copy loop.
612 fn sendfile_splice(mode: SpliceMode, reader: RawFd, writer: RawFd, len: u64) -> CopyResult {
613     static HAS_SENDFILE: AtomicBool = AtomicBool::new(true);
614     static HAS_SPLICE: AtomicBool = AtomicBool::new(true);
615
616     // Android builds use feature level 14, but the libc wrapper for splice is
617     // gated on feature level 21+, so we have to invoke the syscall directly.
618     #[cfg(target_os = "android")]
619     syscall! {
620         fn splice(
621             srcfd: libc::c_int,
622             src_offset: *const i64,
623             dstfd: libc::c_int,
624             dst_offset: *const i64,
625             len: libc::size_t,
626             flags: libc::c_int
627         ) -> libc::ssize_t
628     }
629
630     #[cfg(target_os = "linux")]
631     use libc::splice;
632
633     match mode {
634         SpliceMode::Sendfile if !HAS_SENDFILE.load(Ordering::Relaxed) => {
635             return CopyResult::Fallback(0);
636         }
637         SpliceMode::Splice if !HAS_SPLICE.load(Ordering::Relaxed) => {
638             return CopyResult::Fallback(0);
639         }
640         _ => (),
641     }
642
643     let mut written = 0u64;
644     while written < len {
645         // according to its manpage that's the maximum size sendfile() will copy per invocation
646         let chunk_size = crate::cmp::min(len - written, 0x7ffff000_u64) as usize;
647
648         let result = match mode {
649             SpliceMode::Sendfile => {
650                 cvt(unsafe { libc::sendfile(writer, reader, ptr::null_mut(), chunk_size) })
651             }
652             SpliceMode::Splice => cvt(unsafe {
653                 splice(reader, ptr::null_mut(), writer, ptr::null_mut(), chunk_size, 0)
654             }),
655         };
656
657         match result {
658             Ok(0) => break, // EOF
659             Ok(ret) => written += ret as u64,
660             Err(err) => {
661                 return match err.raw_os_error() {
662                     Some(ENOSYS | EPERM) => {
663                         // syscall not supported (ENOSYS)
664                         // syscall is disallowed, e.g. by seccomp (EPERM)
665                         match mode {
666                             SpliceMode::Sendfile => HAS_SENDFILE.store(false, Ordering::Relaxed),
667                             SpliceMode::Splice => HAS_SPLICE.store(false, Ordering::Relaxed),
668                         }
669                         assert_eq!(written, 0);
670                         CopyResult::Fallback(0)
671                     }
672                     Some(EINVAL) => {
673                         // splice/sendfile do not support this particular file descriptor (EINVAL)
674                         assert_eq!(written, 0);
675                         CopyResult::Fallback(0)
676                     }
677                     Some(os_err) if mode == SpliceMode::Sendfile && os_err == EOVERFLOW => {
678                         CopyResult::Fallback(written)
679                     }
680                     _ => CopyResult::Error(err, written),
681                 };
682             }
683         }
684     }
685     CopyResult::Ended(written)
686 }