// SPDX-License-Identifier: GPL-2.012// Copyright (C) 2024 Google LLC.34//! Kernel IO callbacks.5//!6//! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)78use core::marker::PhantomData;9use core::ptr::NonNull;10use kernel::types::ForeignOwnable;1112/// Wrapper for the kernel's `struct kiocb`.13///14/// Currently this abstractions is incomplete and is essentially just a tuple containing a15/// reference to a file and a file position.16///17/// The type `T` represents the filesystem or driver specific data associated with the file.18///19/// # Invariants20///21/// `inner` points at a valid `struct kiocb` whose file has the type `T` as its private data.22pub struct Kiocb<'a, T> {23inner: NonNull<bindings::kiocb>,24_phantom: PhantomData<&'a T>,25}2627impl<'a, T: ForeignOwnable> Kiocb<'a, T> {28/// Create a `Kiocb` from a raw pointer.29///30/// # Safety31///32/// The pointer must reference a valid `struct kiocb` for the duration of `'a`. The private33/// data of the file must be `T`.34pub unsafe fn from_raw(kiocb: *mut bindings::kiocb) -> Self {35Self {36// SAFETY: If a pointer is valid it is not null.37inner: unsafe { NonNull::new_unchecked(kiocb) },38_phantom: PhantomData,39}40}4142/// Access the underlying `struct kiocb` directly.43pub fn as_raw(&self) -> *mut bindings::kiocb {44self.inner.as_ptr()45}4647/// Get the filesystem or driver specific data associated with the file.48pub fn file(&self) -> <T as ForeignOwnable>::Borrowed<'a> {49// SAFETY: We have shared access to this kiocb and hence the underlying file, so we can50// read the file's private data.51let private = unsafe { (*(*self.as_raw()).ki_filp).private_data };52// SAFETY: The kiocb has shared access to the private data.53unsafe { <T as ForeignOwnable>::borrow(private) }54}5556/// Gets the current value of `ki_pos`.57pub fn ki_pos(&self) -> i64 {58// SAFETY: We have shared access to the kiocb, so we can read its `ki_pos` field.59unsafe { (*self.as_raw()).ki_pos }60}6162/// Gets a mutable reference to the `ki_pos` field.63pub fn ki_pos_mut(&mut self) -> &mut i64 {64// SAFETY: We have exclusive access to the kiocb, so we can write to `ki_pos`.65unsafe { &mut (*self.as_raw()).ki_pos }66}67}686970