From: Ariel Miculas <amiculas@cisco.com>
To: rust-for-linux@vger.kernel.org
Cc: linux-kernel@vger.kernel.org, linux-fsdevel@vger.kernel.org,
tycho@tycho.pizza, brauner@kernel.org, viro@zeniv.linux.org.uk,
ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com,
shallyn@cisco.com, Ariel Miculas <amiculas@cisco.com>
Subject: [RFC PATCH v3 12/22] rust: file: Add support for reading files using their path
Date: Thu, 16 May 2024 22:03:35 +0300 [thread overview]
Message-ID: <20240516190345.957477-13-amiculas@cisco.com> (raw)
In-Reply-To: <20240516190345.957477-1-amiculas@cisco.com>
Implement from_path, from_path_in_root_mnt, read_with_offset,
read_to_end and get_file_size methods for a RegularFile newtype.
`kernel_read_file` is used under the hood for reading files.
These functions will be used for reading the PuzzleFS metadata files and
the chunks in the data store.
Signed-off-by: Ariel Miculas <amiculas@cisco.com>
---
rust/kernel/error.rs | 2 +-
rust/kernel/file.rs | 124 ++++++++++++++++++++++++++++++++++++++++++-
2 files changed, 124 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs
index edada157879a..3cf916bc884f 100644
--- a/rust/kernel/error.rs
+++ b/rust/kernel/error.rs
@@ -263,7 +263,7 @@ pub fn to_result(err: core::ffi::c_int) -> Result {
/// from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
/// }
/// ```
-pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
+pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
// CAST: Casting a pointer to `*const core::ffi::c_void` is always valid.
let const_ptr: *const core::ffi::c_void = ptr.cast();
// SAFETY: The FFI function does not deref the pointer.
diff --git a/rust/kernel/file.rs b/rust/kernel/file.rs
index 99657adf2472..c381cc297f3a 100644
--- a/rust/kernel/file.rs
+++ b/rust/kernel/file.rs
@@ -5,11 +5,16 @@
//! C headers: [`include/linux/fs.h`](../../../../include/linux/fs.h) and
//! [`include/linux/file.h`](../../../../include/linux/file.h)
+use crate::alloc::flags::GFP_KERNEL;
+use crate::alloc::vec_ext::VecExt;
use crate::{
bindings,
- error::{code::*, Error, Result},
+ error::{code::*, from_err_ptr, Error, Result},
+ mount::Vfsmount,
+ str::CStr,
types::{ARef, AlwaysRefCounted, Opaque},
};
+use alloc::vec::Vec;
use core::ptr;
/// Flags associated with a [`File`].
@@ -164,6 +169,123 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
}
}
+/// A newtype over file, specific to regular files
+pub struct RegularFile(ARef<File>);
+impl RegularFile {
+ /// Creates a new instance of Self if the file is a regular file
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure file_ptr.f_inode is initialized to a valid pointer (e.g. file_ptr is
+ /// a pointer returned by path_openat); It must also ensure that file_ptr's reference count was
+ /// incremented at least once
+ unsafe fn create_if_regular(file_ptr: *mut bindings::file) -> Result<RegularFile> {
+ let file_ptr = ptr::NonNull::new(file_ptr).ok_or(ENOENT)?;
+ // SAFETY: file_ptr is a NonNull pointer
+ let inode = unsafe { core::ptr::addr_of!((*file_ptr.as_ptr()).f_inode).read() };
+ // SAFETY: the caller must ensure f_inode is initialized to a valid pointer
+ let inode_mode = unsafe { (*inode).i_mode as u32 };
+ if bindings::S_IFMT & inode_mode != bindings::S_IFREG {
+ return Err(EINVAL);
+ }
+ // SAFETY: the safety requirements state that file_ptr's reference count was incremented at
+ // least once
+ Ok(RegularFile(unsafe { ARef::from_raw(file_ptr.cast()) }))
+ }
+ /// Constructs a new [`struct file`] wrapper from a path.
+ pub fn from_path(filename: &CStr, flags: i32, mode: u16) -> Result<Self> {
+ // SAFETY: filename is a reference, so it's a valid pointer
+ let file_ptr = unsafe {
+ from_err_ptr(bindings::filp_open(
+ filename.as_ptr().cast::<i8>(),
+ flags,
+ mode,
+ ))?
+ };
+
+ // SAFETY: `filp_open` initializes the refcount with 1
+ unsafe { Self::create_if_regular(file_ptr) }
+ }
+
+ /// Constructs a new [`struct file`] wrapper from a path and a vfsmount.
+ pub fn from_path_in_root_mnt(
+ mount: &Vfsmount,
+ filename: &CStr,
+ flags: i32,
+ mode: u16,
+ ) -> Result<Self> {
+ let mnt = mount.get();
+ // construct a path from vfsmount, see file_open_root_mnt
+ let raw_path = bindings::path {
+ mnt,
+ // SAFETY: Vfsmount structure stores a valid vfsmount object
+ dentry: unsafe { (*mnt).mnt_root },
+ };
+ let file_ptr = unsafe {
+ // SAFETY: raw_path and filename are both references
+ from_err_ptr(bindings::file_open_root(
+ &raw_path,
+ filename.as_ptr().cast::<i8>(),
+ flags,
+ mode,
+ ))?
+ };
+ // SAFETY: `file_open_root` initializes the refcount with 1
+ unsafe { Self::create_if_regular(file_ptr) }
+ }
+
+ /// Read from the file into the specified buffer
+ pub fn read_with_offset(&self, buf: &mut [u8], offset: u64) -> Result<usize> {
+ // kernel_read_file expects a pointer to a "void *" buffer
+ let mut ptr_to_buf = buf.as_mut_ptr() as *mut core::ffi::c_void;
+ // Unless we give a non-null pointer to the file size:
+ // 1. we cannot give a non-zero value for the offset
+ // 2. we cannot have offset 0 and buffer_size > file_size
+ let mut file_size = 0;
+
+ // SAFETY: 'file' is valid because it's taken from Self, 'buf' and 'file_size` are
+ // references to the stack variables 'ptr_to_buf' and 'file_size'; ptr_to_buf is also
+ // a pointer to a valid buffer that was obtained from a reference
+ let result = unsafe {
+ bindings::kernel_read_file(
+ self.0 .0.get(),
+ offset.try_into()?,
+ &mut ptr_to_buf,
+ buf.len(),
+ &mut file_size,
+ bindings::kernel_read_file_id_READING_UNKNOWN,
+ )
+ };
+
+ // kernel_read_file returns the number of bytes read on success or negative on error.
+ if result < 0 {
+ return Err(Error::from_errno(result.try_into()?));
+ }
+
+ Ok(result.try_into()?)
+ }
+
+ /// Allocate and return a vector containing the contents of the entire file
+ pub fn read_to_end(&self) -> Result<Vec<u8>> {
+ let file_size = self.get_file_size()?;
+ let mut buffer = Vec::with_capacity(file_size, GFP_KERNEL)?;
+ buffer.resize(file_size, 0, GFP_KERNEL)?;
+ self.read_with_offset(&mut buffer, 0)?;
+ Ok(buffer)
+ }
+
+ fn get_file_size(&self) -> Result<usize> {
+ // SAFETY: 'file' is valid because it's taken from Self
+ let file_size = unsafe { bindings::i_size_read((*self.0 .0.get()).f_inode) };
+
+ if file_size < 0 {
+ return Err(EINVAL);
+ }
+
+ Ok(file_size.try_into()?)
+ }
+}
+
/// Represents the EBADF error code.
///
/// Used for methods that can only fail with EBADF.
--
2.34.1
next prev parent reply other threads:[~2024-05-16 19:04 UTC|newest]
Thread overview: 24+ messages / expand[flat|nested] mbox.gz Atom feed top
2024-05-16 19:03 [RFC PATCH v3 00/22] Rust PuzzleFS filesystem driver Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 01/22] kernel: configs: add qemu-busybox-min.config Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 02/22] rust: hex: import crate Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 03/22] rust: hex: add SPDX license identifiers Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 04/22] rust: Kbuild: enable `hex` Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 05/22] rust: hex: add encode_hex_iter and encode_hex_upper_iter methods Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 06/22] rust: capnp: import crate Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 07/22] rust: capnp: add SPDX License Identifiers Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 08/22] rust: capnp: return an error when trying to display floating point values Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 09/22] rust: Kbuild: enable `capnp` Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 10/22] rust: kernel: add an abstraction over vfsmount to allow cloning a new private mount Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 11/22] rust: file: add bindings for `struct file` Ariel Miculas
2024-05-16 19:03 ` Ariel Miculas [this message]
2024-05-16 19:03 ` [RFC PATCH v3 13/22] fs: puzzlefs: Implement the initial version of PuzzleFS Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 14/22] rust: kernel: add from_iter_fallible for Vec<T> Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 15/22] kernel: configs: add puzzlefs config fragment Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 16/22] scripts: add fs directory to rust-analyzer Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 17/22] fs: puzzlefs: add extended attributes support Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 18/22] rust: add improved version of `ForeignOwnable::borrow_mut` Ariel Miculas
2024-05-17 8:37 ` Alice Ryhl
2024-05-16 19:03 ` [RFC PATCH v3 19/22] Add borrow_mut implementation to a ForeignOwnable CString Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 20/22] rust: add support for file system parameters Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 21/22] fs: puzzlefs: add oci_root_dir and image_manifest mount parameters Ariel Miculas
2024-05-16 19:03 ` [RFC PATCH v3 22/22] fs: puzzlefs: implement statfs for puzzlefs Ariel Miculas
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20240516190345.957477-13-amiculas@cisco.com \
--to=amiculas@cisco.com \
--cc=alex.gaynor@gmail.com \
--cc=brauner@kernel.org \
--cc=linux-fsdevel@vger.kernel.org \
--cc=linux-kernel@vger.kernel.org \
--cc=ojeda@kernel.org \
--cc=rust-for-linux@vger.kernel.org \
--cc=shallyn@cisco.com \
--cc=tycho@tycho.pizza \
--cc=viro@zeniv.linux.org.uk \
--cc=wedsonaf@gmail.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).