Skip to contentSkip to conversation

File abstractions needed by Rust Binder

PATCH Superseded Alice Ryhl 6 participants 25 messages Jul 25, 2024 – Aug 8, 2024

Subsystems (6)

v8 of 10 Superseded Latest is v10 →

lore
Share & tools
lore

Alice Ryhl

author maintainer
#0 lore raw

v8 cover File abstractions needed by Rust Binder

This patchset contains the file abstractions needed by the Rust implementation of the Binder driver.

Please see the Rust Binder RFC for usage examples:
https://lore.kernel.org/rust-for-linux/[email protected]/

Users of "rust: types: add NotThreadSafe":
[PATCH 5/9] rust: file: add FileDescriptorReservation

Users of "rust: task: add Task::current_raw":
[PATCH 7/9] rust: file: add Kuid wrapper [PATCH 8/9] rust: file: add DeferredFdCloser

Users of "rust: file: add Rust abstraction for struct file":
[PATCH RFC 02/20] rust_binder: add binderfs support to Rust binder [PATCH RFC 03/20] rust_binder: add threading support

Users of "rust: cred: add Rust abstraction for struct cred":
[PATCH RFC 05/20] rust_binder: add nodes and context managers [PATCH RFC 06/20] rust_binder: add oneway transactions [PATCH RFC 11/20] rust_binder: send nodes in transaction [PATCH RFC 13/20] rust_binder: add BINDER_TYPE_FD support

Users of "rust: security: add abstraction for secctx":
[PATCH RFC 06/20] rust_binder: add oneway transactions

Users of "rust: file: add FileDescriptorReservation":
[PATCH RFC 13/20] rust_binder: add BINDER_TYPE_FD support [PATCH RFC 14/20] rust_binder: add BINDER_TYPE_FDA support

Users of "rust: file: add Kuid wrapper":
[PATCH RFC 05/20] rust_binder: add nodes and context managers [PATCH RFC 06/20] rust_binder: add oneway transactions

Users of "rust: file: add abstraction for poll_table":
[PATCH RFC 07/20] rust_binder: add epoll support

This patchset has some uses of read_volatile in place of READ_ONCE. Please see the following rfc for context on this:
https://lore.kernel.org/all/[email protected]/

---
Changes in v8:
- Rename File::from_ptr to File::from_raw_file.
- Mention that NotThreadSafe also affects Sync.
- Fix copyright lines.
- Move rust/kernel/file.rs to rust/kernel/fs/file.rs to reduce conflicts with Wedson's vfs patches.
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- Replace file sharing modes with File / LocalFile.
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- Introduce file sharing modes.
- Rewrite most documentation for struct file wrapper.
- Drop DeferredFdCloser. It will be sent later when it can be placed
somewhere where only Rust Binder can use it.
- Rebase on top of rust-next: 97ab3e8eec0c ("rust: alloc: fix dangling pointer in VecExt<T>::reserve()")
- Link to v5: https://lore.kernel.org/r/[email protected]

Changes in v5:
- Pass a null pointer to task_tgid_nr_ns.
- Fix some typos and other formatting issues.
- Add Reviewed-by where appropriate.
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- Moved the two really simple patches to the beginning of the patchset.
- Update Send safety comments.
- Use srctree relative links.
- Mention that Credential::euid is immutable.
- Update some safety comments to mention the invariant on Self.
- Use new name for close_fd_get_file.
- Move safety comments on DeferredFdCloser around and be more explicit about how many refcounts we own.
- Reword safety comments related to _qproc.
- Add Reviewed-by where appropriate.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Completely rewrite comments about refcounting in the first patch.
- And add a note to the documentation in fs/file.c.
- Discuss speculation gadgets in commit message for the Kuid wrapper.
- Introduce NotThreadSafe and Task::current_raw patches and use them in later patches.
- Improve safety comments in DeferredFdCloser.
- Some other minor changes.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Update various docs and safety comments.
- Rename method names to match the C name.
- Use ordinary read instead of READ_ONCE in File::cred.
- Changed null check in secctx.
- Add type alias for PhantomData in FileDescriptorReservation.
- Use Kuid::from_raw in Kuid::current_euid.
- Make DeferredFdCloser fallible if it is unable to schedule a task
work. And also schedule the task work *before* closing the file.
- Moved PollCondVar to rust/kernel/sync.
- Updated PollCondVar to use wake_up_pollfree.
- Link to v1: https://lore.kernel.org/all/[email protected]/

Link to RFC:
https://lore.kernel.org/all/[email protected]/

---
Alice Ryhl (5):
rust: types: add NotThreadSafe
rust: task: add Task::current_raw
rust: security: add abstraction for secctx
rust: file: add Kuid wrapper
rust: file: add abstraction for poll_table

Wedson Almeida Filho (3):
rust: file: add Rust abstraction for struct file
rust: cred: add Rust abstraction for struct cred
rust: file: add FileDescriptorReservation

 fs/file.c                       |   7 +
 rust/bindings/bindings_helper.h |   6 +
 rust/helpers.c                  |  86 ++++++++
 rust/kernel/cred.rs             |  85 ++++++++
 rust/kernel/fs.rs               |   8 +
 rust/kernel/fs/file.rs          | 461 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   3 +
 rust/kernel/security.rs         |  74 +++++++
 rust/kernel/sync.rs             |   1 +
 rust/kernel/sync/lock.rs        |  13 +-
 rust/kernel/sync/poll.rs        | 121 +++++++++++
 rust/kernel/task.rs             |  91 +++++++-
 rust/kernel/types.rs            |  29 +++
 13 files changed, 973 insertions(+), 12 deletions(-)

---
base-commit: b1263411112305acf2af728728591465becb45b0
change-id: 20231123-alice-file-525b98e8a724

Best regards,

Signature · 1 line
Alice Ryhl <[email protected]>
author maintainer
#1 lore raw

PATCH v8 1/8 rust: types: add `NotThreadSafe`

This introduces a new marker type for types that shouldn't be thread safe. By adding a field of this type to a struct, it becomes non-Send and non-Sync, which means that it cannot be accessed in any way from threads other than the one it was created on.

This is useful for APIs that require globals such as current to remain constant while the value exists.

We update two existing users in the Kernel to use this helper:

* Task::current() - moving the return type of this value to a different thread would not be safe as you can no longer be guaranteed that the current pointer remains valid.
* Lock guards. Mutexes and spinlocks should be unlocked on the same thread as where they were locked, so we enforce this using the Send trait.

There are also additional users in later patches of this patchset. See
[1] and [2] for the discussion that led to the introduction of this patch.

---
 rust/kernel/sync/lock.rs | 13 +++++++++----
 rust/kernel/task.rs      | 10 ++++++----
 rust/kernel/types.rs     | 21 +++++++++++++++++++++
 3 files changed, 36 insertions(+), 8 deletions(-)
rust/kernel/sync/lock.rs +9 -4
index f6c34ca4d819..d6e9bab114b8 100644
@@ -6,8 +6,13 @@
 //! spinlocks, raw spinlocks) to be provided with minimal effort.
 
 use super::LockClassKey;
-use crate::{init::PinInit, pin_init, str::CStr, types::Opaque, types::ScopeGuard};
-use core::{cell::UnsafeCell, marker::PhantomData, marker::PhantomPinned};
+use crate::{
+    init::PinInit,
+    pin_init,
+    str::CStr,
+    types::{NotThreadSafe, Opaque, ScopeGuard},
+};
+use core::{cell::UnsafeCell, marker::PhantomPinned};
 use macros::pin_data;
 
 pub mod mutex;
@@ -139,7 +144,7 @@ pub fn lock(&self) -> Guard<'_, T, B> {
 pub struct Guard<'a, T: ?Sized, B: Backend> {
     pub(crate) lock: &'a Lock<T, B>,
     pub(crate) state: B::GuardState,
-    _not_send: PhantomData<*mut ()>,
+    _not_send: NotThreadSafe,
 }
 
 // SAFETY: `Guard` is sync when the data protected by the lock is also sync.
@@ -191,7 +196,7 @@ pub(crate) unsafe fn new(lock: &'a Lock<T, B>, state: B::GuardState) -> Self {
         Self {
             lock,
             state,
-            _not_send: PhantomData,
+            _not_send: NotThreadSafe,
         }
     }
 }
