Avoid synchronize_rcu() for every thread drop in Rust Binder
Subsystems (4)
Alice Ryhl
maintainerv3 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.
---
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/process.rs | 51 +++++++++++++++++------ drivers/android/binder/thread.rs | 78 +++++++++++++++++------------------ drivers/android/binder/transaction.rs | 4 ++ rust/kernel/sync/poll.rs | 73 +++++++++++++++++++++++++++++++- 4 files changed, 154 insertions(+), 52 deletions(-)
---
base-commit: 254f49634ee16a731174d2ae34bc50bd5f45e731
change-id: 20260117-upgrade-poll-37ee2a7a79dd
Best regards,
Signature · 1 line
Alice Ryhl <[email protected]>
Alice Ryhl
maintainerPATCH v3 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.54.0.563.g4f69b47b94-goog
Alice Ryhl
maintainerPATCH v3 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/process.rs | 51 +++++++++++++++++------ drivers/android/binder/thread.rs | 78 +++++++++++++++++------------------ drivers/android/binder/transaction.rs | 4 ++ 3 files changed, 82 insertions(+), 51 deletions(-)
drivers/android/binder/process.rs +39 -12
@@ -30,6 +30,7 @@ sync::{ aref::ARef, lock::{spinlock::SpinLockBackend, Guard}, + poll::PollCondVarBox, Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock, UniqueArc, }, task::Task,
@@ -135,6 +136,7 @@ pub(crate) struct ProcessInner { pub(crate) binderfs_file: Option<BinderfsProcFile>,/// Check for oneway spam oneway_spam_detection_enabled: bool, + poll: Option<PollCondVarBox>, }impl ProcessInner {
@@ -158,6 +160,7 @@ fn new() -> Self { async_recv: false, binderfs_file: None, oneway_spam_detection_enabled: false, + poll: None, } }
@@ -174,19 +177,23 @@ pub(crate) fn push_work( &mut self, work: DLArc<dyn DeliverToRead>, ) -> Result<(), (BinderError, DLArc<dyn DeliverToRead>)> { +let sync = work.should_sync_wakeup (); +// Try to find a ready thread to which to push the work. if let Some (thread) = self.ready_threads.pop_front () {// Push to thread while holding state lock. This prevents the thread from giving up // (for example, because of a signal) when we're about to deliver work. -match thread.push_work (work) { +match thread.push_work_inner (work, sync) {PushWorkRes ::Ok =>Ok (()), +PushWorkRes ::OkNotifyPoll => { + self.notify_poll (sync); +Ok (()) + }PushWorkRes ::FailedDead (work) =>Err ((BinderError ::new_dead (), work)), } }else if self.is_dead {Err ((BinderError ::new_dead (), work)) }else { -let sync = work.should_sync_wakeup (); -// Didn't find a thread waiting for proc work; this can happen // in two scenarios: // 1. All threads are busy handling transactions
@@ -194,22 +201,26 @@ pub(crate) fn push_work(// the kernel driver soon and pick up this work. // 2. Threads are using the (e)poll interface, in which case // they may be blocked on the waitqueue without having been -// added to waiting_threads. For this case, we just iterate -// over all threads not handling transaction work, and -// wake them all up. We wake all because we don't know whether -// a thread that called into (e)poll is handling non-binder -// work currently. +// added to waiting_threads. For this case, we wake it up +// directly. self.work.push_back (work);// Wake up polling threads, if any. -for threadin self.threads.values () { - thread.notify_if_poll_ready (sync); - } + self.notify_poll (sync);Ok (()) } } +pub (crate )fn notify_poll (&self, sync:bool ) { +if let Some (poll) = &self.poll { +if sync { + poll.notify_sync (); + } + poll.notify_all (); + } + } +pub (crate )fn remove_node (&mut self, ptr:u64 ) { self.nodes.remove (&ptr); }
@@ -1322,11 +1333,15 @@ fn deferred_flush(&self) {fn deferred_release (self:Arc <Self >) {let is_manager = { +// These variables contain values to be dropped after releasing spinlock. +let _poll; +let mut inner = self.inner.lock (); inner.is_dead =true ; inner.is_frozen =IsFrozen ::No ; inner.sync_recv =false ; inner.async_recv =false ; + _poll = inner.poll.take (); inner.is_manager };
@@ -1696,7 +1711,19 @@ pub(crate) fn poll( table: PollTable<'_>, ) -> Result<u32> {let thread = this.get_current_thread ()?; -let (from_proc,mut mask) = thread.poll (file, table); + { +let mut inner = this.inner.lock (); +let poll =if let Some (poll) = &inner.poll { + &**poll + }else { +drop (inner); +let poll =PollCondVarBox ::new (c"Process::poll" , kernel::static_lock_class!())?; + inner = this.inner.lock (); + &**inner.poll.get_or_insert (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 ; }
drivers/android/binder/thread.rs +39 -39
195 lines not on this page · raw message
drivers/android/binder/transaction.rs +4 -0
@@ -322,6 +322,10 @@ 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_inner.notify_poll (true ); +Ok (()) + }PushWorkRes ::FailedDead (me) =>Err ((BinderError ::new_dead (), me)), } }else {
Signature · 1 line
2.54.0.563.g4f69b47b94-goog