//
// 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)
}
