// SPDX-License-Identifier: GPL-2.012// Copyright (C) 2024 Google LLC.34//! Files and file descriptors.5//!6//! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h) and7//! [`include/linux/file.h`](srctree/include/linux/file.h)89use crate::{10bindings,11cred::Credential,12error::{code::*, to_result, Error, Result},13fmt,14sync::aref::{ARef, AlwaysRefCounted},15types::{NotThreadSafe, Opaque},16};17use core::ptr;1819/// Primitive type representing the offset within a [`File`].20///21/// Type alias for `bindings::loff_t`.22pub type Offset = bindings::loff_t;2324/// Flags associated with a [`File`].25pub mod flags {26/// File is opened in append mode.27pub const O_APPEND: u32 = bindings::O_APPEND;2829/// Signal-driven I/O is enabled.30pub const O_ASYNC: u32 = bindings::FASYNC;3132/// Close-on-exec flag is set.33pub const O_CLOEXEC: u32 = bindings::O_CLOEXEC;3435/// File was created if it didn't already exist.36pub const O_CREAT: u32 = bindings::O_CREAT;3738/// Direct I/O is enabled for this file.39pub const O_DIRECT: u32 = bindings::O_DIRECT;4041/// File must be a directory.42pub const O_DIRECTORY: u32 = bindings::O_DIRECTORY;4344/// Like [`O_SYNC`] except metadata is not synced.45pub const O_DSYNC: u32 = bindings::O_DSYNC;4647/// Ensure that this file is created with the `open(2)` call.48pub const O_EXCL: u32 = bindings::O_EXCL;4950/// Large file size enabled (`off64_t` over `off_t`).51pub const O_LARGEFILE: u32 = bindings::O_LARGEFILE;5253/// Do not update the file last access time.54pub const O_NOATIME: u32 = bindings::O_NOATIME;5556/// File should not be used as process's controlling terminal.57pub const O_NOCTTY: u32 = bindings::O_NOCTTY;5859/// If basename of path is a symbolic link, fail open.60pub const O_NOFOLLOW: u32 = bindings::O_NOFOLLOW;6162/// File is using nonblocking I/O.63pub const O_NONBLOCK: u32 = bindings::O_NONBLOCK;6465/// File is using nonblocking I/O.66///67/// This is effectively the same flag as [`O_NONBLOCK`] on all architectures68/// except SPARC64.69pub const O_NDELAY: u32 = bindings::O_NDELAY;7071/// Used to obtain a path file descriptor.72pub const O_PATH: u32 = bindings::O_PATH;7374/// Write operations on this file will flush data and metadata.75pub const O_SYNC: u32 = bindings::O_SYNC;7677/// This file is an unnamed temporary regular file.78pub const O_TMPFILE: u32 = bindings::O_TMPFILE;7980/// File should be truncated to length 0.81pub const O_TRUNC: u32 = bindings::O_TRUNC;8283/// Bitmask for access mode flags.84///85/// # Examples86///87/// ```88/// use kernel::fs::file;89/// # fn do_something() {}90/// # let flags = 0;91/// if (flags & file::flags::O_ACCMODE) == file::flags::O_RDONLY {92/// do_something();93/// }94/// ```95pub const O_ACCMODE: u32 = bindings::O_ACCMODE;9697/// File is read only.98pub const O_RDONLY: u32 = bindings::O_RDONLY;99100/// File is write only.101pub const O_WRONLY: u32 = bindings::O_WRONLY;102103/// File can be both read and written.104pub const O_RDWR: u32 = bindings::O_RDWR;105}106107/// Wraps the kernel's `struct file`. Thread safe.108///109/// This represents an open file rather than a file on a filesystem. Processes generally reference110/// open files using file descriptors. However, file descriptors are not the same as files. A file111/// descriptor is just an integer that corresponds to a file, and a single file may be referenced112/// by multiple file descriptors.113///114/// # Refcounting115///116/// Instances of this type are reference-counted. The reference count is incremented by the117/// `fget`/`get_file` functions and decremented by `fput`. The Rust type `ARef<File>` represents a118/// pointer that owns a reference count on the file.119///120/// Whenever a process opens a file descriptor (fd), it stores a pointer to the file in its fd121/// table (`struct files_struct`). This pointer owns a reference count to the file, ensuring the122/// file isn't prematurely deleted while the file descriptor is open. In Rust terminology, the123/// pointers in `struct files_struct` are `ARef<File>` pointers.124///125/// ## Light refcounts126///127/// Whenever a process has an fd to a file, it may use something called a "light refcount" as a128/// performance optimization. Light refcounts are acquired by calling `fdget` and released with129/// `fdput`. The idea behind light refcounts is that if the fd is not closed between the calls to130/// `fdget` and `fdput`, then the refcount cannot hit zero during that time, as the `struct131/// files_struct` holds a reference until the fd is closed. This means that it's safe to access the132/// file even if `fdget` does not increment the refcount.133///134/// The requirement that the fd is not closed during a light refcount applies globally across all135/// threads - not just on the thread using the light refcount. For this reason, light refcounts are136/// only used when the `struct files_struct` is not shared with other threads, since this ensures137/// that other unrelated threads cannot suddenly start using the fd and close it. Therefore,138/// calling `fdget` on a shared `struct files_struct` creates a normal refcount instead of a light139/// refcount.140///141/// Light reference counts must be released with `fdput` before the system call returns to142/// userspace. This means that if you wait until the current system call returns to userspace, then143/// all light refcounts that existed at the time have gone away.144///145/// ### The file position146///147/// Each `struct file` has a position integer, which is protected by the `f_pos_lock` mutex.148/// However, if the `struct file` is not shared, then the kernel may avoid taking the lock as a149/// performance optimization.150///151/// The condition for avoiding the `f_pos_lock` mutex is different from the condition for using152/// `fdget`. With `fdget`, you may avoid incrementing the refcount as long as the current fd table153/// is not shared; it is okay if there are other fd tables that also reference the same `struct154/// file`. However, `fdget_pos` can only avoid taking the `f_pos_lock` if the entire `struct file`155/// is not shared, as different processes with an fd to the same `struct file` share the same156/// position.157///158/// To represent files that are not thread safe due to this optimization, the [`LocalFile`] type is159/// used.160///161/// ## Rust references162///163/// The reference type `&File` is similar to light refcounts:164///165/// * `&File` references don't own a reference count. They can only exist as long as the reference166/// count stays positive, and can only be created when there is some mechanism in place to ensure167/// this.168///169/// * The Rust borrow-checker normally ensures this by enforcing that the `ARef<File>` from which170/// a `&File` is created outlives the `&File`.171///172/// * Using the unsafe [`File::from_raw_file`] means that it is up to the caller to ensure that the173/// `&File` only exists while the reference count is positive.174///175/// * You can think of `fdget` as using an fd to look up an `ARef<File>` in the `struct176/// files_struct` and create an `&File` from it. The "fd cannot be closed" rule is like the Rust177/// rule "the `ARef<File>` must outlive the `&File`".178///179/// # Invariants180///181/// * All instances of this type are refcounted using the `f_count` field.182/// * There must not be any active calls to `fdget_pos` on this file that did not take the183/// `f_pos_lock` mutex.184#[repr(transparent)]185pub struct File {186inner: Opaque<bindings::file>,187}188189// SAFETY: This file is known to not have any active `fdget_pos` calls that did not take the190// `f_pos_lock` mutex, so it is safe to transfer it between threads.191unsafe impl Send for File {}192193// SAFETY: This file is known to not have any active `fdget_pos` calls that did not take the194// `f_pos_lock` mutex, so it is safe to access its methods from several threads in parallel.195unsafe impl Sync for File {}196197// SAFETY: The type invariants guarantee that `File` is always ref-counted. This implementation198// makes `ARef<File>` own a normal refcount.199unsafe impl AlwaysRefCounted for File {200#[inline]201fn inc_ref(&self) {202// SAFETY: The existence of a shared reference means that the refcount is nonzero.203unsafe { bindings::get_file(self.as_ptr()) };204}205206#[inline]207unsafe fn dec_ref(obj: ptr::NonNull<File>) {208// SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we209// may drop it. The cast is okay since `File` has the same representation as `struct file`.210unsafe { bindings::fput(obj.cast().as_ptr()) }211}212}213214/// Wraps the kernel's `struct file`. Not thread safe.215///216/// This type represents a file that is not known to be safe to transfer across thread boundaries.217/// To obtain a thread-safe [`File`], use the [`assume_no_fdget_pos`] conversion.218///219/// See the documentation for [`File`] for more information.220///221/// # Invariants222///223/// * All instances of this type are refcounted using the `f_count` field.224/// * If there is an active call to `fdget_pos` that did not take the `f_pos_lock` mutex, then it225/// must be on the same thread as this file.226///227/// [`assume_no_fdget_pos`]: LocalFile::assume_no_fdget_pos228#[repr(transparent)]229pub struct LocalFile {230inner: Opaque<bindings::file>,231}232233// SAFETY: The type invariants guarantee that `LocalFile` is always ref-counted. This implementation234// makes `ARef<LocalFile>` own a normal refcount.235unsafe impl AlwaysRefCounted for LocalFile {236#[inline]237fn inc_ref(&self) {238// SAFETY: The existence of a shared reference means that the refcount is nonzero.239unsafe { bindings::get_file(self.as_ptr()) };240}241242#[inline]243unsafe fn dec_ref(obj: ptr::NonNull<LocalFile>) {244// SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we245// may drop it. The cast is okay since `LocalFile` has the same representation as246// `struct file`.247unsafe { bindings::fput(obj.cast().as_ptr()) }248}249}250251impl LocalFile {252/// Constructs a new `struct file` wrapper from a file descriptor.253///254/// The file descriptor belongs to the current process, and there might be active local calls255/// to `fdget_pos` on the same file.256///257/// To obtain an `ARef<File>`, use the [`assume_no_fdget_pos`] function to convert.258///259/// [`assume_no_fdget_pos`]: LocalFile::assume_no_fdget_pos260#[inline]261pub fn fget(fd: u32) -> Result<ARef<LocalFile>, BadFdError> {262// SAFETY: FFI call, there are no requirements on `fd`.263let ptr = ptr::NonNull::new(unsafe { bindings::fget(fd) }).ok_or(BadFdError)?;264265// SAFETY: `bindings::fget` created a refcount, and we pass ownership of it to the `ARef`.266//267// INVARIANT: This file is in the fd table on this thread, so either all `fdget_pos` calls268// are on this thread, or the file is shared, in which case `fdget_pos` calls took the269// `f_pos_lock` mutex.270Ok(unsafe { ARef::from_raw(ptr.cast()) })271}272273/// Creates a reference to a [`LocalFile`] from a valid pointer.274///275/// # Safety276///277/// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is278/// positive for the duration of `'a`.279/// * The caller must ensure that if there is an active call to `fdget_pos` that did not take280/// the `f_pos_lock` mutex, then that call is on the current thread.281#[inline]282pub unsafe fn from_raw_file<'a>(ptr: *const bindings::file) -> &'a LocalFile {283// SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the284// duration of `'a`. The cast is okay because `LocalFile` is `repr(transparent)`.285//286// INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.287unsafe { &*ptr.cast() }288}289290/// Assume that there are no active `fdget_pos` calls that prevent us from sharing this file.291///292/// This makes it safe to transfer this file to other threads. No checks are performed, and293/// using it incorrectly may lead to a data race on the file position if the file is shared294/// with another thread.295///296/// This method is intended to be used together with [`LocalFile::fget`] when the caller knows297/// statically that there are no `fdget_pos` calls on the current thread. For example, you298/// might use it when calling `fget` from an ioctl, since ioctls usually do not touch the file299/// position.300///301/// # Safety302///303/// There must not be any active `fdget_pos` calls on the current thread.304#[inline]305pub unsafe fn assume_no_fdget_pos(me: ARef<LocalFile>) -> ARef<File> {306// INVARIANT: There are no `fdget_pos` calls on the current thread, and by the type307// invariants, if there is a `fdget_pos` call on another thread, then it took the308// `f_pos_lock` mutex.309//310// SAFETY: `LocalFile` and `File` have the same layout.311unsafe { ARef::from_raw(ARef::into_raw(me).cast()) }312}313314/// Returns a raw pointer to the inner C struct.315#[inline]316pub fn as_ptr(&self) -> *mut bindings::file {317self.inner.get()318}319320/// Returns the credentials of the task that originally opened the file.321pub fn cred(&self) -> &Credential {322// SAFETY: It's okay to read the `f_cred` field without synchronization because `f_cred` is323// never changed after initialization of the file.324let ptr = unsafe { (*self.as_ptr()).f_cred };325326// SAFETY: The signature of this function ensures that the caller will only access the327// returned credential while the file is still valid, and the C side ensures that the328// credential stays valid at least as long as the file.329unsafe { Credential::from_ptr(ptr) }330}331332/// Returns the flags associated with the file.333///334/// The flags are a combination of the constants in [`flags`].335#[inline]336pub fn flags(&self) -> u32 {337// This `read_volatile` is intended to correspond to a READ_ONCE call.338//339// SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.340//341// FIXME(read_once): Replace with `read_once` when available on the Rust side.342unsafe { core::ptr::addr_of!((*self.as_ptr()).f_flags).read_volatile() }343}344}345346impl File {347/// Creates a reference to a [`File`] from a valid pointer.348///349/// # Safety350///351/// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is352/// positive for the duration of `'a`.353/// * The caller must ensure that if there are active `fdget_pos` calls on this file, then they354/// took the `f_pos_lock` mutex.355#[inline]356pub unsafe fn from_raw_file<'a>(ptr: *const bindings::file) -> &'a File {357// SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the358// duration of `'a`. The cast is okay because `File` is `repr(transparent)`.359//360// INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.361unsafe { &*ptr.cast() }362}363}364365// Make LocalFile methods available on File.366impl core::ops::Deref for File {367type Target = LocalFile;368#[inline]369fn deref(&self) -> &LocalFile {370// SAFETY: The caller provides a `&File`, and since it is a reference, it must point at a371// valid file for the desired duration.372//373// By the type invariants, there are no `fdget_pos` calls that did not take the374// `f_pos_lock` mutex.375unsafe { LocalFile::from_raw_file(core::ptr::from_ref(self).cast()) }376}377}378379/// A file descriptor reservation.380///381/// This allows the creation of a file descriptor in two steps: first, we reserve a slot for it,382/// then we commit or drop the reservation. The first step may fail (e.g., the current process ran383/// out of available slots), but commit and drop never fail (and are mutually exclusive).384///385/// Dropping the reservation happens in the destructor of this type.386///387/// # Invariants388///389/// The fd stored in this struct must correspond to a reserved file descriptor of the current task.390pub struct FileDescriptorReservation {391fd: u32,392/// Prevent values of this type from being moved to a different task.393///394/// The `fd_install` and `put_unused_fd` functions assume that the value of `current` is395/// unchanged since the call to `get_unused_fd_flags`. By adding this marker to this type, we396/// prevent it from being moved across task boundaries, which ensures that `current` does not397/// change while this value exists.398_not_send: NotThreadSafe,399}400401impl FileDescriptorReservation {402/// Creates a new file descriptor reservation.403#[inline]404pub fn get_unused_fd_flags(flags: u32) -> Result<Self> {405// SAFETY: FFI call, there are no safety requirements on `flags`.406let fd: i32 = unsafe { bindings::get_unused_fd_flags(flags) };407to_result(fd)?;408409Ok(Self {410fd: fd as u32,411_not_send: NotThreadSafe,412})413}414415/// Returns the file descriptor number that was reserved.416#[inline]417pub fn reserved_fd(&self) -> u32 {418self.fd419}420421/// Commits the reservation.422///423/// The previously reserved file descriptor is bound to `file`. This method consumes the424/// [`FileDescriptorReservation`], so it will not be usable after this call.425#[inline]426pub fn fd_install(self, file: ARef<File>) {427// SAFETY: `self.fd` was previously returned by `get_unused_fd_flags`. We have not yet used428// the fd, so it is still valid, and `current` still refers to the same task, as this type429// cannot be moved across task boundaries.430//431// Furthermore, the file pointer is guaranteed to own a refcount by its type invariants,432// and we take ownership of that refcount by not running the destructor below.433// Additionally, the file is known to not have any non-shared `fdget_pos` calls, so even if434// this process starts using the file position, this will not result in a data race on the435// file position.436unsafe { bindings::fd_install(self.fd, file.as_ptr()) };437438// `fd_install` consumes both the file descriptor and the file reference, so we cannot run439// the destructors.440core::mem::forget(self);441core::mem::forget(file);442}443}444445impl Drop for FileDescriptorReservation {446#[inline]447fn drop(&mut self) {448// SAFETY: By the type invariants of this type, `self.fd` was previously returned by449// `get_unused_fd_flags`. We have not yet used the fd, so it is still valid, and `current`450// still refers to the same task, as this type cannot be moved across task boundaries.451unsafe { bindings::put_unused_fd(self.fd) };452}453}454455/// Represents the [`EBADF`] error code.456///457/// Used for methods that can only fail with [`EBADF`].458#[derive(Copy, Clone, Eq, PartialEq)]459pub struct BadFdError;460461impl From<BadFdError> for Error {462#[inline]463fn from(_: BadFdError) -> Error {464EBADF465}466}467468impl fmt::Debug for BadFdError {469fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {470f.pad("EBADF")471}472}473474475