rust/kernel/task.rs +6 -4
index 55dff7e088bf..278c623de0c6 100644
@@ -4,10 +4,12 @@
 //!
 //! C header: [`include/linux/sched.h`](srctree/include/linux/sched.h).
 
-use crate::types::Opaque;
+use crate::{
+    bindings,
+    types::{NotThreadSafe, Opaque},
+};
 use core::{
     ffi::{c_int, c_long, c_uint},
-    marker::PhantomData,
     ops::Deref,
     ptr,
 };
@@ -106,7 +108,7 @@ impl Task {
     pub unsafe fn current() -> impl Deref<Target = Task> {
         struct TaskRef<'a> {
             task: &'a Task,
-            _not_send: PhantomData<*mut ()>,
+            _not_send: NotThreadSafe,
         }
 
         impl Deref for TaskRef<'_> {
@@ -125,7 +127,7 @@ fn deref(&self) -> &Self::Target {
             // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
             // (where it could potentially outlive the caller).
             task: unsafe { &*ptr.cast() },
-            _not_send: PhantomData,
+            _not_send: NotThreadSafe,
         }
     }
 
rust/kernel/types.rs +21 -0
index bd189d646adb..bb115d730ebb 100644
@@ -473,3 +473,24 @@ unsafe impl AsBytes for str {}
 // does not have any uninitialized portions either.
 unsafe impl<T: AsBytes> AsBytes for [T] {}
 unsafe impl<T: AsBytes, const N: usize> AsBytes for [T; N] {}
+
+/// Zero-sized type to mark types not [`Send`].
+///
+/// Add this type as a field to your struct if your type should not be sent to a different task.
+/// Since [`Send`] is an auto trait, adding a single field that is `!Send` will ensure that the
+/// whole type is `!Send`.
+///
+/// If a type is `!Send` it is impossible to give control over an instance of the type to another
+/// task. This is useful to include in types that store or reference task-local information. A file
+/// descriptor is an example of such task-local information.
+///
+/// This type also makes the type `!Sync`, which prevents immutable access to the value from
+/// several threads in parallel.
+pub type NotThreadSafe = PhantomData<*mut ()>;
+
+/// Used to construct instances of type [`NotThreadSafe`] similar to how `PhantomData` is
+/// constructed.
+///
+/// [`NotThreadSafe`]: type@NotThreadSafe
+#[allow(non_upper_case_globals)]
+pub const NotThreadSafe: NotThreadSafe = PhantomData;
Signature · 1 line
2.45.2.1089.g2a221341d9-goog
maintainer
#2 lore raw

Re: [PATCH v8 1/8] rust: types: add `NotThreadSafe`

Quoted 102 lines · Alice Ryhl

This introduces a new marker type for types that shouldn't be thread safe. By adding a field of this type to a struct, it becomes non-Send and non-Sync, which means that it cannot be accessed in any way from threads other than the one it was created on.

This is useful for APIs that require globals such as current to remain constant while the value exists.

We update two existing users in the Kernel to use this helper:

* Task::current() - moving the return type of this value to a different thread would not be safe as you can no longer be guaranteed that the current pointer remains valid.
* Lock guards. Mutexes and spinlocks should be unlocked on the same thread as where they were locked, so we enforce this using the Send trait.

There are also additional users in later patches of this patchset. See
[1] and [2] for the discussion that led to the introduction of this patch.

---
 rust/kernel/sync/lock.rs | 13 +++++++++----
 rust/kernel/task.rs      | 10 ++++++----
 rust/kernel/types.rs     | 21 +++++++++++++++++++++
 3 files changed, 36 insertions(+), 8 deletions(-)
rust/kernel/sync/lock.rs +9 -4
index f6c34ca4d819..d6e9bab114b8 100644
@@ -6,8 +6,13 @@
 //! spinlocks, raw spinlocks) to be provided with minimal effort.
 
 use super::LockClassKey;
-use crate::{init::PinInit, pin_init, str::CStr, types::Opaque, types::ScopeGuard};
-use core::{cell::UnsafeCell, marker::PhantomData, marker::PhantomPinned};
+use crate::{
+    init::PinInit,
+    pin_init,
+    str::CStr,
+    types::{NotThreadSafe, Opaque, ScopeGuard},
+};
+use core::{cell::UnsafeCell, marker::PhantomPinned};
 use macros::pin_data;
 
 pub mod mutex;
@@ -139,7 +144,7 @@ pub fn lock(&self) -> Guard<'_, T, B> {
 pub struct Guard<'a, T: ?Sized, B: Backend> {
     pub(crate) lock: &'a Lock<T, B>,
     pub(crate) state: B::GuardState,
-    _not_send: PhantomData<*mut ()>,
+    _not_send: NotThreadSafe,
 }
 
 // SAFETY: `Guard` is sync when the data protected by the lock is also sync.
@@ -191,7 +196,7 @@ pub(crate) unsafe fn new(lock: &'a Lock<T, B>, state: B::GuardState) -> Self {
         Self {
             lock,
             state,
-            _not_send: PhantomData,
+            _not_send: NotThreadSafe,
         }
     }
 }
rust/kernel/task.rs +5 -3
index 55dff7e088bf..278c623de0c6 100644
@@ -4,10 +4,12 @@
 //!
 //! C header: [`include/linux/sched.h`](srctree/include/linux/sched.h).
 
-use crate::types::Opaque;
+use crate::{
+    bindings,
+    types::{NotThreadSafe, Opaque},
+};
 use core::{
     ffi::{c_int, c_long, c_uint},
-    marker::PhantomData,
     ops::Deref,
     ptr,
 };
@@ -106,7 +108,7 @@ impl Task {
     pub unsafe fn current() -> impl Deref<Target = Task> {
         struct TaskRef<'a> {
             task: &'a Task,
-            _not_send: PhantomData<*mut ()>,
+            _not_send: NotThreadSafe,
         }
 
         impl Deref for TaskRef<'_> {

rust/kernel/task.rs fn deref(&self) -> &Self::Target { · line 132

Quoted 7 lines
rust/kernel/task.rs +1 -1
@@ -125,7 +127,7 @@ fn deref(&self) -> &Self::Target {
             // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
             // (where it could potentially outlive the caller).
             task: unsafe { &*ptr.cast() },
-            _not_send: PhantomData,
+            _not_send: NotThreadSafe,
         }
     }

As per always for not being able to read rust; how does this extend to get_task_struct()? Once you've taken a reference on current, you should be free to pass it along to whomever.

author maintainer
#3 lore raw

Re: [PATCH v8 1/8] rust: types: add `NotThreadSafe`

Quoted 102 lines · Peter Zijlstra
Quoted 100 lines · Alice Ryhl

This introduces a new marker type for types that shouldn't be thread safe. By adding a field of this type to a struct, it becomes non-Send and non-Sync, which means that it cannot be accessed in any way from threads other than the one it was created on.

This is useful for APIs that require globals such as current to remain constant while the value exists.

We update two existing users in the Kernel to use this helper:

* Task::current() - moving the return type of this value to a different thread would not be safe as you can no longer be guaranteed that the current pointer remains valid.
* Lock guards. Mutexes and spinlocks should be unlocked on the same thread as where they were locked, so we enforce this using the Send trait.

There are also additional users in later patches of this patchset. See
[1] and [2] for the discussion that led to the introduction of this patch.

---
 rust/kernel/sync/lock.rs | 13 +++++++++----
 rust/kernel/task.rs      | 10 ++++++----
 rust/kernel/types.rs     | 21 +++++++++++++++++++++
 3 files changed, 36 insertions(+), 8 deletions(-)
rust/kernel/sync/lock.rs +9 -4
index f6c34ca4d819..d6e9bab114b8 100644
@@ -6,8 +6,13 @@
 //! spinlocks, raw spinlocks) to be provided with minimal effort.
 
 use super::LockClassKey;
-use crate::{init::PinInit, pin_init, str::CStr, types::Opaque, types::ScopeGuard};
-use core::{cell::UnsafeCell, marker::PhantomData, marker::PhantomPinned};
+use crate::{
+    init::PinInit,
+    pin_init,
+    str::CStr,
+    types::{NotThreadSafe, Opaque, ScopeGuard},
+};
+use core::{cell::UnsafeCell, marker::PhantomPinned};
 use macros::pin_data;
 
 pub mod mutex;
@@ -139,7 +144,7 @@ pub fn lock(&self) -> Guard<'_, T, B> {
 pub struct Guard<'a, T: ?Sized, B: Backend> {
     pub(crate) lock: &'a Lock<T, B>,
     pub(crate) state: B::GuardState,
-    _not_send: PhantomData<*mut ()>,
+    _not_send: NotThreadSafe,
 }
 
 // SAFETY: `Guard` is sync when the data protected by the lock is also sync.
