+sub _rename_noreplace_racy ($$) {
+ my ($old, $new) = @_;
+ if (link($old, $new)) {
+ warn "unlink $old: $!\n" if !unlink($old) && $! != ENOENT;
+ 1
+ } else {
+ undef;
+ }
+}
+
+# TODO: support FD args?
+sub rename_noreplace ($$) {
+ my ($old, $new) = @_;
+ if ($SYS_renameat2) { # RENAME_NOREPLACE = 1, AT_FDCWD = -100
+ my $ret = syscall($SYS_renameat2, -100, $old, -100, $new, 1);
+ if ($ret == 0) {
+ 1; # like rename() perlop
+ } elsif ($! == ENOSYS || $! == EINVAL) {
+ undef $SYS_renameat2;
+ _rename_noreplace_racy($old, $new);
+ } else {
+ undef
+ }
+ } else {
+ _rename_noreplace_racy($old, $new);
+ }
+}
+
+sub nodatacow_fh {
+ return if !defined($SYS_fstatfs);
+ my $buf = '';
+ vec($buf, 120 * 8 - 1, 1) = 0;
+ my ($fh) = @_;
+ syscall($SYS_fstatfs, fileno($fh), $buf) == 0 or
+ return warn("fstatfs: $!\n");
+ my $f_type = unpack('l!', $buf); # statfs.f_type is a signed word
+ return if $f_type != 0x9123683E; # BTRFS_SUPER_MAGIC
+
+ $FS_IOC_GETFLAGS //
+ return warn('FS_IOC_GETFLAGS undefined for platform');
+ ioctl($fh, $FS_IOC_GETFLAGS, $buf) //
+ return warn("FS_IOC_GETFLAGS: $!\n");
+ my $attr = unpack('l!', $buf);
+ return if ($attr & 0x00800000); # FS_NOCOW_FL;
+ ioctl($fh, $FS_IOC_SETFLAGS, pack('l', $attr | 0x00800000)) //
+ warn("FS_IOC_SETFLAGS: $!\n");
+}
+
+sub nodatacow_dir {
+ if (open my $fh, '<', $_[0]) { nodatacow_fh($fh) }
+}
+