Skip to contentSkip to conversation

rust_binder: update Process::node_refs to use SpinLock

PATCH Superseded Alice Ryhl 2 participants 13 messages Jun 9 – Jun 11

Subsystems (2)

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Alice Ryhl

author maintainer
#0 lore raw

v2 cover rust_binder: update Process::node_refs to use SpinLock

Unfortunately the current use of a mutex for this lock leads to priority inversion. Traces have been observed where a process is trying to obtain this mutex for 22ms, but it's unable to do so because the thread holding the lock is scheduled out. Since this occurred on a UI thread, that is an extremely long delay.

This patch series fixes that by first making a series of changes that remove the possibility of sleeping under the lock, and then finally changing it to a spinlock.

---
Changes in v2:
- Make more tweaks to various critical regions and extract them to
separate commits.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Alice Ryhl (6):
rust_binder: avoid allocating under node_refs for freeze listeners
rust_binder: avoid dropping NodeRef in update_ref() under lock
rust_binder: schedule NodeDeath outside of node_refs lock
rust_binder: keep NodeDeath in NodeRefInfo during process cleanup
rust_binder: avoid destructors in insert_or_update_handle()
rust_binder: update Process::node_refs to use SpinLock

 drivers/android/binder/freeze.rs  | 67 +++++++++++++++++++++++++++------------
 drivers/android/binder/node.rs    | 55 ++++++++++++++++++--------------
 drivers/android/binder/process.rs | 57 +++++++++++++++++++--------------
 3 files changed, 111 insertions(+), 68 deletions(-)

---
base-commit: da61573f783897ae5a96c8f1c71aad6242344feb
change-id: 20260608-binder-noderefs-spin-3a0ec0589043

Best regards,

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

PATCH v2 1/6 rust_binder: avoid allocating under node_refs for freeze listeners

The node_refs mutex needs to be changed to a spinlock, so in preparation for that, update freeze.rs to avoid allocating under the node_refs lock. This is done by adding a retry loop so that if add_freeze_listener() requires reallocating the KVVec<_> of freeze listeners, the caller will allocate a larger vector and retry.

Analogously, the remove_freeze_listener() function is updated to return the empty KVVec<_> when it is no longer needed, to avoid calling kvfree() under the node_refs lock.

---
 drivers/android/binder/freeze.rs | 67 +++++++++++++++++++++++++++-------------
 drivers/android/binder/node.rs   | 55 +++++++++++++++++++--------------
 2 files changed, 77 insertions(+), 45 deletions(-)
