1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Syd: rock-solid application kernel
// src/ofd.rs: Interface to Open File Description locks
//
// Copyright (c) 2025 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0
//! Interface to Open File Description locks
// SAFETY: This module has (almost) been liberated from unsafe code!
// We use std::mem::zeroed to initialize struct flock portably.
// This struct has reserved fields on some architectures such as mipsel.
#![deny(unsafe_code)]
use std::os::fd::AsFd;
use libc::{flock, F_RDLCK, F_UNLCK, F_WRLCK, SEEK_SET};
use nix::{
errno::Errno,
fcntl::{fcntl, FcntlArg},
};
use crate::retry::retry_on_eintr;
/// This function creates an Open File Description (OFD) lock.
///
/// This function does NOT retry the system call on EINTR.
#[expect(clippy::cast_possible_truncation)]
pub fn lock_fd<Fd: AsFd>(fd: Fd, write: bool, wait: bool) -> Result<(), Errno> {
// SAFETY: struct flock has reserved fields on some architectures such as mipsel.
#[expect(unsafe_code)]
let mut lock: flock = unsafe { std::mem::zeroed() };
// No need to set l_len, l_start, and l_pid to zero.
lock.l_type = if write { F_WRLCK } else { F_RDLCK } as i16;
lock.l_whence = SEEK_SET as i16;
fcntl(
&fd,
if wait {
FcntlArg::F_OFD_SETLKW(&lock)
} else {
FcntlArg::F_OFD_SETLK(&lock)
},
)
.map(drop)
}
/// This function releases an Open File Description (OFD) lock.
///
/// This function retries the system call on EINTR.
#[expect(clippy::cast_possible_truncation)]
pub fn unlock_fd<Fd: AsFd>(fd: Fd) -> Result<(), Errno> {
// SAFETY: struct flock has reserved fields on some architectures such as mipsel.
#[expect(unsafe_code)]
let mut lock: flock = unsafe { std::mem::zeroed() };
// No need to set l_len, l_start, and l_pid to zero.
lock.l_type = F_UNLCK as i16;
lock.l_whence = SEEK_SET as i16;
retry_on_eintr(|| fcntl(&fd, FcntlArg::F_OFD_SETLK(&lock))).map(drop)
}