Avoid synchronize_rcu() for every thread drop in Rust Binder
Subsystems (4)
Alice Ryhl
maintainerv6 cover Avoid synchronize_rcu() for every thread drop in Rust Binder
Right now Rust Binder calls synchronize_rcu() more often than is necessary. Most processes do not use epoll at all, so they don't require rcu here. Back in Kangrejos I came up with a way to avoid this. Idea is to move the value that needs rcu to a separate allocation that's easy to kfree_rcu(). We pay the allocation only when the proc uses epoll using an "upgrade" strategy - most processes don't.
Based on top of:
https://lore.kernel.org/rust-for-linux/[email protected]/
---
Changes in v6:
- Rebase on v7.2-rc2 and node_ref spinlock change.
- Fix conflict with commit 77bfebf11077 ("rust_binder: fix BINDER_GET_EXTENDED_ERROR")
- Link to v5: https://lore.kernel.org/r/[email protected]
Changes in v5:
- Rebase on top of series converting node_refs to spinlock.
- Reword comment claiming node_refs is a mutex.
- Link to v4: https://lore.kernel.org/r/[email protected]
Changes in v4:
- Use SetOnce for PollCondVar variable instead of storing inside
spinlock. This avoids calling poll_wait() under the spinlock.
- Link to v3: https://lore.kernel.org/r/[email protected]
Changes in v3:
- This series was almost entirely rewritten to use a different implementation strategy. By moving the PollCondVar to the process we
can avoid the upgrade logic entirely.
- Link to v2: https://lore.kernel.org/r/[email protected]
Changes in v2:
- Change how Rust Binder handles the lock class key.
- Rebase.
- Link to v1: https://lore.kernel.org/r/[email protected]
---
Alice Ryhl (2):
rust: poll: use kfree_rcu() for PollCondVar
rust_binder: move (e)poll wait queue to Process
drivers/android/binder/node.rs | 4 +- drivers/android/binder/process.rs | 67 ++++++++++++++++++++++-------- drivers/android/binder/thread.rs | 78 +++++++++++++++++------------------ drivers/android/binder/transaction.rs | 6 ++- rust/kernel/sync/poll.rs | 73 +++++++++++++++++++++++++++++++- 5 files changed, 167 insertions(+), 61 deletions(-)
---
base-commit: 0e77a935cf137e791c672d21bb80441043017ff2
change-id: 20260117-upgrade-poll-37ee2a7a79dd
Best regards,
Signature · 1 line
Alice Ryhl <[email protected]>
Alice Ryhl
maintainerPATCH v6 1/2 rust: poll: use kfree_rcu() for PollCondVar
Rust Binder currently uses PollCondVar, but it calls synchronize_rcu() in the destructor, which we would like to avoid. Add a variation of PollCondVar that kfree_rcu() instead.
One could avoid the rcu field and allocate the rcu_head on drop using a fallback to synchronize_rcu() on ENOMEM. However, I'd prefer to avoid the potential for synchronize_rcu(), and Binder will only use this for a small fraction of processes, so even if it changes which kmalloc bucket it falls into, the extra memory is not a problem.
--- rust/kernel/sync/poll.rs | 73 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-)
rust/kernel/sync/poll.rs +72 -1
@@ -5,12 +5,18 @@//! Utilities for working with `struct poll_table`. use crate ::{ + alloc::AllocError , bindings, fs::File , prelude::*, sync::{CondVar ,LockClassKey }, + types::Opaque ,// +}; +use core::{ + marker::PhantomData , + mem::ManuallyDrop , + ops::Deref ,// }; -use core::{marker::PhantomData , ops::Deref };/// Creates a [`PollCondVar`] initialiser with the given name and a newly-created lock class. #[macro_export]
@@ -66,6 +72,7 @@ pub fn register_wait(&self, file: &File, cv: &PollCondVar) {/// /// [`CondVar`]: crate::sync::CondVar #[pin_data( PinnedDrop )] +#[repr(transparent)] pub struct PollCondVar {#[pin] inner:CondVar ,
@@ -104,3 +111,67 @@ fn drop(self: Pin<&mut Self>) {unsafe { bindings::synchronize_rcu () }; } } + +/// A [`KBox<PollCondVar>`] that uses `kfree_rcu`. +/// +/// [`KBox<PollCondVar>`]: PollCondVar +pub struct PollCondVarBox { + inner:ManuallyDrop <Pin <KBox <PollCondVarBoxInner >>>, +} + +#[pin_data] +#[repr( C )] +struct PollCondVarBoxInner { +#[pin] + inner:PollCondVar , + rcu:Opaque <bindings::callback_head >, +} + +// SAFETY: PollCondVar is Send +unsafe impl Send for PollCondVarBoxInner {} +// SAFETY: PollCondVar is Sync +unsafe impl Sync for PollCondVarBoxInner {} + +impl PollCondVarBox { +/// Constructs a new boxed [`PollCondVar`]. +pub fn new (name: &'staticCStr , key:Pin <&'staticLockClassKey >) ->Result <Self ,AllocError > { +let b =KBox ::pin_init ( +pin_init! (PollCondVarBoxInner { + inner <-PollCondVar ::new (name, key), + rcu:Opaque ::uninit (), + }), +GFP_KERNEL , + ) + .map_err (|_|AllocError )?; + +Ok (PollCondVarBox { + inner:ManuallyDrop ::new (b), + }) + } +} + +impl Deref for PollCondVarBox { +type Target =PollCondVar ; +fn deref (&self) -> &PollCondVar { + &self.inner.inner + } +} + +impl Drop for PollCondVarBox { +#[inline] +fn drop (&mut self) { +// SAFETY: ManuallyDrop::take ok because not already taken. +let boxed =unsafe {ManuallyDrop ::take (&mut self.inner) }; + +// SAFETY: The code below frees the box without calling the actual destructor of the type, +// but it's okay because it re-implements the destructor using `kfree_rcu()` in place of +// `synchronize_rcu()`. +let ptr =KBox ::into_raw (unsafe {Pin ::into_inner_unchecked (boxed) }); + +// SAFETY: The pointer points at a valid `wait_queue_head`. +unsafe { bindings::__wake_up_pollfree ((*ptr).inner.inner.wait_queue_head.get ()) }; + +// SAFETY: This was allocated using `KBox::pin_init`, so it can be freed with `kvfree`. +unsafe { bindings::kvfree_call_rcu ((*ptr).rcu.get (), ptr.cast ::<ffi::c_void >()) }; + } +}
Signature · 1 line
2.55.0.rc2.803.g1fd1e6609c-goog
Re: [PATCH v6 1/2] rust: poll: use kfree_rcu() for PollCondVar
Quoted 11 lines · Alice Ryhl
Rust Binder currently uses PollCondVar, but it calls
synchronize_rcu()in the destructor, which we would like to avoid. Add a variation of PollCondVar thatkfree_rcu()instead.One could avoid the
rcufield and allocate thercu_headon drop using a fallback tosynchronize_rcu()on ENOMEM. However, I'd prefer to avoid the potential forsynchronize_rcu(), and Binder will only use this for a small fraction of processes, so even if it changes which kmalloc bucket it falls into, the extra memory is not a problem.Signed-off-by Alice Ryhl <[email protected]>
Let's switch to a better abstraction like RcuFreeBox later, but I don't see any issue of this approach in general.
Regards,
Boqun
Quoted 4 lines
--- rust/kernel/sync/poll.rs | 73 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-)
[..]
Alice Ryhl
maintainerPATCH v6 2/2 rust_binder: move (e)poll wait queue to Process
In reply to Alice RyhlMost processes do not use Rust Binder with epoll, so avoid paying the synchronize_rcu() cost in drop for those that don't need it. For those that do, we also manage to replace synchronize_rcu() with kfree_rcu(), though we introduce an extra allocation.
In case the last ref to an Arc<Thread> is dropped outside of deferred_release(), this also ensures that synchronize_rcu() is not called in destructor of Arc<Thread> in other places. Theoretically that could lead to jank by making other syscalls slow, which would be problematic.
--- drivers/android/binder/node.rs | 4 +- drivers/android/binder/process.rs | 67 ++++++++++++++++++++++-------- drivers/android/binder/thread.rs | 78 +++++++++++++++++------------------ drivers/android/binder/transaction.rs | 6 ++- 4 files changed, 95 insertions(+), 60 deletions(-)
drivers/android/binder/node.rs +2 -2
@@ -538,7 +538,7 @@ pub(crate) fn submit_oneway( inner.oneway_todo.push_back (transaction); }else { inner.has_oneway_transaction =true ; - guard.push_work (transaction)?; + guard.push_work (&self.owner, transaction)?; }Ok (()) }
@@ -570,7 +570,7 @@ pub(crate) fn pending_oneway_finished(&self) {let transaction = inner.oneway_todo.pop_front (); inner.has_oneway_transaction = transaction.is_some ();if let Some (transaction) = transaction { -match guard.push_work (transaction) { +match guard.push_work (&self.owner, transaction) {Ok (()) => {}Err ((_err, work)) => {// Process is dead.
drivers/android/binder/process.rs +49 -18
144 lines not on this page · raw message
drivers/android/binder/thread.rs +39 -39
195 lines not on this page · raw message
drivers/android/binder/transaction.rs +5 -1
@@ -371,11 +371,15 @@ pub(crate) fn submit(self: DLArc<Self>, info: &mut TransactionInfo) -> BinderRescrate ::trace::trace_transaction (false , &self,Some (&thread.task));match thread.push_work (self) {PushWorkRes ::Ok =>Ok (()), +PushWorkRes ::OkNotifyPoll => { + process.notify_poll (true ); +Ok (()) + }PushWorkRes ::FailedDead (me) =>Err ((BinderError ::new_dead (), me)), } }else {crate ::trace::trace_transaction (false , &self,None ); - process_inner.push_work (self) + process_inner.push_work (&process, self) };drop (process_inner);
Signature · 1 line
2.55.0.rc2.803.g1fd1e6609c-goog
Re: [PATCH v6 2/2] rust_binder: move (e)poll wait queue to Process
Quoted 13 lines · Alice Ryhl
Most processes do not use Rust Binder with epoll, so avoid paying the
synchronize_rcu()cost in drop for those that don't need it. For those that do, we also manage to replacesynchronize_rcu()withkfree_rcu(), though we introduce an extra allocation.In case the last ref to an Arc<Thread> is dropped outside of
deferred_release(), this also ensures thatsynchronize_rcu()is not called in destructor of Arc<Thread> in other places. Theoretically that could lead to jank by making other syscalls slow, which would be problematic.Signed-off-by Alice Ryhl <[email protected]>---
[...]
Quoted 4 lines
drivers/android/binder/process.rs +0
-0
[...]
Quoted 19 lines
} } }drivers/android/binder/process.rs +9
-0+ +pub (crate )fn notify_poll (&self, sync:bool ) { +if let Some (poll) = self.poll.as_ref () { +if sync { + poll.notify_sync (); + } + poll.notify_all (); + } + } }fn get_frozen_status (data:UserSlice ) ->Result {@@ -1726,7 +1743,21 @@ pub(crate) fn poll( table: PollTable<'_>, ) -> Result<u32> {let thread = this.get_current_thread ()?;
drivers/android/binder/process.rs pub(crate) fn poll( · line 1754
Quoted 10 lines
drivers/android/binder/process.rs +9
-1-let (from_proc,mut mask) = thread.poll (file, table); + { +let poll =loop { +if let Some (poll) = this.poll.as_ref () { +break poll; + } + +let poll =PollCondVarBox ::new (c"Process::poll" , kernel::static_lock_class!())?; +// Reuse our existing lock to synchronize callers initializing. +let _guard = this.node_refs.lock ();
Note sure whether this lock is needed? SetOnce::populate() should be atomic, i.e. only one populate() would win?
Also seems we should have a SetOnce::as_ref_or_populate(&self, default:
T).
The rest looks good to me. FWIW,
Regards,
Boqun
Quoted 9 lines
drivers/android/binder/process.rs +6
-0+ this.poll.populate (poll); + }; + + table.register_wait (file, poll); + } +let (from_proc,mut mask) = thread.poll ()?;if mask ==0 && from_proc && !this.inner.lock ().work.is_empty () { mask |= bindings::POLLIN ; }
[..]
Alice Ryhl
maintainerRe: [PATCH v6 2/2] rust_binder: move (e)poll wait queue to Process
Quoted 13 lines · Boqun Feng
drivers/android/binder/process.rs pub(crate) fn poll( · line 1756
Quoted 11 lines · Alice Ryhl
drivers/android/binder/process.rs +11
-0+ { +let poll =loop { +if let Some (poll) = this.poll.as_ref () { +break poll; + } + +let poll =PollCondVarBox ::new (c"Process::poll" , kernel::static_lock_class!())?; +// Reuse our existing lock to synchronize callers initializing. +let _guard = this.node_refs.lock (); + this.poll.populate (poll); + };
Quoted 5 lines
Note sure whether this lock is needed?
SetOnce::populate()should be atomic, i.e. only onepopulate()would win?Also seems we should have a SetOnce::as_ref_or_populate(&self, default:
T).
I'm taking this lock because I want to ensure that losers only loop once. The problem is that just because you lost the race in populate(), it's not guaranteed that as_ref() will return Some on the next iteration, since the winner of the race may still be busy executing populate(). Taking the loop avoids this possibility.
With regards to as_ref_or_populate(), I point you to this discussion for reasons why this is hard:
https://lore.kernel.org/all/[email protected]/
Quoted 3 lines
The rest looks good to me. FWIW,
Reviewed-by Boqun Feng <[email protected]>
Thanks!
Alice
Boqun Feng
maintainerRe: [PATCH v6 2/2] rust_binder: move (e)poll wait queue to Process
Quoted 14 lines · Alice Ryhl
Quoted 13 lines · Boqun Feng
Quoted 11 lines · Alice Ryhl
drivers/android/binder/process.rs +11
-0+ { +let poll =loop { +if let Some (poll) = this.poll.as_ref () { +break poll; + } + +let poll =PollCondVarBox ::new (c"Process::poll" , kernel::static_lock_class!())?; +// Reuse our existing lock to synchronize callers initializing. +let _guard = this.node_refs.lock (); + this.poll.populate (poll); + };
Quoted 8 lines
Quoted 5 lines
Note sure whether this lock is needed?
SetOnce::populate()should be atomic, i.e. only onepopulate()would win?Also seems we should have a SetOnce::as_ref_or_populate(&self, default:
T).I'm taking this lock because I want to ensure that losers only loop once. The problem is that just because you lost the race in
populate(),
Then probably you could add some comment explaining this. For example:
// Reuse our existing lock to synchronize callers initializing to
// make sure in the next iteration `as_ref()` will return `Some`.Quoted 8 lines
it's not guaranteed that
as_ref()will return Some on the next iteration, since the winner of the race may still be busy executingpopulate(). Taking the loop avoids this possibility.With regards to
as_ref_or_populate(), I point you to this discussion for reasons why this is hard:
https://lore.kernel.org/all/[email protected]/
Seems to me you really want OnceLock behavior here, and other code may have the same requirement in the future. So maybe we just add OnceLock for it? If the space cost is the concern, we can add a SetOnce::populate_with_lock(&self, lock: &Lock<..>) to provide users an option. I think it's better than open-code here.
Thoughts?
Regards,
Boqun
Quoted 7 lines
Quoted 3 lines
The rest looks good to me. FWIW,
Reviewed-by Boqun Feng <[email protected]>Thanks!
Alice
Alice Ryhl
maintainerRe: [PATCH v6 2/2] rust_binder: move (e)poll wait queue to Process
Quoted 21 lines · Boqun Feng
Quoted 20 lines · Alice Ryhl
Quoted 18 lines · Boqun Feng
drivers/android/binder/process.rs pub(crate) fn poll( · line 1756
Quoted 11 lines · Alice Ryhl
drivers/android/binder/process.rs +11
-0+ { +let poll =loop { +if let Some (poll) = this.poll.as_ref () { +break poll; + } + +let poll =PollCondVarBox ::new (c"Process::poll" , kernel::static_lock_class!())?; +// Reuse our existing lock to synchronize callers initializing. +let _guard = this.node_refs.lock (); + this.poll.populate (poll); + };Note sure whether this lock is needed?
SetOnce::populate()should be atomic, i.e. only onepopulate()would win?Also seems we should have a SetOnce::as_ref_or_populate(&self, default:
T).
Quoted 7 lines
Quoted 2 lines
I'm taking this lock because I want to ensure that losers only loop once. The problem is that just because you lost the race in
populate(),Then probably you could add some comment explaining this. For example:
// Reuse our existing lock to synchronize callers initializing to // make sure in the next iteration `as_ref()` will return `Some`.
I don't mind adding the comment.
Quoted 9 lines
Quoted 8 lines
it's not guaranteed that
as_ref()will return Some on the next iteration, since the winner of the race may still be busy executingpopulate(). Taking the loop avoids this possibility.With regards to
as_ref_or_populate(), I point you to this discussion for reasons why this is hard:
https://lore.kernel.org/all/[email protected]/
Quoted 7 lines
Seems to me you really want OnceLock behavior here, and other code may have the same requirement in the future. So maybe we just add OnceLock for it? If the space cost is the concern, we can add a
SetOnce::populate_with_lock(&self, lock: &Lock<..>)to provide users an option. I think it's better than open-code here.Thoughts?
Well, I don't think it's a bad idea.
The current code drops the value under the spinlock if populate() loses the race, and a populate_with_lock() could help avoid that, so that seems like a reasonable idea. It's not a big problem in this case (it's just a kfree_rcu() call after all), but could be a problem for other SetOnce users.
I mean, it'd be ideal if SetOnce could just properly support this, but like I discussed on the thread, there are a bunch of things to keep in mind if we want to actually do that. You want preemption disabled while you memcpy() in the value in populate(). I guess preemption doesn't matter for as_ref(), though. Not sure how that would interact with PREEMPT_RT.
Alice