@@ -191,7 +196,7 @@ pub(crate) unsafe fn new(lock: &'a Lock<T, B>, state: B::GuardState) -> Self {
         Self {
             lock,
             state,
-            _not_send: PhantomData,
+            _not_send: NotThreadSafe,
         }
     }
 }
rust/kernel/task.rs +5 -3
index 55dff7e088bf..278c623de0c6 100644
@@ -4,10 +4,12 @@
 //!
 //! C header: [`include/linux/sched.h`](srctree/include/linux/sched.h).
 
-use crate::types::Opaque;
+use crate::{
+    bindings,
+    types::{NotThreadSafe, Opaque},
+};
 use core::{
     ffi::{c_int, c_long, c_uint},
-    marker::PhantomData,
     ops::Deref,
     ptr,
 };
@@ -106,7 +108,7 @@ impl Task {
     pub unsafe fn current() -> impl Deref<Target = Task> {
         struct TaskRef<'a> {
             task: &'a Task,
-            _not_send: PhantomData<*mut ()>,
+            _not_send: NotThreadSafe,
         }
 
Quoted 13 lines

rust/kernel/task.rs fn deref(&self) -> &Self::Target { · line 132

Quoted 9 lines
rust/kernel/task.rs +1 -1
         impl Deref for TaskRef<'_> {
@@ -125,7 +127,7 @@ fn deref(&self) -> &Self::Target {
             // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
             // (where it could potentially outlive the caller).
             task: unsafe { &*ptr.cast() },
-            _not_send: PhantomData,
+            _not_send: NotThreadSafe,
         }
     }

As per always for not being able to read rust; how does this extend to get_task_struct()? Once you've taken a reference on current, you should be free to pass it along to whomever.

Once you take a reference on current, it becomes thread-safe. This is because taking a reference creates a value of type ARef<Task> rather than TaskRef, and ARef<Task> is considered thread-safe.

Alice

maintainer
#4 lore raw

Re: [PATCH v8 1/8] rust: types: add `NotThreadSafe`

Quoted 7 lines · Alice Ryhl
Quoted 3 lines

As per always for not being able to read rust; how does this extend to get_task_struct()? Once you've taken a reference on current, you should be free to pass it along to whomever.

Once you take a reference on current, it becomes thread-safe. This is because taking a reference creates a value of type ARef<Task> rather than TaskRef, and ARef<Task> is considered thread-safe.

Ignoring comments, there isn't a single mention of ARef there. Where does it come from?

author maintainer
#5 lore raw

Re: [PATCH v8 1/8] rust: types: add `NotThreadSafe`

Quoted 7 lines · Peter Zijlstra
Quoted 4 lines · Alice Ryhl
Quoted 3 lines

As per always for not being able to read rust; how does this extend to get_task_struct()? Once you've taken a reference on current, you should be free to pass it along to whomever.

Quoted 6 lines
Quoted 3 lines

Once you take a reference on current, it becomes thread-safe. This is because taking a reference creates a value of type ARef<Task> rather than TaskRef, and ARef<Task> is considered thread-safe.

Ignoring comments, there isn't a single mention of ARef there. Where does it come from?

That's because the conversion to ARef<Task> is a two-step process. The TaskRef type just provides a conversion from &TaskRef to &Task via the impl Deref block. There is a conversion from &Task to ARef<Task> elsewhere, and this conversion is where the call to get_task_struct() happens.

Alice

maintainer Reviewed-by on v8 1/8
#6 lore raw

Re: [PATCH v8 1/8] rust: types: add `NotThreadSafe`

In reply to Alice Ryhl
Quoted 21 lines · On Thu, 25 Jul 2024 14:27:34 +0000 Alice Ryhl <[email protected]> wrote:

This introduces a new marker type for types that shouldn't be thread safe. By adding a field of this type to a struct, it becomes non-Send and non-Sync, which means that it cannot be accessed in any way from threads other than the one it was created on.

This is useful for APIs that require globals such as current to remain constant while the value exists.

We update two existing users in the Kernel to use this helper:

* Task::current() - moving the return type of this value to a different thread would not be safe as you can no longer be guaranteed that the current pointer remains valid.
* Lock guards. Mutexes and spinlocks should be unlocked on the same thread as where they were locked, so we enforce this using the Send trait.

There are also additional users in later patches of this patchset. See
[1] and [2] for the discussion that led to the introduction of this patch.

Quoted 8 lines
Quoted 5 lines
---
 rust/kernel/sync/lock.rs | 13 +++++++++----
 rust/kernel/task.rs      | 10 ++++++----
 rust/kernel/types.rs     | 21 +++++++++++++++++++++
 3 files changed, 36 insertions(+), 8 deletions(-)
author maintainer
#7 lore raw

PATCH v8 2/8 rust: task: add `Task::current_raw`

In reply to Alice Ryhl

Introduces a safe function for getting a raw pointer to the current task.

When writing bindings that need to access the current task, it is often more convenient to call a method that directly returns a raw pointer than to use the existing Task::current method. However, the only way to do that is bindings::get_current() which is unsafe since it calls into C. By introducing Task::current_raw(), it becomes possible to obtain a pointer to the current task without using unsafe.

---
 rust/kernel/task.rs | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
rust/kernel/task.rs +11 -4
index 278c623de0c6..367b4bbddd9f 100644
@@ -97,6 +97,15 @@ unsafe impl Sync for Task {}
 type Pid = bindings::pid_t;
 
 impl Task {
+    /// Returns a raw pointer to the current task.
+    ///
+    /// It is up to the user to use the pointer correctly.
+    #[inline]
+    pub fn current_raw() -> *mut bindings::task_struct {
+        // SAFETY: Getting the current pointer is always safe.
+        unsafe { bindings::get_current() }
+    }
+
     /// Returns a task reference for the currently executing task/thread.
     ///
     /// The recommended way to get the current task/thread is to use the
@@ -119,14 +128,12 @@ fn deref(&self) -> &Self::Target {
             }
         }
 
-        // SAFETY: Just an FFI call with no additional safety requirements.
-        let ptr = unsafe { bindings::get_current() };
-
+        let current = Task::current_raw();
         TaskRef {
             // SAFETY: If the current thread is still running, the current task is valid. Given
             // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
             // (where it could potentially outlive the caller).
-            task: unsafe { &*ptr.cast() },
+            task: unsafe { &*current.cast() },
             _not_send: NotThreadSafe,
         }
     }
Signature · 1 line
2.45.2.1089.g2a221341d9-goog
maintainer Reviewed-by on v8 2/8
#8 lore raw

Re: [PATCH v8 2/8] rust: task: add `Task::current_raw`

Quoted 10 lines · On Thu, 25 Jul 2024 14:27:35 +0000 Alice Ryhl <[email protected]> wrote:

Introduces a safe function for getting a raw pointer to the current task.

When writing bindings that need to access the current task, it is often more convenient to call a method that directly returns a raw pointer than to use the existing Task::current method. However, the only way to do that is bindings::get_current() which is unsafe since it calls into C. By introducing Task::current_raw(), it becomes possible to obtain a pointer to the current task without using unsafe.

Quoted 5 lines
Quoted 3 lines
---
 rust/kernel/task.rs | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
author maintainer
#9 lore raw

PATCH v8 3/8 rust: file: add Rust abstraction for `struct file`

In reply to Alice Ryhl

From: Wedson Almeida Filho <[email protected]>

This abstraction makes it possible to manipulate the open files for a process. The new File struct wraps the C struct file. When accessing it using the smart pointer ARef<File>, the pointer will own a reference count to the file. When accessing it as &File, then the reference does not own a refcount, but the borrow checker will ensure that the reference count does not hit zero while the &File is live.

Since this is intended to manipulate the open files of a process, we introduce an fget constructor that corresponds to the C fget method. In future patches, it will become possible to create a new fd in a process and bind it to a File. Rust Binder will use these to send fds from one process to another.