drivers/android/binder/freeze.rs +46 -21
index 53b60035639a..20041689e98d 100644
@@ -173,36 +173,60 @@ pub(crate) fn request_freeze_notif(
         let msg = FreezeMessage::new(GFP_KERNEL)?;
         let alloc = RBTreeNodeReservation::new(GFP_KERNEL)?;
 
+        let mut afl_vec_alloc = KVVec::new();
+        let mut info;
+        let mut node;
+        let mut freeze_entry;
         let mut node_refs_guard = self.node_refs.lock();
-        let node_refs = &mut *node_refs_guard;
-        let Some(info) = node_refs.by_handle.get_mut(&handle) else {
-            pr_warn!("BC_REQUEST_FREEZE_NOTIFICATION invalid ref {}\n", handle);
-            return Err(EINVAL);
-        };
-        if info.freeze().is_some() {
-            pr_warn!("BC_REQUEST_FREEZE_NOTIFICATION already set\n");
-            return Err(EINVAL);
-        }
-        let node_ref = info.node_ref();
-        let freeze_entry = node_refs.freeze_listeners.entry(cookie);
-
-        if let rbtree::Entry::Occupied(ref dupe) = freeze_entry {
-            if !dupe.get().allow_duplicate(&node_ref.node) {
-                pr_warn!("BC_REQUEST_FREEZE_NOTIFICATION duplicate cookie\n");
+        loop {
+            let node_refs = &mut *node_refs_guard;
+            info = match node_refs.by_handle.get_mut(&handle) {
+                Some(info) => info,
+                None => {
+                    pr_warn!("BC_REQUEST_FREEZE_NOTIFICATION invalid ref {}\n", handle);
+                    return Err(EINVAL);
+                }
+            };
+            if info.freeze().is_some() {
+                pr_warn!("BC_REQUEST_FREEZE_NOTIFICATION already set\n");
                 return Err(EINVAL);
             }
-        }
+            let node_ref = info.node_ref();
+            node = node_ref.node.clone();
+            freeze_entry = node_refs.freeze_listeners.entry(cookie);
+
+            if let rbtree::Entry::Occupied(ref dupe) = freeze_entry {
+                if !dupe.get().allow_duplicate(&node_ref.node) {
+                    pr_warn!("BC_REQUEST_FREEZE_NOTIFICATION duplicate cookie\n");
+                    return Err(EINVAL);
+                }
+            }
 
-        // All failure paths must come before this call, and all modifications must come after this
-        // call.
-        node_ref.node.add_freeze_listener(self, GFP_KERNEL)?;
+            // Now we add to the node's freeze listener list, with retry and re-allocate if the
+            // vector is full.
+            //
+            // To ensure that the node is added atomically, this is the first time we modify any
+            // state. When this call succeeds, all other modifications must occur without the
+            // possibility for any failure paths.
+            match node_ref
+                .node
+                .add_freeze_listener(self, &mut afl_vec_alloc)?
+            {
+                Ok(()) => break,
+                Err(resize_target) => {
+                    drop(node_refs_guard);
+                    Node::resize_for_add_freeze_listener(&mut afl_vec_alloc, resize_target)?;
+                    node_refs_guard = self.node_refs.lock();
+                }
+            }
+        }
 
         match freeze_entry {
             rbtree::Entry::Vacant(entry) => {
                 entry.insert(
                     FreezeListener {
                         cookie,
-                        node: node_ref.node.clone(),
+                        node,
                         last_is_frozen: None,
                         is_pending: false,
                         is_clearing: false,
@@ -273,6 +297,7 @@ pub(crate) fn clear_freeze_notif(self: &Arc<Self>, reader: &mut UserSliceReader)
         let handle = hc.handle;
         let cookie = FreezeCookie(hc.cookie);
 
+        let _to_free_fl;
         let alloc = FreezeMessage::new(GFP_KERNEL)?;
         let mut node_refs_guard = self.node_refs.lock();
         let node_refs = &mut *node_refs_guard;
@@ -293,7 +318,7 @@ pub(crate) fn clear_freeze_notif(self: &Arc<Self>, reader: &mut UserSliceReader)
             return Err(EINVAL);
         };
         listener.is_clearing = true;
-        listener.node.remove_freeze_listener(self);
+        _to_free_fl = listener.node.remove_freeze_listener(self);
         *info.freeze() = None;
         let mut msg = None;
         if !listener.is_pending {
drivers/android/binder/node.rs +31 -24

73 lines not on this page · raw message

Signature · 1 line
2.54.0.1064.gd145956f57-goog
Reviewed-by on v2 1/6
#2 lore raw

Re: [PATCH v2 1/6] rust_binder: avoid allocating under node_refs for freeze listeners

Quoted 7 lines · Alice Ryhl

The node_refs mutex needs to be changed to a spinlock, so in preparation for that, update freeze.rs to avoid allocating under the node_refs lock. This is done by adding a retry loop so that if add_freeze_listener() requires reallocating the KVVec<_> of freeze listeners, the caller will allocate a larger vector and retry.

Quoted 5 lines

Analogously, the remove_freeze_listener() function is updated to return the empty KVVec<_> when it is no longer needed, to avoid calling kvfree() under the node_refs lock.

Nit: Consider moving the clone to the success path at the end, since the cloned node is not used until then? It's probably cheap enough that it doesn't matter though.

Quoted 2 lines

+ node = node_ref.node.clone();

This is wrapping a single line, and is only called once. Why add a separate function for it?

drivers/android/binder/node.rs fn do_work_locked( · line 688

Quoted 7 lines
drivers/android/binder/node.rs +6 -0
+    pub(crate) fn resize_for_add_freeze_listener(
+        vec_alloc: &mut KVVec<Arc<Process>>,
+        target_size: usize,
+    ) -> Result {
+        *vec_alloc = KVVec::with_capacity(target_size.next_power_of_two(), GFP_KERNEL)?;
+        Ok(())
     }

Otherwise looks fine.

author maintainer
#3 lore raw

PATCH v2 2/6 rust_binder: avoid dropping NodeRef in update_ref() under lock

In reply to Alice Ryhl

In preparation for changing the node_refs lock to a spinlock, move the cleanup of NodeRefInfo in update_ref() so that it occurs without the node_refs lock held. This avoids dropping an Arc<Node> with the lock held. Furthermore, the NodeDeath field is kept in the NodeRefInfo to be dropped outside the lock as well.

The removal from the rbtree is updated to use remove_node(), which keeps the rbtree node allocation until after node_refs is unlocked as well. This is not strictly necessary as it just moves a kfree() outside the lock, but there's no reason to invoke the kfree() under the lock if we can easily avoid it, so avoid it.

---
 drivers/android/binder/process.rs | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/android/binder/process.rs +8 -4
index 96b8440ceac6..f4f4d45e1ab7 100644
@@ -942,13 +942,17 @@ pub(crate) fn update_ref(
 
         // To preserve original binder behaviour, we only fail requests where the manager tries to
         // increment references on itself.
+        let _to_free_by_handle;
+        let _to_free_by_node;
         let mut refs = self.node_refs.lock();
         if let Some(info) = refs.by_handle.get_mut(&handle) {
             if info.node_ref().update(inc, strong) {
                 // Clean up death if there is one attached to this node reference.
-                if let Some(death) = info.death().take() {
+                //
+                // We remove the entire `info` below, so no need to remove `death` from `info`.
+                if let Some(death) = info.death().as_ref() {
                     death.set_cleared(true);
-                    self.remove_from_delivered_deaths(&death);
+                    self.remove_from_delivered_deaths(death);
                 }
 
                 // Remove reference from process tables, and from the node's `refs` list.
@@ -957,8 +961,8 @@ pub(crate) fn update_ref(
                 unsafe { info.node_ref2().node.remove_node_info(info) };
 
                 let id = info.node_ref().node.global_id();
-                refs.by_handle.remove(&handle);
-                refs.by_node.remove(&id);
+                _to_free_by_handle = refs.by_handle.remove_node(&handle);
+                _to_free_by_node = refs.by_node.remove_node(&id);
                 refs.handle_is_present.release_id(handle as usize);
 
                 if let Some(shrink) = refs.handle_is_present.shrink_request() {
Signature · 1 line
2.54.0.1064.gd145956f57-goog
Reviewed-by on v2 2/6
#4 lore raw

Re: [PATCH v2 2/6] rust_binder: avoid dropping NodeRef in update_ref() under lock

Quoted 55 lines · Alice Ryhl

In preparation for changing the node_refs lock to a spinlock, move the cleanup of NodeRefInfo in update_ref() so that it occurs without the node_refs lock held. This avoids dropping an Arc<Node> with the lock held. Furthermore, the NodeDeath field is kept in the NodeRefInfo to be dropped outside the lock as well.

The removal from the rbtree is updated to use remove_node(), which keeps the rbtree node allocation until after node_refs is unlocked as well. This is not strictly necessary as it just moves a kfree() outside the lock, but there's no reason to invoke the kfree() under the lock if we can easily avoid it, so avoid it.

---
 drivers/android/binder/process.rs | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/android/binder/process.rs +8 -5
index 96b8440ceac6..f4f4d45e1ab7 100644
@@ -942,13 +942,17 @@ pub(crate) fn update_ref(
 
         // To preserve original binder behaviour, we only fail requests where the manager tries to
         // increment references on itself.
+        let _to_free_by_handle;
+        let _to_free_by_node;
         let mut refs = self.node_refs.lock();
         if let Some(info) = refs.by_handle.get_mut(&handle) {
             if info.node_ref().update(inc, strong) {
                 // Clean up death if there is one attached to this node reference.
-                if let Some(death) = info.death().take() {
+                //
+                // We remove the entire `info` below, so no need to remove `death` from `info`.
+                if let Some(death) = info.death().as_ref() {
                     death.set_cleared(true);
-                    self.remove_from_delivered_deaths(&death);
+                    self.remove_from_delivered_deaths(death);
                 }
 
                 // Remove reference from process tables, and from the node's `refs` list.
@@ -957,8 +961,8 @@ pub(crate) fn update_ref(
                 unsafe { info.node_ref2().node.remove_node_info(info) };
 
                 let id = info.node_ref().node.global_id();
-                refs.by_handle.remove(&handle);
-                refs.by_node.remove(&id);
+                _to_free_by_handle = refs.by_handle.remove_node(&handle);
+                _to_free_by_node = refs.by_node.remove_node(&id);
                 refs.handle_is_present.release_id(handle as usize);
 
                 if let Some(shrink) = refs.handle_is_present.shrink_request() {
 
--
Quoted 3 lines

2.54.0.1064.gd145956f57-goog

author maintainer
#5 lore raw

PATCH v2 3/6 rust_binder: schedule NodeDeath outside of node_refs lock

In reply to Alice Ryhl

There's no reason to hold the node_refs lock while scheduling the NodeDeath to the thread todo list, so don't. The call to set_cleared() is kept under the lock so that the state update is kept atomic.

---
 drivers/android/binder/process.rs | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/android/binder/process.rs +4 -1
index f4f4d45e1ab7..a8836cb8b8cc 100644
@@ -1289,7 +1289,10 @@ pub(crate) fn clear_death(&self, reader: &mut UserSliceReader, thread: &Thread)
 
         // Update state and determine if we need to queue a work item. We only need to do it when
         // the node is not dead or if the user already completed the death notification.
-        if death.set_cleared(false) {
+        let should_schedule = death.set_cleared(false);
+        drop(refs);
+
+        if should_schedule {
             if let Some(death) = ListArc::try_from_arc_or_drop(death) {
                 let _ = thread.push_work_if_looper(death);
             }
Signature · 1 line
2.54.0.1064.gd145956f57-goog
Reviewed-by on v2 3/6
#6 lore raw

Re: [PATCH v2 3/6] rust_binder: schedule NodeDeath outside of node_refs lock

Quoted 28 lines · Alice Ryhl

There's no reason to hold the node_refs lock while scheduling the NodeDeath to the thread todo list, so don't. The call to set_cleared() is kept under the lock so that the state update is kept atomic.

---
 drivers/android/binder/process.rs | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/android/binder/process.rs +4 -2
index f4f4d45e1ab7..a8836cb8b8cc 100644
@@ -1289,7 +1289,10 @@ pub(crate) fn clear_death(&self, reader: &mut UserSliceReader, thread: &Thread)
 
         // Update state and determine if we need to queue a work item. We only need to do it when
         // the node is not dead or if the user already completed the death notification.
-        if death.set_cleared(false) {
+        let should_schedule = death.set_cleared(false);
+        drop(refs);
+
+        if should_schedule {
             if let Some(death) = ListArc::try_from_arc_or_drop(death) {
                 let _ = thread.push_work_if_looper(death);
             }
 
--
Quoted 3 lines

2.54.0.1064.gd145956f57-goog

author maintainer
#7 lore raw

PATCH v2 4/6 rust_binder: keep NodeDeath in NodeRefInfo during process cleanup

In reply to Alice Ryhl

By keeping the NodeDeath inside the NodeRefInfo structure during process cleanup, we avoid running its destructor under the node_refs lock. It is still dropped shortly thereafter when the entire rbtree holding the NodeRefInfo objects is dropped, but that occurs outside of the lock.

---
 drivers/android/binder/process.rs | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)
drivers/android/binder/process.rs +5 -7
index a8836cb8b8cc..c8e9fd0d0472 100644
@@ -1375,13 +1375,11 @@ fn deferred_release(self: Arc<Self>) {
             // SAFETY: We are removing the `NodeRefInfo` from the right node.
             unsafe { info.node_ref2().node.remove_node_info(info) };
 
-            // Remove all death notifications from the nodes (that belong to a different process).
-            let death = if let Some(existing) = info.death().take() {
-                existing
-            } else {
-                continue;
-            };
-            death.set_cleared(false);
+            // Clear death notifications from the nodes (that belong to a different process).
+            // No need to remove them from `info` as we clear info below.
+            if let Some(death) = info.death().as_ref() {
+                death.set_cleared(false);
+            }
         }
 
         // Clean up freeze listeners.
Signature · 1 line
2.54.0.1064.gd145956f57-goog
Reviewed-by on v2 4/6
#8 lore raw

Re: [PATCH v2 4/6] rust_binder: keep NodeDeath in NodeRefInfo during process cleanup

Quoted 11 lines · Alice Ryhl

By keeping the NodeDeath inside the NodeRefInfo structure during process cleanup, we avoid running its destructor under the node_refs lock. It is still dropped shortly thereafter when the entire rbtree holding the NodeRefInfo objects is dropped, but that occurs outside of the lock.

---
 drivers/android/binder/process.rs | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)
author maintainer
#9 lore raw

PATCH v2 5/6 rust_binder: avoid destructors in insert_or_update_handle()

In reply to Alice Ryhl

The insert_or_update_handle() function currently has two places where it drops objects under the node_refs lock. In preparation for changing node_refs into a spinlock, update the code to either entirely remove the codepath or drop the node_refs lock first before running the destructor.

This also has the side-benefit that we avoid traversing the by_node rbtree twice. Currently it's first traversed to see if the new node is present, and then traversed again to insert it. By saving the VacantEntry from the first lookup, we can perform the insertion without traversing the tree again.

---
 drivers/android/binder/process.rs | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)
drivers/android/binder/process.rs +14 -8
index c8e9fd0d0472..268d78f8cfb3 100644
@@ -861,14 +861,17 @@ pub(crate) fn insert_or_update_handle(
         let handle = unused_id.as_u32();
 
         // Do a lookup again as node may have been inserted before the lock was reacquired.
-        if let Some(handle_ref) = refs.by_node.get(&node_ref.node.global_id()) {
-            let handle = *handle_ref;
-            let info = refs.by_handle.get_mut(&handle).unwrap();
-            info.node_ref().absorb(node_ref);
-            return Ok(handle);
-        }
+        let by_node_slot = match refs.by_node.entry(node_ref.node.global_id()) {
+            rbtree::Entry::Vacant(by_node_slot) => by_node_slot,
+            rbtree::Entry::Occupied(handle_ref) => {
+                // The node was inserted by another thread while we didn't hold the lock.
+                let handle = handle_ref.get();
+                let info = refs.by_handle.get_mut(handle).unwrap();
+                info.node_ref().absorb(node_ref);
+                return Ok(*handle);
+            }
+        };
 
-        let gid = node_ref.node.global_id();
         let (info_proc, info_node) = {
             let info_init = NodeRefInfo::new(node_ref, handle, self.into());
             match info.pin_init_with(info_init) {
@@ -884,6 +887,9 @@ pub(crate) fn insert_or_update_handle(
         // first thing in `deferred_release`, process cleanup will not miss the items inserted into
         // `refs` below.
         if self.inner.lock().is_dead {
+            // Explicitly drop the lock so that `info_proc` and `info_node` are dropped outside of
+            // the lock.
+            drop(refs_lock);
             return Err(ESRCH);
         }
 
@@ -891,7 +897,7 @@ pub(crate) fn insert_or_update_handle(
         // `info_node` into the right node's `refs` list.
         unsafe { info_proc.node_ref2().node.insert_node_info(info_node) };
 
-        refs.by_node.insert(reserve1.into_node(gid, handle));
+        by_node_slot.insert(handle, reserve1);
         by_handle_slot.insert(info_proc, reserve2);
         unused_id.acquire();
         Ok(handle)
Signature · 1 line
2.54.0.1064.gd145956f57-goog
Reviewed-by on v2 5/6
#10 lore raw

Re: [PATCH v2 5/6] rust_binder: avoid destructors in insert_or_update_handle()

Quoted 67 lines · Alice Ryhl

The insert_or_update_handle() function currently has two places where it drops objects under the node_refs lock. In preparation for changing node_refs into a spinlock, update the code to either entirely remove the codepath or drop the node_refs lock first before running the destructor.

This also has the side-benefit that we avoid traversing the by_node rbtree twice. Currently it's first traversed to see if the new node is present, and then traversed again to insert it. By saving the VacantEntry from the first lookup, we can perform the insertion without traversing the tree again.

---
 drivers/android/binder/process.rs | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)
drivers/android/binder/process.rs +14 -9
index c8e9fd0d0472..268d78f8cfb3 100644
@@ -861,14 +861,17 @@ pub(crate) fn insert_or_update_handle(
         let handle = unused_id.as_u32();
 
         // Do a lookup again as node may have been inserted before the lock was reacquired.
-        if let Some(handle_ref) = refs.by_node.get(&node_ref.node.global_id()) {
-            let handle = *handle_ref;
-            let info = refs.by_handle.get_mut(&handle).unwrap();
-            info.node_ref().absorb(node_ref);
-            return Ok(handle);
-        }
+        let by_node_slot = match refs.by_node.entry(node_ref.node.global_id()) {
+            rbtree::Entry::Vacant(by_node_slot) => by_node_slot,
+            rbtree::Entry::Occupied(handle_ref) => {
+                // The node was inserted by another thread while we didn't hold the lock.
+                let handle = handle_ref.get();
+                let info = refs.by_handle.get_mut(handle).unwrap();
+                info.node_ref().absorb(node_ref);
+                return Ok(*handle);
+            }
+        };
 
-        let gid = node_ref.node.global_id();
         let (info_proc, info_node) = {
             let info_init = NodeRefInfo::new(node_ref, handle, self.into());
             match info.pin_init_with(info_init) {
@@ -884,6 +887,9 @@ pub(crate) fn insert_or_update_handle(
         // first thing in `deferred_release`, process cleanup will not miss the items inserted into
         // `refs` below.
         if self.inner.lock().is_dead {
+            // Explicitly drop the lock so that `info_proc` and `info_node` are dropped outside of
+            // the lock.
+            drop(refs_lock);
             return Err(ESRCH);
         }
 
@@ -891,7 +897,7 @@ pub(crate) fn insert_or_update_handle(
         // `info_node` into the right node's `refs` list.
         unsafe { info_proc.node_ref2().node.insert_node_info(info_node) };
 
-        refs.by_node.insert(reserve1.into_node(gid, handle));
+        by_node_slot.insert(handle, reserve1);
         by_handle_slot.insert(info_proc, reserve2);
         unused_id.acquire();
         Ok(handle)
 
--
Quoted 3 lines

2.54.0.1064.gd145956f57-goog

author maintainer
#11 lore raw

PATCH v2 6/6 rust_binder: update Process::node_refs to use SpinLock

In reply to Alice Ryhl

Unfortunately the current use of a mutex for this lock leads to priority inversion. Traces have been observed where a process is trying to obtain this mutex for 22ms, but it's unable to do so because the thread holding the lock is scheduled out. Since this occurred on a UI thread, that is an extremely long delay.

Code paths that might sleep under this lock have already been updated in patches leading up to this one.

---
 drivers/android/binder/process.rs | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/android/binder/process.rs +3 -3
index 268d78f8cfb3..82c34a93660e 100644
@@ -30,7 +30,7 @@
     sync::{
         aref::ARef,
         lock::{spinlock::SpinLockBackend, Guard},
-        Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock, UniqueArc,
+        Arc, ArcBorrow, CondVar, CondVarTimeoutResult, SpinLock, UniqueArc,
     },
     task::Task,
     uaccess::{UserSlice, UserSliceReader},
@@ -455,7 +455,7 @@ pub(crate) struct Process {
     // Node references are in a different lock to avoid recursive acquisition when
     // incrementing/decrementing a node in another process.
     #[pin]
-    node_refs: Mutex<ProcessNodeRefs>,
+    node_refs: SpinLock<ProcessNodeRefs>,
 
     // Work node for deferred work item.
     #[pin]
@@ -510,7 +510,7 @@ fn new(ctx: Arc<Context>, cred: ARef<Credential>) -> Result<Arc<Self>> {
                 cred,
                 inner <- kernel::new_spinlock!(ProcessInner::new(), "Process::inner"),
                 pages <- ShrinkablePageRange::new(&super::BINDER_SHRINKER),
-                node_refs <- kernel::new_mutex!(ProcessNodeRefs::new(), "Process::node_refs"),
+                node_refs <- kernel::new_spinlock!(ProcessNodeRefs::new(), "Process::node_refs"),
                 freeze_wait <- kernel::new_condvar!("Process::freeze_wait"),
                 task: current.group_leader().into(),
                 defer_work <- kernel::new_work!("Process::defer_work"),
Signature · 1 line
2.54.0.1064.gd145956f57-goog
Reviewed-by on v2 6/6
#12 lore raw
Quoted 48 lines · Alice Ryhl

Unfortunately the current use of a mutex for this lock leads to priority inversion. Traces have been observed where a process is trying to obtain this mutex for 22ms, but it's unable to do so because the thread holding the lock is scheduled out. Since this occurred on a UI thread, that is an extremely long delay.

Code paths that might sleep under this lock have already been updated in patches leading up to this one.

---
 drivers/android/binder/process.rs | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/android/binder/process.rs +3 -4
index 268d78f8cfb3..82c34a93660e 100644
@@ -30,7 +30,7 @@
     sync::{
         aref::ARef,
         lock::{spinlock::SpinLockBackend, Guard},
-        Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock, UniqueArc,
+        Arc, ArcBorrow, CondVar, CondVarTimeoutResult, SpinLock, UniqueArc,
     },
     task::Task,
     uaccess::{UserSlice, UserSliceReader},
@@ -455,7 +455,7 @@ pub(crate) struct Process {
     // Node references are in a different lock to avoid recursive acquisition when
     // incrementing/decrementing a node in another process.
     #[pin]
-    node_refs: Mutex<ProcessNodeRefs>,
+    node_refs: SpinLock<ProcessNodeRefs>,
 
     // Work node for deferred work item.
     #[pin]
@@ -510,7 +510,7 @@ fn new(ctx: Arc<Context>, cred: ARef<Credential>) -> Result<Arc<Self>> {
                 cred,
                 inner <- kernel::new_spinlock!(ProcessInner::new(), "Process::inner"),
                 pages <- ShrinkablePageRange::new(&super::BINDER_SHRINKER),
-                node_refs <- kernel::new_mutex!(ProcessNodeRefs::new(), "Process::node_refs"),
+                node_refs <- kernel::new_spinlock!(ProcessNodeRefs::new(), "Process::node_refs"),
                 freeze_wait <- kernel::new_condvar!("Process::freeze_wait"),
                 task: current.group_leader().into(),
                 defer_work <- kernel::new_work!("Process::defer_work"),
 
--
Quoted 3 lines

2.54.0.1064.gd145956f57-goog