// SPDX-License-Identifier: GPL-2.01// Copyright (C) 2025 Google LLC.23use super::{BinaryReader, BinaryWriter, Reader, Writer};4use crate::debugfs::callback_adapters::Adapter;5use crate::fmt;6use crate::fs::file;7use crate::prelude::*;8use crate::seq_file::SeqFile;9use crate::seq_print;10use crate::uaccess::UserSlice;11use core::marker::PhantomData;1213#[cfg(CONFIG_DEBUG_FS)]14use core::ops::Deref;1516/// # Invariant17///18/// `FileOps<T>` will always contain an `operations` which is safe to use for a file backed19/// off an inode which has a pointer to a `T` in its private data that is safe to convert20/// into a reference.21pub(super) struct FileOps<T> {22#[cfg(CONFIG_DEBUG_FS)]23operations: bindings::file_operations,24#[cfg(CONFIG_DEBUG_FS)]25mode: u16,26_phantom: PhantomData<T>,27}2829impl<T> FileOps<T> {30/// # Safety31///32/// The caller asserts that the provided `operations` is safe to use for a file whose33/// inode has a pointer to `T` in its private data that is safe to convert into a reference.34const unsafe fn new(operations: bindings::file_operations, mode: u16) -> Self {35Self {36#[cfg(CONFIG_DEBUG_FS)]37operations,38#[cfg(CONFIG_DEBUG_FS)]39mode,40_phantom: PhantomData,41}42}4344#[cfg(CONFIG_DEBUG_FS)]45pub(crate) const fn mode(&self) -> u16 {46self.mode47}48}4950impl<T: Adapter> FileOps<T> {51pub(super) const fn adapt(&self) -> &FileOps<T::Inner> {52// SAFETY: `Adapter` asserts that `T` can be legally cast to `T::Inner`.53unsafe { core::mem::transmute(self) }54}55}5657#[cfg(CONFIG_DEBUG_FS)]58impl<T> Deref for FileOps<T> {59type Target = bindings::file_operations;6061fn deref(&self) -> &Self::Target {62&self.operations63}64}6566struct WriterAdapter<T>(T);6768impl<'a, T: Writer> fmt::Display for WriterAdapter<&'a T> {69fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {70self.0.write(f)71}72}7374/// Implements `open` for `file_operations` via `single_open` to fill out a `seq_file`.75///76/// # Safety77///78/// * `inode`'s private pointer must point to a value of type `T` which will outlive the `inode`79/// and will not have any unique references alias it during the call.80/// * `file` must point to a live, not-yet-initialized file object.81unsafe extern "C" fn writer_open<T: Writer + Sync>(82inode: *mut bindings::inode,83file: *mut bindings::file,84) -> c_int {85// SAFETY: The caller ensures that `inode` is a valid pointer.86let data = unsafe { (*inode).i_private };87// SAFETY:88// * `file` is acceptable by caller precondition.89// * `print_act` will be called on a `seq_file` with private data set to the third argument,90// so we meet its safety requirements.91// * The `data` pointer passed in the third argument is a valid `T` pointer that outlives92// this call by caller preconditions.93unsafe { bindings::single_open(file, Some(writer_act::<T>), data) }94}9596/// Prints private data stashed in a seq_file to that seq file.97///98/// # Safety99///100/// `seq` must point to a live `seq_file` whose private data is a valid pointer to a `T` which may101/// not have any unique references alias it during the call.102unsafe extern "C" fn writer_act<T: Writer + Sync>(103seq: *mut bindings::seq_file,104_: *mut c_void,105) -> c_int {106// SAFETY: By caller precondition, this pointer is valid pointer to a `T`, and107// there are not and will not be any unique references until we are done.108let data = unsafe { &*((*seq).private.cast::<T>()) };109// SAFETY: By caller precondition, `seq_file` points to a live `seq_file`, so we can lift110// it.111let seq_file = unsafe { SeqFile::from_raw(seq) };112seq_print!(seq_file, "{}", WriterAdapter(data));1130114}115116// Work around lack of generic const items.117pub(crate) trait ReadFile<T> {118const FILE_OPS: FileOps<T>;119}120121impl<T: Writer + Sync> ReadFile<T> for T {122const FILE_OPS: FileOps<T> = {123let operations = bindings::file_operations {124read: Some(bindings::seq_read),125llseek: Some(bindings::seq_lseek),126release: Some(bindings::single_release),127open: Some(writer_open::<Self>),128// SAFETY: `file_operations` supports zeroes in all fields.129..unsafe { core::mem::zeroed() }130};131// SAFETY: `operations` is all stock `seq_file` implementations except for `writer_open`.132// `open`'s only requirement beyond what is provided to all open functions is that the133// inode's data pointer must point to a `T` that will outlive it, which matches the134// `FileOps` requirements.135unsafe { FileOps::new(operations, 0o400) }136};137}138139fn read<T: Reader + Sync>(data: &T, buf: *const c_char, count: usize) -> isize {140let mut reader = UserSlice::new(UserPtr::from_ptr(buf as *mut c_void), count).reader();141142if let Err(e) = data.read_from_slice(&mut reader) {143return e.to_errno() as isize;144}145146count as isize147}148149/// # Safety150///151/// `file` must be a valid pointer to a `file` struct.152/// The `private_data` of the file must contain a valid pointer to a `seq_file` whose153/// `private` data in turn points to a `T` that implements `Reader`.154/// `buf` must be a valid user-space buffer.155pub(crate) unsafe extern "C" fn write<T: Reader + Sync>(156file: *mut bindings::file,157buf: *const c_char,158count: usize,159_ppos: *mut bindings::loff_t,160) -> isize {161// SAFETY: The file was opened with `single_open`, which sets `private_data` to a `seq_file`.162let seq = unsafe { &mut *((*file).private_data.cast::<bindings::seq_file>()) };163// SAFETY: By caller precondition, this pointer is live and points to a value of type `T`.164let data = unsafe { &*(seq.private as *const T) };165read(data, buf, count)166}167168// A trait to get the file operations for a type.169pub(crate) trait ReadWriteFile<T> {170const FILE_OPS: FileOps<T>;171}172173impl<T: Writer + Reader + Sync> ReadWriteFile<T> for T {174const FILE_OPS: FileOps<T> = {175let operations = bindings::file_operations {176open: Some(writer_open::<T>),177read: Some(bindings::seq_read),178write: Some(write::<T>),179llseek: Some(bindings::seq_lseek),180release: Some(bindings::single_release),181// SAFETY: `file_operations` supports zeroes in all fields.182..unsafe { core::mem::zeroed() }183};184// SAFETY: `operations` is all stock `seq_file` implementations except for `writer_open`185// and `write`.186// `writer_open`'s only requirement beyond what is provided to all open functions is that187// the inode's data pointer must point to a `T` that will outlive it, which matches the188// `FileOps` requirements.189// `write` only requires that the file's private data pointer points to `seq_file`190// which points to a `T` that will outlive it, which matches what `writer_open`191// provides.192unsafe { FileOps::new(operations, 0o600) }193};194}195196/// # Safety197///198/// `inode` must be a valid pointer to an `inode` struct.199/// `file` must be a valid pointer to a `file` struct.200unsafe extern "C" fn write_only_open(201inode: *mut bindings::inode,202file: *mut bindings::file,203) -> c_int {204// SAFETY: The caller ensures that `inode` and `file` are valid pointers.205unsafe { (*file).private_data = (*inode).i_private };2060207}208209/// # Safety210///211/// * `file` must be a valid pointer to a `file` struct.212/// * The `private_data` of the file must contain a valid pointer to a `T` that implements213/// `Reader`.214/// * `buf` must be a valid user-space buffer.215pub(crate) unsafe extern "C" fn write_only_write<T: Reader + Sync>(216file: *mut bindings::file,217buf: *const c_char,218count: usize,219_ppos: *mut bindings::loff_t,220) -> isize {221// SAFETY: The caller ensures that `file` is a valid pointer and that `private_data` holds a222// valid pointer to `T`.223let data = unsafe { &*((*file).private_data as *const T) };224read(data, buf, count)225}226227pub(crate) trait WriteFile<T> {228const FILE_OPS: FileOps<T>;229}230231impl<T: Reader + Sync> WriteFile<T> for T {232const FILE_OPS: FileOps<T> = {233let operations = bindings::file_operations {234open: Some(write_only_open),235write: Some(write_only_write::<T>),236llseek: Some(bindings::noop_llseek),237// SAFETY: `file_operations` supports zeroes in all fields.238..unsafe { core::mem::zeroed() }239};240// SAFETY:241// * `write_only_open` populates the file private data with the inode private data242// * `write_only_write`'s only requirement is that the private data of the file point to243// a `T` and be legal to convert to a shared reference, which `write_only_open`244// satisfies.245unsafe { FileOps::new(operations, 0o200) }246};247}248249extern "C" fn blob_read<T: BinaryWriter>(250file: *mut bindings::file,251buf: *mut c_char,252count: usize,253ppos: *mut bindings::loff_t,254) -> isize {255// SAFETY:256// - `file` is a valid pointer to a `struct file`.257// - The type invariant of `FileOps` guarantees that `private_data` points to a valid `T`.258let this = unsafe { &*((*file).private_data.cast::<T>()) };259260// SAFETY:261// - `ppos` is a valid `file::Offset` pointer.262// - We have exclusive access to `ppos`.263let pos: &mut file::Offset = unsafe { &mut *ppos };264265let mut writer = UserSlice::new(UserPtr::from_ptr(buf.cast()), count).writer();266267let ret = || -> Result<isize> {268let written = this.write_to_slice(&mut writer, pos)?;269270Ok(written.try_into()?)271}();272273match ret {274Ok(n) => n,275Err(e) => e.to_errno() as isize,276}277}278279/// Representation of [`FileOps`] for read only binary files.280pub(crate) trait BinaryReadFile<T> {281const FILE_OPS: FileOps<T>;282}283284impl<T: BinaryWriter + Sync> BinaryReadFile<T> for T {285const FILE_OPS: FileOps<T> = {286let operations = bindings::file_operations {287read: Some(blob_read::<T>),288llseek: Some(bindings::default_llseek),289open: Some(bindings::simple_open),290// SAFETY: `file_operations` supports zeroes in all fields.291..unsafe { core::mem::zeroed() }292};293294// SAFETY:295// - The private data of `struct inode` does always contain a pointer to a valid `T`.296// - `simple_open()` stores the `struct inode`'s private data in the private data of the297// corresponding `struct file`.298// - `blob_read()` re-creates a reference to `T` from the `struct file`'s private data.299// - `default_llseek()` does not access the `struct file`'s private data.300unsafe { FileOps::new(operations, 0o400) }301};302}303304extern "C" fn blob_write<T: BinaryReader>(305file: *mut bindings::file,306buf: *const c_char,307count: usize,308ppos: *mut bindings::loff_t,309) -> isize {310// SAFETY:311// - `file` is a valid pointer to a `struct file`.312// - The type invariant of `FileOps` guarantees that `private_data` points to a valid `T`.313let this = unsafe { &*((*file).private_data.cast::<T>()) };314315// SAFETY:316// - `ppos` is a valid `file::Offset` pointer.317// - We have exclusive access to `ppos`.318let pos: &mut file::Offset = unsafe { &mut *ppos };319320let mut reader = UserSlice::new(UserPtr::from_ptr(buf.cast_mut().cast()), count).reader();321322let ret = || -> Result<isize> {323let read = this.read_from_slice(&mut reader, pos)?;324325Ok(read.try_into()?)326}();327328match ret {329Ok(n) => n,330Err(e) => e.to_errno() as isize,331}332}333334/// Representation of [`FileOps`] for write only binary files.335pub(crate) trait BinaryWriteFile<T> {336const FILE_OPS: FileOps<T>;337}338339impl<T: BinaryReader + Sync> BinaryWriteFile<T> for T {340const FILE_OPS: FileOps<T> = {341let operations = bindings::file_operations {342write: Some(blob_write::<T>),343llseek: Some(bindings::default_llseek),344open: Some(bindings::simple_open),345// SAFETY: `file_operations` supports zeroes in all fields.346..unsafe { core::mem::zeroed() }347};348349// SAFETY:350// - The private data of `struct inode` does always contain a pointer to a valid `T`.351// - `simple_open()` stores the `struct inode`'s private data in the private data of the352// corresponding `struct file`.353// - `blob_write()` re-creates a reference to `T` from the `struct file`'s private data.354// - `default_llseek()` does not access the `struct file`'s private data.355unsafe { FileOps::new(operations, 0o200) }356};357}358359/// Representation of [`FileOps`] for read/write binary files.360pub(crate) trait BinaryReadWriteFile<T> {361const FILE_OPS: FileOps<T>;362}363364impl<T: BinaryWriter + BinaryReader + Sync> BinaryReadWriteFile<T> for T {365const FILE_OPS: FileOps<T> = {366let operations = bindings::file_operations {367read: Some(blob_read::<T>),368write: Some(blob_write::<T>),369llseek: Some(bindings::default_llseek),370open: Some(bindings::simple_open),371// SAFETY: `file_operations` supports zeroes in all fields.372..unsafe { core::mem::zeroed() }373};374375// SAFETY:376// - The private data of `struct inode` does always contain a pointer to a valid `T`.377// - `simple_open()` stores the `struct inode`'s private data in the private data of the378// corresponding `struct file`.379// - `blob_read()` re-creates a reference to `T` from the `struct file`'s private data.380// - `blob_write()` re-creates a reference to `T` from the `struct file`'s private data.381// - `default_llseek()` does not access the `struct file`'s private data.382unsafe { FileOps::new(operations, 0o600) }383};384}385386387