We also provide a method for accessing the file's flags. Rust Binder will use this to access the flags of the Binder fd to check whether the non-blocking flag is set, which affects what the Binder ioctl does.

This introduces a struct for the EBADF error type, rather than just using the Error type directly. This has two advantages:
* File::fget returns a Result<ARef<File>, BadFdError>, which the compiler will represent as a single pointer, with null being an error. This is possible because the compiler understands that BadFdError has only one possible value, and it also understands that the ARef<File> smart pointer is guaranteed non-null.
* Additionally, we promise to users of the method that the method can only fail with EBADF, which means that they can rely on this promise without having to inspect its implementation.
That said, there are also two disadvantages:
* Defining additional error types involves boilerplate.
* The question mark operator will only utilize the From trait once, which prevents you from using the question mark operator on BadFdError in methods that return some third error type that the kernel Error is convertible into. (However, it works fine in methods that return Error.)

---
 fs/file.c                       |   7 +
 rust/bindings/bindings_helper.h |   2 +
 rust/helpers.c                  |   7 +
 rust/kernel/fs.rs               |   8 +
 rust/kernel/fs/file.rs          | 375 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   1 +
 rust/kernel/types.rs            |   8 +
 7 files changed, 408 insertions(+)
fs/file.c +7 -0
index a3b72aa64f11..1d910f96ec2e 100644
@@ -1127,6 +1127,13 @@ EXPORT_SYMBOL(task_lookup_next_fdget_rcu);
  *
  * The fput_needed flag returned by fget_light should be passed to the
  * corresponding fput_light.
+ *
+ * (As an exception to rule 2, you can call filp_close between fget_light and
+ * fput_light provided that you capture a real refcount with get_file before
+ * the call to filp_close, and ensure that this real refcount is fput *after*
+ * the fput_light call.)
+ *
+ * See also the documentation in rust/kernel/file.rs.
  */
 static unsigned long __fget_light(unsigned int fd, fmode_t mask)
 {
rust/bindings/bindings_helper.h +2 -0
index f2bafb10f181..e2d22f151ec9 100644
@@ -9,6 +9,8 @@
 #include <kunit/test.h>
 #include <linux/errname.h>
 #include <linux/ethtool.h>
+#include <linux/file.h>
+#include <linux/fs.h>
 #include <linux/jiffies.h>
 #include <linux/mdio.h>
 #include <linux/phy.h>
rust/helpers.c +7 -0
index 305f0577fae9..5ba1f6de0251 100644
@@ -25,6 +25,7 @@
 #include <linux/build_bug.h>
 #include <linux/err.h>
 #include <linux/errname.h>
+#include <linux/fs.h>
 #include <linux/gfp.h>
 #include <linux/highmem.h>
 #include <linux/mutex.h>
@@ -199,6 +200,12 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags)
 }
 EXPORT_SYMBOL_GPL(rust_helper_krealloc);
 
