Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Add copy_file_range strategy and benchmark metrics

Mel8c4caabddfa9
diff --git a/src/files/copy_bench.zig b/src/files/copy_bench.zig
index 1fcba80..991e1f2 100644
--- a/src/files/copy_bench.zig
+++ b/src/files/copy_bench.zig
@@ -9,6 +9,7 @@
//! A warm-up run precedes five measured runs for each profile.
const std = @import("std");
+const builtin = @import("builtin");
const ops = @import("ops.zig");
const c = @import("c.zig").api;
const Allocator = std.mem.Allocator;
@@ -346,6 +347,8 @@ fn emitRow(
stats: WorkloadStats,
samples: []const u64,
buffer_size: usize,
+ strategy: ops.CopyStrategy,
+ metrics: ops.CopyMetrics,
) void {
const median_ns = samples[samples.len / 2];
const mib_per_second =
@@ -359,8 +362,9 @@ fn emitRow(
@as(f64, @floatFromInt(median_ns));
std.debug.print(
- "BENCH,A,job_copy_e2e,{s},warm_source_cache,{d},{d},{d},{d},{d},{d},{d},{d},{d:.2},{d:.2}\n",
+ "BENCH,A,job_copy_e2e_{s},{s},warm_source_cache,{d},{d},{d},{d},{d},{d},{d},{d},{d:.2},{d:.2},{d},{d},{d}\n",
.{
+ strategy.name(),
profile.name,
stats.files,
stats.directories,
@@ -372,6 +376,9 @@ fn emitRow(
samples[samples.len - 1],
mib_per_second,
files_per_second,
+ metrics.copy_file_range_calls,
+ metrics.copy_file_range_bytes,
+ metrics.buffered_fallback_files,
},
);
}
@@ -392,36 +399,42 @@ fn benchmarkProfile(
var runner = try ops.JobRunner.init(allocator);
defer runner.deinit();
- for (buffer_sizes) |buffer_size| {
- runner.copy_buffer_bytes = buffer_size;
+ const strategy_count = if (builtin.os.tag == .linux) 2 else 1;
+ for (0..strategy_count) |strategy_index| {
+ const strategy: ops.CopyStrategy =
+ if (strategy_index == 0) .buffered else .copy_file_range;
+ runner.copy_strategy = strategy;
- // Warm source data and filesystem metadata for this buffer size.
- _ = try runCopySample(
- allocator,
- runner,
- source_root,
- benchmark_root,
- profile.name,
- 0,
- stats.total_bytes,
- buffer_size,
- );
+ for (buffer_sizes) |buffer_size| {
+ runner.copy_buffer_bytes = buffer_size;
- var samples: [benchmark_iterations]u64 = undefined;
- for (&samples, 0..) |*sample, iteration| {
- sample.* = try runCopySample(
+ // Warm source data and filesystem metadata for this combination.
+ _ = try runCopySample(
allocator,
runner,
source_root,
benchmark_root,
profile.name,
- iteration + 1,
+ 0,
stats.total_bytes,
buffer_size,
);
+ var samples: [benchmark_iterations]u64 = undefined;
+ for (&samples, 0..) |*sample, iteration| {
+ sample.* = try runCopySample(
+ allocator,
+ runner,
+ source_root,
+ benchmark_root,
+ profile.name,
+ iteration + 1,
+ stats.total_bytes,
+ buffer_size,
+ );
+ }
+ sortSamples(&samples);
+ emitRow(profile, stats, &samples, buffer_size, strategy, runner.copyMetrics());
}
- sortSamples(&samples);
- emitRow(profile, stats, &samples, buffer_size);
}
}
@@ -444,7 +457,7 @@ pub fn run(allocator: Allocator) !void {
defer ops.deleteRecursive(allocator, benchmark_root) catch {};
std.debug.print(
- "BENCH,phase,operation,profile,cache_mode,files,directories,total_bytes,buffer_bytes,iterations,median_ns,min_ns,max_ns,median_mib_per_second,median_files_per_second\n",
+ "BENCH,phase,operation,profile,cache_mode,files,directories,total_bytes,buffer_bytes,iterations,median_ns,min_ns,max_ns,median_mib_per_second,median_files_per_second,copy_file_range_calls,copy_file_range_bytes,buffered_fallback_files\n",
.{},
);
diff --git a/src/files/ops.zig b/src/files/ops.zig
index 7ca4700..081b36c 100644
--- a/src/files/ops.zig
+++ b/src/files/ops.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const builtin = @import("builtin");
const platform = @import("platform");
const i18n = @import("i18n");
const tr = i18n.tr;
@@ -10,6 +11,24 @@ const max_progress_path_bytes = 4096;
pub const copy_buffer_size = 64 * 1024;
const max_copy_buffer_size = 1024 * 1024;
+pub const CopyStrategy = enum {
+ buffered,
+ copy_file_range,
+
+ pub fn name(self: CopyStrategy) []const u8 {
+ return switch (self) {
+ .buffered => "buffered",
+ .copy_file_range => "copy_file_range",
+ };
+ }
+};
+
+pub const CopyMetrics = struct {
+ copy_file_range_calls: u64 = 0,
+ copy_file_range_bytes: u64 = 0,
+ buffered_fallback_files: u64 = 0,
+};
+
pub const ConflictAction = enum {
ask,
skip,
@@ -552,6 +571,64 @@ fn copyFileContentsTracked(
var buf: [max_copy_buffer_size]u8 = undefined;
const buffer_len = if (runner) |job| job.copy_buffer_bytes else copy_buffer_size;
std.debug.assert(buffer_len > 0 and buffer_len <= buf.len);
+
+ var use_buffered_copy = true;
+ if (comptime builtin.os.tag == .linux) {
+ if (runner) |job| {
+ if (job.copy_strategy == .copy_file_range) {
+ use_buffered_copy = false;
+ while (true) {
+ if (!job.waitIfResumed(cancel)) {
+ _ = c.unlink(dst_z);
+ return error.Cancelled;
+ }
+ if (cancel != null and cancel.?.load(.acquire)) {
+ _ = c.unlink(dst_z);
+ return error.Cancelled;
+ }
+
+ const copied = c.copy_file_range(
+ src_fd,
+ null,
+ dst_fd,
+ null,
+ buffer_len,
+ 0,
+ );
+ job.recordCopyFileRangeCall();
+ if (copied == 0) break;
+ if (copied > 0) {
+ job.recordCopyFileRangeBytes(@intCast(copied));
+ job.addFileTransferredBytes(@intCast(copied));
+ continue;
+ }
+
+ const copy_errno = std.c._errno().*;
+ if (copy_errno == c.EINTR) continue;
+
+ // Unsupported filesystems, cross-device copies, and
+ // unsupported kernel paths fall back at the current
+ // file offsets. Any bytes already copied remain valid.
+ if (copy_errno == c.EXDEV or
+ copy_errno == c.EINVAL or
+ copy_errno == c.ENOSYS or
+ copy_errno == c.EOPNOTSUPP or
+ copy_errno == c.EPERM)
+ {
+ job.recordBufferedFallback();
+ use_buffered_copy = true;
+ break;
+ }
+
+ _ = c.unlink(dst_z);
+ return error.CopyFailed;
+ }
+ }
+ }
+ }
+
+ if (!use_buffered_copy) return;
+
while (true) {
if (runner) |job| if (!job.waitIfResumed(cancel)) {
_ = c.unlink(dst_z);
@@ -788,6 +865,9 @@ pub const JobRunner = struct {
allocator: Allocator,
/// Per-job copy buffer size. Production defaults to 64 KiB.
copy_buffer_bytes: usize = copy_buffer_size,
+ /// The production default remains buffered until benchmarks justify a change.
+ copy_strategy: CopyStrategy = .buffered,
+ copy_metrics: CopyMetrics = .{},
mutex: c.pthread_mutex_t = undefined,
cond: c.pthread_cond_t = undefined,
thread: ?std.Thread = null,
@@ -963,6 +1043,7 @@ pub const JobRunner = struct {
self.processed_items = 0;
self.total_bytes = 0;
self.transferred_bytes = 0;
+ self.copy_metrics = .{};
self.total_bytes_known = false;
self.measuring = kind == .copy or kind == .move;
self.success_count = 0;
@@ -1130,6 +1211,31 @@ pub const JobRunner = struct {
_ = c.pthread_mutex_unlock(&self.mutex);
}
+ /// Returns copy_file_range activity accumulated by the current job.
+ pub fn copyMetrics(self: *JobRunner) CopyMetrics {
+ _ = c.pthread_mutex_lock(&self.mutex);
+ defer _ = c.pthread_mutex_unlock(&self.mutex);
+ return self.copy_metrics;
+ }
+
+ fn recordCopyFileRangeCall(self: *JobRunner) void {
+ _ = c.pthread_mutex_lock(&self.mutex);
+ self.copy_metrics.copy_file_range_calls +|= 1;
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ }
+
+ fn recordCopyFileRangeBytes(self: *JobRunner, bytes: u64) void {
+ _ = c.pthread_mutex_lock(&self.mutex);
+ self.copy_metrics.copy_file_range_bytes +|= bytes;
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ }
+
+ fn recordBufferedFallback(self: *JobRunner) void {
+ _ = c.pthread_mutex_lock(&self.mutex);
+ self.copy_metrics.buffered_fallback_files +|= 1;
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ }
+
fn beginFileProgress(self: *JobRunner, path: []const u8, size: u64) void {
_ = c.pthread_mutex_lock(&self.mutex);
self.current_file_path_len = 0;
diff --git a/src/files/ops_tests.zig b/src/files/ops_tests.zig
index 38b3826..040f389 100644
--- a/src/files/ops_tests.zig
+++ b/src/files/ops_tests.zig
@@ -938,6 +938,54 @@ test "view preferences survive restart and reject malformed state" {
try std.testing.expectEqual(Preferences{}, Preferences.load(a, std.testing.io, path));
}
+test "JobRunner copy_file_range strategy copies contents and tracks progress" {
+ const allocator = std.testing.allocator;
+ var tmp_path_buf: [256]u8 = undefined;
+ const tmp_path = try makeTestDir(&tmp_path_buf);
+ defer ops_mod.deleteRecursive(allocator, tmp_path) catch {};
+
+ try ops_mod.createFolder(allocator, tmp_path, "src");
+ try ops_mod.createFolder(allocator, tmp_path, "dst");
+
+ const src_dir = try std.fmt.allocPrint(allocator, "{s}/src", .{tmp_path});
+ defer allocator.free(src_dir);
+ const dst_dir = try std.fmt.allocPrint(allocator, "{s}/dst", .{tmp_path});
+ defer allocator.free(dst_dir);
+ const src_path = try std.fmt.allocPrint(allocator, "{s}/payload.bin", .{src_dir});
+ defer allocator.free(src_path);
+ const dst_path = try std.fmt.allocPrint(allocator, "{s}/payload.bin", .{dst_dir});
+ defer allocator.free(dst_path);
+
+ const payload = "copy_file_range progress and fallback test payload";
+ try writeTestFile(src_path, payload);
+
+ const runner = try ops_mod.JobRunner.init(allocator);
+ defer runner.deinit();
+ runner.copy_strategy = .copy_file_range;
+ runner.copy_buffer_bytes = 16;
+ try runner.start(.copy, &.{src_path}, dst_dir, .skip);
+
+ while (true) {
+ const progress = runner.pollProgress();
+ if (progress.state == .finished) {
+ try std.testing.expectEqual(@as(usize, 1), progress.success_count);
+ try std.testing.expectEqual(@as(usize, 0), progress.failed_count);
+ try std.testing.expectEqual(@as(u64, payload.len), progress.transferred_bytes);
+ const metrics = runner.copyMetrics();
+ try std.testing.expect(metrics.copy_file_range_calls > 0);
+ try std.testing.expect(
+ metrics.copy_file_range_bytes > 0 or
+ metrics.buffered_fallback_files > 0,
+ );
+ break;
+ }
+ _ = c.usleep(1000);
+ }
+
+ var actual: [128]u8 = undefined;
+ try std.testing.expectEqualStrings(payload, try readTestFile(dst_path, &actual));
+}
+
test "cancelling an active copy removes partial output and preserves source" {
const a = std.testing.allocator;
var tmp_buf: [256]u8 = undefined;
@@ -957,6 +1005,7 @@ test "cancelling an active copy removes partial output and preserves source" {
try std.testing.expect(c.ftruncate(fd, 512 * 1024 * 1024) == 0);
const runner = try ops_mod.JobRunner.init(a);
defer runner.deinit();
+ runner.copy_strategy = .copy_file_range;
try runner.start(.copy, &.{src}, dest, .ask);
var started = false;
for (0..1000) |_| {
@@ -1002,6 +1051,7 @@ test "paused copy stops at a safe point and resumes" {
const runner = try ops_mod.JobRunner.init(a);
defer runner.deinit();
+ runner.copy_strategy = .copy_file_range;
try runner.start(.copy, &.{src}, dest, .ask);
var started = false;