Skip to content

Commit

Permalink
os/linux: add fadvise
Browse files Browse the repository at this point in the history
  • Loading branch information
vrischmann committed Mar 20, 2021
1 parent d1d4b14 commit 58a2140
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
56 changes: 56 additions & 0 deletions lib/std/os/linux.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1386,6 +1386,62 @@ pub fn madvise(address: [*]u8, len: usize, advice: u32) usize {
return syscall3(.madvise, @ptrToInt(address), len, advice);
}

pub fn fadvise(fd: fd_t, offset: u64, len: u64, advice: usize) usize {
if (comptime std.Target.current.cpu.arch.isMIPS()) {
// MIPS requires a 7 argument syscall

const offset_halves = splitValue64(@bitCast(u64, offset));
const length_halves = splitValue64(@bitCast(u64, len));

return syscall7(
.fadvise64,
@bitCast(usize, @as(isize, fd)),
0,
offset_halves[0],
offset_halves[1],
length_halves[0],
length_halves[1],
advice,
);
} else if (comptime std.Target.current.cpu.arch.isARM()) {
// ARM reorders the arguments

const offset_halves = splitValue64(@bitCast(u64, offset));
const length_halves = splitValue64(@bitCast(u64, len));

return syscall6(
.fadvise64_64,
@bitCast(usize, @as(isize, fd)),
advice,
offset_halves[0],
offset_halves[1],
length_halves[0],
length_halves[1],
);
} else if (@hasField(SYS, "fadvise64_64")) {
const offset_halves = splitValue64(@bitCast(u64, offset));
const length_halves = splitValue64(@bitCast(u64, len));

return syscall6(
.fadvise64_64,
@bitCast(usize, @as(isize, fd)),
offset_halves[0],
offset_halves[1],
length_halves[0],
length_halves[1],
advice,
);
} else {
return syscall4(
.fadvise64,
@bitCast(usize, @as(isize, fd)),
@bitCast(usize, offset),
@bitCast(usize, len),
advice,
);
}
}

test {
if (builtin.os.tag == .linux) {
_ = @import("linux/test.zig");
Expand Down
20 changes: 20 additions & 0 deletions lib/std/os/linux/test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,23 @@ test "user and group ids" {
expectEqual(linux.getauxval(elf.AT_EUID), linux.geteuid());
expectEqual(linux.getauxval(elf.AT_EGID), linux.getegid());
}

test "fadvise" {
const tmp_file_name = "temp_posix_fadvise.txt";
var file = try fs.cwd().createFile(tmp_file_name, .{});
defer {
file.close();
fs.cwd().deleteFile(tmp_file_name) catch {};
}

var buf: [2048]u8 = undefined;
try file.writeAll(&buf);

const ret = linux.fadvise(
file.handle,
0,
0,
linux.POSIX_FADV_SEQUENTIAL,
);
expectEqual(@as(usize, 0), ret);
}

0 comments on commit 58a2140

Please sign in to comment.