+struct file *rust_helper_get_file(struct file *f)
+{
+	return get_file(f);
+}
+EXPORT_SYMBOL_GPL(rust_helper_get_file);
+
 /*
  * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can
  * use it in contexts where Rust expects a `usize` like slice (array) indices.
rust/kernel/fs.rs new file +8 -0
new file mode 100644
index 000000000000..0121b38c59e6
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Kernel file systems.
+//!
+//! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
+
+pub mod file;
+pub use self::file::{File, LocalFile};
rust/kernel/fs/file.rs new file +375 -0

375 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
index 5d310e79485f..c364893e13a2 100644
@@ -29,6 +29,7 @@
 pub mod alloc;
 mod build_assert;
 pub mod error;
+pub mod fs;
 pub mod init;
 pub mod ioctl;
 #[cfg(CONFIG_KUNIT)]
rust/kernel/types.rs +8 -0
index bb115d730ebb..cb3e178b2000 100644
@@ -366,6 +366,14 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
             _p: PhantomData,
         }
     }
+
+    /// Convert this [`ARef`] into a raw pointer.
+    ///
+    /// The caller retains ownership of the refcount that this `ARef` used to own.
+    pub fn into_raw(me: Self) -> NonNull<T> {
+        let me = core::mem::ManuallyDrop::new(me);
+        me.ptr
+    }
 }
 
 impl<T: AlwaysRefCounted> Clone for ARef<T> {
Signature · 1 line
2.45.2.1089.g2a221341d9-goog
Reviewed-by on v8 3/8
#10 lore raw

Re: [PATCH v8 3/8] rust: file: add Rust abstraction for `struct file`

rust/kernel/fs/file.rs line 193

Quoted 12 lines · Alice Ryhl
rust/kernel/fs/file.rs new file +12 -0
+/// Wraps the kernel's `struct file`. Not thread safe.
+///
+/// This type represents a file that is not known to be safe to transfer across thread boundaries.
+/// To obtain a thread-safe [`File`], use the [`assume_no_fdget_pos`] conversion.
+///
+/// See the documentation for [`File`] for more information.
+///
+/// # Invariants
+///
+/// * All instances of this type are refcounted using the `f_count` field.
+/// * If there is an active call to `fdget_pos` that did not take the `f_pos_lock` mutex, then it
+///   must be on the same thread as this `File`.

Do you mean LocalFile?

Quoted 5 lines
rust/kernel/fs/file.rs new file +5 -0
+///
+/// [`assume_no_fdget_pos`]: LocalFile::assume_no_fdget_pos
+pub struct LocalFile {
+    inner: Opaque<bindings::file>,
+}

[...]

rust/kernel/fs/file.rs line 286

Quoted 10 lines
rust/kernel/fs/file.rs new file +10 -0
+    /// Returns the flags associated with the file.
+    ///
+    /// The flags are a combination of the constants in [`flags`].
+    #[inline]
+    pub fn flags(&self) -> u32 {
+        // This `read_volatile` is intended to correspond to a READ_ONCE call.
+        //
+        // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.
+        //
+        // FIXME(read_once): Replace with `read_once` when available on the Rust side.

Do you know the status of this?

Quoted 43 lines
rust/kernel/fs/file.rs new file +43 -0
+        unsafe { core::ptr::addr_of!((*self.as_ptr()).f_flags).read_volatile() }
+    }
+}
+
+impl File {
+    /// Creates a reference to a [`File`] from a valid pointer.
+    ///
+    /// # Safety
+    ///
+    /// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is
+    ///   positive for the duration of 'a.
+    /// * The caller must ensure that if there are active `fdget_pos` calls on this file, then they
+    ///   took the `f_pos_lock` mutex.
+    #[inline]
+    pub unsafe fn from_raw_file<'a>(ptr: *const bindings::file) -> &'a File {
+        // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the
+        // duration of 'a. The cast is okay because `File` is `repr(transparent)`.
+        //
+        // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.
+        unsafe { &*ptr.cast() }
+    }
+}
+
+// Make LocalFile methods available on File.
+impl core::ops::Deref for File {
+    type Target = LocalFile;
+    #[inline]
+    fn deref(&self) -> &LocalFile {
+        // SAFETY: The caller provides a `&File`, and since it is a reference, it must point at a
+        // valid file for the desired duration.
+        //
+        // By the type invariants, there are no `fdget_pos` calls that did not take the
+        // `f_pos_lock` mutex.
+        unsafe { LocalFile::from_raw_file(self as *const File as *const bindings::file) }
+    }
+}
+
+// SAFETY: The type invariants guarantee that `LocalFile` is always ref-counted. This implementation
+// makes `ARef<File>` own a normal refcount.
+unsafe impl AlwaysRefCounted for LocalFile {
+    #[inline]
+    fn inc_ref(&self) {
+        // SAFETY: The existence of a shared reference means that the refcount is nonzero.

rust/kernel/fs/file.rs line 339

Quoted 10 lines
rust/kernel/fs/file.rs new file +10 -0
+        unsafe { bindings::get_file(self.as_ptr()) };
+    }
+
+    #[inline]
+    unsafe fn dec_ref(obj: ptr::NonNull<LocalFile>) {
+        // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
+        // may drop it. The cast is okay since `File` has the same representation as `struct file`.
+        unsafe { bindings::fput(obj.cast().as_ptr()) }
+    }
+}

Can you move these AlwaysRefCounted impls towards the struct definitions?

With those two comments fixed:

---
Cheers,
Benno

author maintainer
#11 lore raw

Re: [PATCH v8 3/8] rust: file: add Rust abstraction for `struct file`

Quoted 16 lines · Benno Lossin

rust/kernel/fs/file.rs line 193

Quoted 12 lines · Alice Ryhl
rust/kernel/fs/file.rs new file +12 -0
+/// Wraps the kernel's `struct file`. Not thread safe.
+///
+/// This type represents a file that is not known to be safe to transfer across thread boundaries.
+/// To obtain a thread-safe [`File`], use the [`assume_no_fdget_pos`] conversion.
+///
+/// See the documentation for [`File`] for more information.
+///
+/// # Invariants
+///
+/// * All instances of this type are refcounted using the `f_count` field.
+/// * If there is an active call to `fdget_pos` that did not take the `f_pos_lock` mutex, then it
+///   must be on the same thread as this `File`.

Do you mean LocalFile?

I guess. Perhaps I should just say "file" as a general concept?

Quoted 19 lines
Quoted 5 lines
rust/kernel/fs/file.rs new file +5 -0
+///
+/// [`assume_no_fdget_pos`]: LocalFile::assume_no_fdget_pos
+pub struct LocalFile {
+    inner: Opaque<bindings::file>,
+}

[...]

rust/kernel/fs/file.rs line 286

Quoted 10 lines
rust/kernel/fs/file.rs new file +10 -0
+    /// Returns the flags associated with the file.
+    ///
+    /// The flags are a combination of the constants in [`flags`].
+    #[inline]
+    pub fn flags(&self) -> u32 {
+        // This `read_volatile` is intended to correspond to a READ_ONCE call.
+        //
+        // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.
+        //
+        // FIXME(read_once): Replace with `read_once` when available on the Rust side.
Quoted 1 line

Do you know the status of this?

It's still unavailable.

Quoted 57 lines
Quoted 43 lines
rust/kernel/fs/file.rs new file +43 -0
+        unsafe { core::ptr::addr_of!((*self.as_ptr()).f_flags).read_volatile() }
+    }
+}
+
+impl File {
+    /// Creates a reference to a [`File`] from a valid pointer.
+    ///
+    /// # Safety
+    ///
+    /// * The caller must ensure that `ptr` points at a valid file and that the file's refcount is
+    ///   positive for the duration of 'a.
+    /// * The caller must ensure that if there are active `fdget_pos` calls on this file, then they
+    ///   took the `f_pos_lock` mutex.
+    #[inline]
+    pub unsafe fn from_raw_file<'a>(ptr: *const bindings::file) -> &'a File {
+        // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the
+        // duration of 'a. The cast is okay because `File` is `repr(transparent)`.
+        //
+        // INVARIANT: The caller guarantees that there are no problematic `fdget_pos` calls.
+        unsafe { &*ptr.cast() }
+    }
+}
+
+// Make LocalFile methods available on File.
+impl core::ops::Deref for File {
+    type Target = LocalFile;
+    #[inline]
+    fn deref(&self) -> &LocalFile {
+        // SAFETY: The caller provides a `&File`, and since it is a reference, it must point at a
+        // valid file for the desired duration.
+        //
+        // By the type invariants, there are no `fdget_pos` calls that did not take the
+        // `f_pos_lock` mutex.
+        unsafe { LocalFile::from_raw_file(self as *const File as *const bindings::file) }
+    }
+}
+
+// SAFETY: The type invariants guarantee that `LocalFile` is always ref-counted. This implementation
+// makes `ARef<File>` own a normal refcount.
+unsafe impl AlwaysRefCounted for LocalFile {
+    #[inline]
+    fn inc_ref(&self) {
+        // SAFETY: The existence of a shared reference means that the refcount is nonzero.

rust/kernel/fs/file.rs line 339

Quoted 10 lines
rust/kernel/fs/file.rs new file +10 -0
+        unsafe { bindings::get_file(self.as_ptr()) };
+    }
+
+    #[inline]
+    unsafe fn dec_ref(obj: ptr::NonNull<LocalFile>) {
+        // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
+        // may drop it. The cast is okay since `File` has the same representation as `struct file`.
+        unsafe { bindings::fput(obj.cast().as_ptr()) }
+    }
+}

Can you move these AlwaysRefCounted impls towards the struct definitions?

Quoted 3 lines

With those two comments fixed:

Thanks!

Alice

#12 lore raw

Re: [PATCH v8 3/8] rust: file: add Rust abstraction for `struct file`

On Tue, Aug 06, 2024 at 10:48:11AM +0200, Alice Ryhl wrote:
[...]

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
rust/kernel/fs/file.rs new file +10 -0
+    /// Returns the flags associated with the file.
+    ///
+    /// The flags are a combination of the constants in [`flags`].
+    #[inline]
+    pub fn flags(&self) -> u32 {
+        // This `read_volatile` is intended to correspond to a READ_ONCE call.
+        //
+        // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.
+        //
+        // FIXME(read_once): Replace with `read_once` when available on the Rust side.
Quoted 4 lines
Quoted 1 line

Do you know the status of this?

It's still unavailable.

I think with our own Atomic API, we can just use atomic_read() here:
yes, I know that to make this is not a UB, we need the C side to also do atomic write on this f_flags, however, my reading of C code seems to suggest that FS relies on writes to this field is atomic, therefore unless someone is willing to convert all writes to f_flags in C into a WRITE_ONCE(), nothing more we can do on Rust side. So using atomic_read() is the correct thing to begin with.

Regards,
Boqun

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
rust/kernel/fs/file.rs new file +3 -0
+        unsafe { core::ptr::addr_of!((*self.as_ptr()).f_flags).read_volatile() }
+    }
+}

[...]

author maintainer
#13 lore raw

Re: [PATCH v8 3/8] rust: file: add Rust abstraction for `struct file`

Quoted 19 lines · Boqun Feng

On Tue, Aug 06, 2024 at 10:48:11AM +0200, Alice Ryhl wrote:
[...]

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
rust/kernel/fs/file.rs new file +10 -0
+    /// Returns the flags associated with the file.
+    ///
+    /// The flags are a combination of the constants in [`flags`].
+    #[inline]
+    pub fn flags(&self) -> u32 {
+        // This `read_volatile` is intended to correspond to a READ_ONCE call.
+        //
+        // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.
+        //
+        // FIXME(read_once): Replace with `read_once` when available on the Rust side.
Quoted 4 lines
Quoted 1 line

Do you know the status of this?

It's still unavailable.

Quoted 7 lines

I think with our own Atomic API, we can just use atomic_read() here:
yes, I know that to make this is not a UB, we need the C side to also do atomic write on this f_flags, however, my reading of C code seems to suggest that FS relies on writes to this field is atomic, therefore unless someone is willing to convert all writes to f_flags in C into a WRITE_ONCE(), nothing more we can do on Rust side. So using atomic_read() is the correct thing to begin with.

Huh? The C side uses atomic reads for this?

Alice

#14 lore raw

Re: [PATCH v8 3/8] rust: file: add Rust abstraction for `struct file`

Quoted 28 lines · Alice Ryhl
Quoted 19 lines · Boqun Feng

On Tue, Aug 06, 2024 at 10:48:11AM +0200, Alice Ryhl wrote:
[...]

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
rust/kernel/fs/file.rs new file +10 -0
+    /// Returns the flags associated with the file.
+    ///
+    /// The flags are a combination of the constants in [`flags`].
+    #[inline]
+    pub fn flags(&self) -> u32 {
+        // This `read_volatile` is intended to correspond to a READ_ONCE call.
+        //
+        // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.
+        //
+        // FIXME(read_once): Replace with `read_once` when available on the Rust side.
Quoted 4 lines
Quoted 1 line

Do you know the status of this?

It's still unavailable.

Quoted 7 lines

I think with our own Atomic API, we can just use atomic_read() here:
yes, I know that to make this is not a UB, we need the C side to also do atomic write on this f_flags, however, my reading of C code seems to suggest that FS relies on writes to this field is atomic, therefore unless someone is willing to convert all writes to f_flags in C into a WRITE_ONCE(), nothing more we can do on Rust side. So using atomic_read() is the correct thing to begin with.

Quoted 2 lines

Huh? The C side uses atomic reads for this?

Well, READ_ONCE(->f_flags) is atomic, so I thought you want to use atomic here. However, after a quick look of ->f_flags accesses, I find out they should be protected by ->f_lock (a few cases rely on data race accesses, see p4_fd_open()), so I think what you should really do here is the similar: make sure Rust code only accesses ->f_flags if ->f_lock is held. Unless that's not the case for binder?

Regards,
Boqun

Quoted 1 line

Alice

#15 lore raw

Re: [PATCH v8 3/8] rust: file: add Rust abstraction for `struct file`

Quoted 32 lines · Boqun Feng
Quoted 28 lines · Alice Ryhl
Quoted 19 lines · Boqun Feng

On Tue, Aug 06, 2024 at 10:48:11AM +0200, Alice Ryhl wrote:
[...]

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
rust/kernel/fs/file.rs new file +10 -0
+    /// Returns the flags associated with the file.
+    ///
+    /// The flags are a combination of the constants in [`flags`].
+    #[inline]
+    pub fn flags(&self) -> u32 {
+        // This `read_volatile` is intended to correspond to a READ_ONCE call.
+        //
+        // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.
+        //
+        // FIXME(read_once): Replace with `read_once` when available on the Rust side.
Quoted 4 lines
Quoted 1 line

Do you know the status of this?

It's still unavailable.

Quoted 7 lines

I think with our own Atomic API, we can just use atomic_read() here:
yes, I know that to make this is not a UB, we need the C side to also do atomic write on this f_flags, however, my reading of C code seems to suggest that FS relies on writes to this field is atomic, therefore unless someone is willing to convert all writes to f_flags in C into a WRITE_ONCE(), nothing more we can do on Rust side. So using atomic_read() is the correct thing to begin with.

Quoted 2 lines

Huh? The C side uses atomic reads for this?

Quoted 6 lines

Well, READ_ONCE(->f_flags) is atomic, so I thought you want to use atomic here. However, after a quick look of ->f_flags accesses, I find out they should be protected by ->f_lock (a few cases rely on data race accesses, see p4_fd_open()), so I think what you should really do here is the similar: make sure Rust code only accesses ->f_flags if ->f_lock is held. Unless that's not the case for binder?

Binder just has an if (filp->f_flags & O_NONBLOCK) block somewhere in the ioctl, where filp is the struct file * passed to the ioctl. Binder doesn't take the lock.

Alice

#16 lore raw

Re: [PATCH v8 3/8] rust: file: add Rust abstraction for `struct file`

Quoted 41 lines · Alice Ryhl
Quoted 32 lines · Boqun Feng
Quoted 28 lines · Alice Ryhl
Quoted 19 lines · Boqun Feng

On Tue, Aug 06, 2024 at 10:48:11AM +0200, Alice Ryhl wrote:
[...]

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
(quoted diff) +10 -0
+    /// Returns the flags associated with the file.
+    ///
+    /// The flags are a combination of the constants in [`flags`].
+    #[inline]
+    pub fn flags(&self) -> u32 {
+        // This `read_volatile` is intended to correspond to a READ_ONCE call.
+        //
+        // SAFETY: The file is valid because the shared reference guarantees a nonzero refcount.
+        //
+        // FIXME(read_once): Replace with `read_once` when available on the Rust side.
Quoted 4 lines
Quoted 1 line

Do you know the status of this?

It's still unavailable.

Quoted 7 lines

I think with our own Atomic API, we can just use atomic_read() here:
yes, I know that to make this is not a UB, we need the C side to also do atomic write on this f_flags, however, my reading of C code seems to suggest that FS relies on writes to this field is atomic, therefore unless someone is willing to convert all writes to f_flags in C into a WRITE_ONCE(), nothing more we can do on Rust side. So using atomic_read() is the correct thing to begin with.

Quoted 2 lines

Huh? The C side uses atomic reads for this?

Quoted 6 lines

Well, READ_ONCE(->f_flags) is atomic, so I thought you want to use atomic here. However, after a quick look of ->f_flags accesses, I find out they should be protected by ->f_lock (a few cases rely on data race accesses, see p4_fd_open()), so I think what you should really do here is the similar: make sure Rust code only accesses ->f_flags if ->f_lock is held. Unless that's not the case for binder?

Quoted 4 lines

Binder just has an if (filp->f_flags & O_NONBLOCK) block somewhere in the ioctl, where filp is the struct file * passed to the ioctl. Binder doesn't take the lock.

Yep, that's my point, I think binder C driver relies on the behaviors of data race today (or probably all ->f_flagss accessed by binder don't have any concurrent write to them). Either way, what you do here is better than C code if there was a data race. I was simply suggesting instead of read_once, we could just do a atomic_read on ->f_flags once we support *unsafe` usage of doing atomic accesses on normal data fields (of course, such a usage will be limited).

In other words, nothing needs to be changed here right now.

Regards,
Boqun

Quoted 1 line

Alice

author maintainer
#17 lore raw

PATCH v8 4/8 rust: cred: add Rust abstraction for `struct cred`

In reply to Alice Ryhl

From: Wedson Almeida Filho <[email protected]>

Add a wrapper around struct cred called Credential, and provide functionality to get the Credential associated with a File.

Rust Binder must check the credentials of processes when they attempt to perform various operations, and these checks usually take a &Credential as parameter. The security_binder_set_context_mgr function would be one example. This patch is necessary to access these security_* methods from Rust.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/helpers.c                  | 13 +++++++
 rust/kernel/cred.rs             | 76 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/fs/file.rs          | 13 +++++++
 rust/kernel/lib.rs              |  1 +
 5 files changed, 104 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index e2d22f151ec9..22e62b3b34b0 100644
@@ -7,6 +7,7 @@
  */
 
 #include <kunit/test.h>
+#include <linux/cred.h>
 #include <linux/errname.h>
 #include <linux/ethtool.h>
 #include <linux/file.h>
rust/helpers.c +13 -0
index 5ba1f6de0251..4831abb5a438 100644
@@ -23,6 +23,7 @@
 #include <kunit/test-bug.h>
 #include <linux/bug.h>
 #include <linux/build_bug.h>
+#include <linux/cred.h>
 #include <linux/err.h>
 #include <linux/errname.h>
 #include <linux/fs.h>
@@ -206,6 +207,18 @@ struct file *rust_helper_get_file(struct file *f)
 }
 EXPORT_SYMBOL_GPL(rust_helper_get_file);
 
+const struct cred *rust_helper_get_cred(const struct cred *cred)
+{
+	return get_cred(cred);
+}
+EXPORT_SYMBOL_GPL(rust_helper_get_cred);
+
+void rust_helper_put_cred(const struct cred *cred)
+{
+	put_cred(cred);
+}
+EXPORT_SYMBOL_GPL(rust_helper_put_cred);
+
 /*
  * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can
  * use it in contexts where Rust expects a `usize` like slice (array) indices.
rust/kernel/cred.rs new file +76 -0

76 lines not on this page · raw message

rust/kernel/fs/file.rs +13 -0
index f1a52814b2da..8bed7bebcc43 100644
@@ -9,6 +9,7 @@
 
 use crate::{
     bindings,
+    cred::Credential,
     error::{code::*, Error, Result},
     types::{ARef, AlwaysRefCounted, Opaque},
 };
@@ -274,6 +275,18 @@ pub fn as_ptr(&self) -> *mut bindings::file {
         self.inner.get()
     }
 
+    /// Returns the credentials of the task that originally opened the file.
+    pub fn cred(&self) -> &Credential {
+        // SAFETY: It's okay to read the `f_cred` field without synchronization because `f_cred` is
+        // never changed after initialization of the file.
+        let ptr = unsafe { (*self.as_ptr()).f_cred };
+
+        // SAFETY: The signature of this function ensures that the caller will only access the
+        // returned credential while the file is still valid, and the C side ensures that the
+        // credential stays valid at least as long as the file.
+        unsafe { Credential::from_ptr(ptr) }
+    }
+
     /// Returns the flags associated with the file.
     ///
     /// The flags are a combination of the constants in [`flags`].
rust/kernel/lib.rs +1 -0
index c364893e13a2..8fb57ec20867 100644
@@ -28,6 +28,7 @@
 
 pub mod alloc;
 mod build_assert;
+pub mod cred;
 pub mod error;
 pub mod fs;
 pub mod init;
Signature · 1 line
2.45.2.1089.g2a221341d9-goog
maintainer Reviewed-by on v8 4/8
#18 lore raw

Re: [PATCH v8 4/8] rust: cred: add Rust abstraction for `struct cred`

Quoted 11 lines · On Thu, 25 Jul 2024 14:27:37 +0000 Alice Ryhl <[email protected]> wrote:

From: Wedson Almeida Filho <[email protected]>

Add a wrapper around struct cred called Credential, and provide functionality to get the Credential associated with a File.

Rust Binder must check the credentials of processes when they attempt to perform various operations, and these checks usually take a &Credential as parameter. The security_binder_set_context_mgr function would be one example. This patch is necessary to access these security_* methods from Rust.

Quoted 6 lines
Quoted 7 lines
---
 rust/bindings/bindings_helper.h |  1 +
 rust/helpers.c                  | 13 +++++++
 rust/kernel/cred.rs             | 76 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/fs/file.rs          | 13 +++++++
 rust/kernel/lib.rs              |  1 +
 5 files changed, 104 insertions(+)
author maintainer
#19 lore raw

PATCH v8 5/8 rust: security: add abstraction for secctx

In reply to Alice Ryhl

Add an abstraction for viewing the string representation of a security context.

This is needed by Rust Binder because it has a feature where a process can view the string representation of the security context for incoming transactions. The process can use that to authenticate incoming transactions, and since the feature is provided by the kernel, the process can trust that the security context is legitimate.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/helpers.c                  | 21 ++++++++++++
 rust/kernel/cred.rs             |  8 +++++
 rust/kernel/lib.rs              |  1 +
 rust/kernel/security.rs         | 74 +++++++++++++++++++++++++++++++++++++++++
 5 files changed, 105 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index 22e62b3b34b0..afa24d54c1a0 100644
@@ -17,6 +17,7 @@
 #include <linux/phy.h>
 #include <linux/refcount.h>
 #include <linux/sched.h>
+#include <linux/security.h>
 #include <linux/slab.h>
 #include <linux/wait.h>
 #include <linux/workqueue.h>
rust/helpers.c +21 -0
index 4831abb5a438..b61f5a8ce1da 100644
@@ -32,6 +32,7 @@
 #include <linux/mutex.h>
 #include <linux/refcount.h>
 #include <linux/sched/signal.h>
+#include <linux/security.h>
 #include <linux/slab.h>
 #include <linux/spinlock.h>
 #include <linux/wait.h>
@@ -219,6 +220,26 @@ void rust_helper_put_cred(const struct cred *cred)
 }
 EXPORT_SYMBOL_GPL(rust_helper_put_cred);
 
+#ifndef CONFIG_SECURITY
+void rust_helper_security_cred_getsecid(const struct cred *c, u32 *secid)
+{
+	security_cred_getsecid(c, secid);
+}
+EXPORT_SYMBOL_GPL(rust_helper_security_cred_getsecid);
+
+int rust_helper_security_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
+{
+	return security_secid_to_secctx(secid, secdata, seclen);
+}
+EXPORT_SYMBOL_GPL(rust_helper_security_secid_to_secctx);
+
+void rust_helper_security_release_secctx(char *secdata, u32 seclen)
+{
+	security_release_secctx(secdata, seclen);
+}
+EXPORT_SYMBOL_GPL(rust_helper_security_release_secctx);
+#endif
+
 /*
  * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can
  * use it in contexts where Rust expects a `usize` like slice (array) indices.
rust/kernel/cred.rs +8 -0
index acee04768927..92659649e932 100644
@@ -52,6 +52,14 @@ pub unsafe fn from_ptr<'a>(ptr: *const bindings::cred) -> &'a Credential {
         unsafe { &*ptr.cast() }
     }
 
+    /// Get the id for this security context.
+    pub fn get_secid(&self) -> u32 {
+        let mut secid = 0;
+        // SAFETY: The invariants of this type ensures that the pointer is valid.
+        unsafe { bindings::security_cred_getsecid(self.0.get(), &mut secid) };
+        secid
+    }
+
     /// Returns the effective UID of the given credential.
     pub fn euid(&self) -> bindings::kuid_t {
         // SAFETY: By the type invariant, we know that `self.0` is valid. Furthermore, the `euid`
rust/kernel/lib.rs +1 -0
index 8fb57ec20867..a8de8293376e 100644
@@ -40,6 +40,7 @@
 pub mod page;
 pub mod prelude;
 pub mod print;
+pub mod security;
 mod static_assert;
 #[doc(hidden)]
 pub mod std_vendor;
rust/kernel/security.rs new file +74 -0

74 lines not on this page · raw message

Signature · 1 line
2.45.2.1089.g2a221341d9-goog
maintainer Reviewed-by on v8 5/8
#20 lore raw

Re: [PATCH v8 5/8] rust: security: add abstraction for secctx

Quoted 9 lines · On Thu, 25 Jul 2024 14:27:38 +0000 Alice Ryhl <[email protected]> wrote:

Add an abstraction for viewing the string representation of a security context.

This is needed by Rust Binder because it has a feature where a process can view the string representation of the security context for incoming transactions. The process can use that to authenticate incoming transactions, and since the feature is provided by the kernel, the process can trust that the security context is legitimate.

Quoted 4 lines
Quoted 7 lines
---
 rust/bindings/bindings_helper.h |  1 +
 rust/helpers.c                  | 21 ++++++++++++
 rust/kernel/cred.rs             |  8 +++++
 rust/kernel/lib.rs              |  1 +
 rust/kernel/security.rs         | 74 +++++++++++++++++++++++++++++++++++++++++
 5 files changed, 105 insertions(+)
author maintainer
#21 lore raw

PATCH v8 6/8 rust: file: add `FileDescriptorReservation`

In reply to Alice Ryhl

From: Wedson Almeida Filho <[email protected]>

Allow for the creation of a file descriptor in two steps: first, we reserve a slot for it, then we commit or drop the reservation. The first step may fail (e.g., the current process ran out of available slots), but commit and drop never fail (and are mutually exclusive).

This is needed by Rust Binder when fds are sent from one process to another. It has to be a two-step process to properly handle the case where multiple fds are sent: The operation must fail or succeed atomically, which we achieve by first reserving the fds we need, and only installing the files once we have reserved enough fds to send the files.

Fd reservations assume that the value of current does not change between the call to get_unused_fd_flags and the call to fd_install (or put_unused_fd). By not implementing the Send trait, this abstraction ensures that the FileDescriptorReservation cannot be moved into a different process.

---
 rust/kernel/fs/file.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 74 insertions(+), 1 deletion(-)
rust/kernel/fs/file.rs +74 -1
index 8bed7bebcc43..af98513bb2ee 100644
@@ -11,7 +11,7 @@
     bindings,
     cred::Credential,
     error::{code::*, Error, Result},
-    types::{ARef, AlwaysRefCounted, Opaque},
+    types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque},
 };
 use core::ptr;
 
@@ -368,6 +368,79 @@ unsafe fn dec_ref(obj: ptr::NonNull<File>) {
     }
 }
 
+/// A file descriptor reservation.
+///
+/// This allows the creation of a file descriptor in two steps: first, we reserve a slot for it,
+/// then we commit or drop the reservation. The first step may fail (e.g., the current process ran
+/// out of available slots), but commit and drop never fail (and are mutually exclusive).
+///
+/// Dropping the reservation happens in the destructor of this type.
+///
+/// # Invariants
+///
+/// The fd stored in this struct must correspond to a reserved file descriptor of the current task.
+pub struct FileDescriptorReservation {
+    fd: u32,
+    /// Prevent values of this type from being moved to a different task.
+    ///
+    /// The `fd_install` and `put_unused_fd` functions assume that the value of `current` is
+    /// unchanged since the call to `get_unused_fd_flags`. By adding this marker to this type, we
+    /// prevent it from being moved across task boundaries, which ensures that `current` does not
+    /// change while this value exists.
+    _not_send: NotThreadSafe,
+}
+
+impl FileDescriptorReservation {
+    /// Creates a new file descriptor reservation.
+    pub fn get_unused_fd_flags(flags: u32) -> Result<Self> {
+        // SAFETY: FFI call, there are no safety requirements on `flags`.
+        let fd: i32 = unsafe { bindings::get_unused_fd_flags(flags) };
+        if fd < 0 {
+            return Err(Error::from_errno(fd));
+        }
+        Ok(Self {
+            fd: fd as u32,
+            _not_send: NotThreadSafe,
+        })
+    }
+
+    /// Returns the file descriptor number that was reserved.
+    pub fn reserved_fd(&self) -> u32 {
+        self.fd
+    }
+
+    /// Commits the reservation.
+    ///
+    /// The previously reserved file descriptor is bound to `file`. This method consumes the
+    /// [`FileDescriptorReservation`], so it will not be usable after this call.
+    pub fn fd_install(self, file: ARef<File>) {
+        // SAFETY: `self.fd` was previously returned by `get_unused_fd_flags`. We have not yet used
+        // the fd, so it is still valid, and `current` still refers to the same task, as this type
+        // cannot be moved across task boundaries.
+        //
+        // Furthermore, the file pointer is guaranteed to own a refcount by its type invariants,
+        // and we take ownership of that refcount by not running the destructor below.
+        // Additionally, the file is known to not have any non-shared `fdget_pos` calls, so even if
+        // this process starts using the file position, this will not result in a data race on the
+        // file position.
+        unsafe { bindings::fd_install(self.fd, file.as_ptr()) };
+
+        // `fd_install` consumes both the file descriptor and the file reference, so we cannot run
+        // the destructors.
+        core::mem::forget(self);
+        core::mem::forget(file);
+    }
+}
+
+impl Drop for FileDescriptorReservation {
+    fn drop(&mut self) {
+        // SAFETY: By the type invariants of this type, `self.fd` was previously returned by
+        // `get_unused_fd_flags`. We have not yet used the fd, so it is still valid, and `current`
+        // still refers to the same task, as this type cannot be moved across task boundaries.
+        unsafe { bindings::put_unused_fd(self.fd) };
+    }
+}
+
 /// Represents the `EBADF` error code.
 ///
 /// Used for methods that can only fail with `EBADF`.
Signature · 1 line
2.45.2.1089.g2a221341d9-goog
maintainer Reviewed-by on v8 6/8
#22 lore raw

Re: [PATCH v8 6/8] rust: file: add `FileDescriptorReservation`

Quoted 20 lines · On Thu, 25 Jul 2024 14:27:39 +0000 Alice Ryhl <[email protected]> wrote:

From: Wedson Almeida Filho <[email protected]>

Allow for the creation of a file descriptor in two steps: first, we reserve a slot for it, then we commit or drop the reservation. The first step may fail (e.g., the current process ran out of available slots), but commit and drop never fail (and are mutually exclusive).

This is needed by Rust Binder when fds are sent from one process to another. It has to be a two-step process to properly handle the case where multiple fds are sent: The operation must fail or succeed atomically, which we achieve by first reserving the fds we need, and only installing the files once we have reserved enough fds to send the files.

Fd reservations assume that the value of current does not change between the call to get_unused_fd_flags and the call to fd_install (or put_unused_fd). By not implementing the Send trait, this abstraction ensures that the FileDescriptorReservation cannot be moved into a different process.

Quoted 6 lines
Quoted 3 lines
---
 rust/kernel/fs/file.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 74 insertions(+), 1 deletion(-)
author maintainer
#23 lore raw

PATCH v8 7/8 rust: file: add `Kuid` wrapper

In reply to Alice Ryhl

Adds a wrapper around kuid_t called Kuid. This allows us to define various operations on kuids such as equality and current_euid. It also lets us provide conversions from kuid into userspace values.

Rust Binder needs these operations because it needs to compare kuids for equality, and it needs to tell userspace about the pid and uid of incoming transactions.

To read kuids from a struct task_struct, you must currently use various #defines that perform the appropriate field access under an RCU read lock. Currently, we do not have a Rust wrapper for rcu_read_lock, which means that for this patch, there are two ways forward:

1. Inline the methods into Rust code, and use __rcu_read_lock directly rather than the rcu_read_lock wrapper. This gives up lockdep for these usages of RCU.

2. Wrap the various #defines in helpers and call the helpers from Rust.

This patch uses the second option. One possible disadvantage of the second option is the possible introduction of speculation gadgets, but as discussed in [1], the risk appears to be acceptable.

Of course, once a wrapper for rcu_read_lock is available, it is preferable to use that over either of the two above approaches.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/helpers.c                  | 45 ++++++++++++++++++++++++++++
 rust/kernel/cred.rs             |  5 ++--
 rust/kernel/task.rs             | 66 +++++++++++++++++++++++++++++++++++++++++
 4 files changed, 115 insertions(+), 2 deletions(-)
rust/bindings/bindings_helper.h +1 -0
index afa24d54c1a0..d7f7ae109e6f 100644
@@ -15,6 +15,7 @@
 #include <linux/jiffies.h>
 #include <linux/mdio.h>
 #include <linux/phy.h>
+#include <linux/pid_namespace.h>
 #include <linux/refcount.h>
 #include <linux/sched.h>
 #include <linux/security.h>
rust/helpers.c +45 -0

51 lines not on this page · raw message

rust/kernel/cred.rs +3 -2
index 92659649e932..81d67789b16f 100644
@@ -10,6 +10,7 @@
 
 use crate::{
     bindings,
+    task::Kuid,
     types::{AlwaysRefCounted, Opaque},
 };
 
@@ -61,11 +62,11 @@ pub fn get_secid(&self) -> u32 {
     }
 
     /// Returns the effective UID of the given credential.
-    pub fn euid(&self) -> bindings::kuid_t {
+    pub fn euid(&self) -> Kuid {
         // SAFETY: By the type invariant, we know that `self.0` is valid. Furthermore, the `euid`
         // field of a credential is never changed after initialization, so there is no potential
         // for data races.
-        unsafe { (*self.0.get()).euid }
+        Kuid::from_raw(unsafe { (*self.0.get()).euid })
     }
 }
 
rust/kernel/task.rs +66 -0

93 lines not on this page · raw message

Signature · 1 line
2.45.2.1089.g2a221341d9-goog
author maintainer
#24 lore raw

PATCH v8 8/8 rust: file: add abstraction for `poll_table`

In reply to Alice Ryhl

The existing CondVar abstraction is a wrapper around wait_queue_head, but it does not support all use-cases of the C wait_queue_head type. To be specific, a CondVar cannot be registered with a struct poll_table. This limitation has the advantage that you do not need to call synchronize_rcu when destroying a CondVar.

However, we need the ability to register a poll_table with a wait_queue_head in Rust Binder. To enable this, introduce a type called PollCondVar, which is like CondVar except that you can register a poll_table. We also introduce PollTable, which is a safe wrapper around poll_table that is intended to be used with PollCondVar.

The destructor of PollCondVar unconditionally calls synchronize_rcu to ensure that the removal of epoll waiters has fully completed before the wait_queue_head is destroyed.

That said, synchronize_rcu is rather expensive and is not needed in all cases: If we have never registered a poll_table with the wait_queue_head, then we don't need to call synchronize_rcu. (And this is a common case in Binder - not all processes use Binder with epoll.) The current implementation does not account for this, but if we find that it is necessary to improve this, a future patch could store a boolean next to the wait_queue_head to keep track of whether a poll_table has ever been registered.

---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/sync.rs             |   1 +
 rust/kernel/sync/poll.rs        | 121 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 123 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index d7f7ae109e6f..809112fd73d3 100644
@@ -16,6 +16,7 @@
 #include <linux/mdio.h>
 #include <linux/phy.h>
 #include <linux/pid_namespace.h>
+#include <linux/poll.h>
 #include <linux/refcount.h>
 #include <linux/sched.h>
 #include <linux/security.h>
rust/kernel/sync.rs +1 -0
index 0ab20975a3b5..bae4a5179c72 100644
@@ -11,6 +11,7 @@
 mod condvar;
 pub mod lock;
 mod locked_by;
+pub mod poll;
 
 pub use arc::{Arc, ArcBorrow, UniqueArc};
 pub use condvar::{new_condvar, CondVar, CondVarTimeoutResult};
rust/kernel/sync/poll.rs new file +121 -0

121 lines not on this page · raw message

Signature · 1 line
2.45.2.1089.g2a221341d9-goog