[PATCH 2/4] rust_binder: add support for thread timeout
From: Nicholas Giunta
Date: Thu Dec 03 2026 - 19:33:24 EST
Allow idle registered binder looper threads to be terminated and have
their resources reclaimed using the existing BINDER_SET_IDLE_TIMEOUT
ioctl and BR_FINISHED return command, and document their semantics
(including runtime reconfiguration) in
include/uapi/linux/android/binder.h. Android's libbinder
(IPCThreadState::joinThreadPool()) already consumes BR_FINISHED by
breaking out of its looper loop and issuing BC_EXIT_LOOPER followed by
BINDER_THREAD_EXIT.
Per-process idle timeout defaults to disabled (Delta::ZERO) and can be
configured in milliseconds via BINDER_SET_IDLE_TIMEOUT (rejecting
negative values with EINVAL). Only registered looper threads spawned via
BR_SPAWN_LOOPER are eligible to time out; main threads registered with
BC_ENTER_LOOPER and polling threads remain exempt.
When a thread's idle timeout expires while it is the sole thread in
ready_threads, retain it with a deferred timeout flag
(InnerThread::deferred_timeout / ProcessInner::has_deferred_timeout) so
at least one ready thread remains warm for incoming work; once a peer
joins ready_threads, notify the deferred thread to exit with BR_FINISHED
(or deliver incoming work if a transaction arrives first). Resetting
BINDER_SET_IDLE_TIMEOUT to 0 clears any active deferred timeout and
prevents waiting threads from spinning down.
Also suppress BR_SPAWN_LOOPER on timeout returns, guard
BC_REGISTER_LOOPER's register_thread() with !inner.is_looper() under
Process::inner -> Thread::inner while recording LooperFlag::Started, and
decrement started_thread_count in Process::remove_thread() only for
started loopers so spun-down threads can be respawned without leaking or
double-counting under duplicate or mixed looper commands.
Assisted-by: Gemini
Signed-off-by: Nicholas Giunta <grahalt@xxxxxxxxxx>
---
drivers/android/binder/defs.rs | 1 +
drivers/android/binder/process.rs | 110 ++++++++++++++++++++++++++++++---
drivers/android/binder/thread.rs | 117 +++++++++++++++++++++++++++++++++---
include/uapi/linux/android/binder.h | 14 ++++-
4 files changed, 220 insertions(+), 22 deletions(-)
diff --git a/drivers/android/binder/defs.rs b/drivers/android/binder/defs.rs
index cc4becd6e168..8c1d24e057f5 100644
--- a/drivers/android/binder/defs.rs
+++ b/drivers/android/binder/defs.rs
@@ -24,6 +24,7 @@ macro_rules! pub_no_prefix {
BR_REPLY,
BR_DEAD_REPLY,
BR_FAILED_REPLY,
+ BR_FINISHED,
BR_FROZEN_REPLY,
BR_NOOP,
BR_SPAWN_LOOPER,
diff --git a/drivers/android/binder/process.rs b/drivers/android/binder/process.rs
index e97213250beb..7f51a500707e 100644
--- a/drivers/android/binder/process.rs
+++ b/drivers/android/binder/process.rs
@@ -35,6 +35,7 @@
Arc, ArcBorrow, CondVar, CondVarTimeoutResult, SetOnce, SpinLock, UniqueArc,
},
task::{Pid, Task},
+ time::Delta,
uaccess::{UserSlice, UserSliceReader},
uapi,
workqueue::{self, Work},
@@ -130,6 +131,10 @@ pub(crate) struct ProcessInner {
max_threads: u32,
/// The number of threads the started and registered with the thread pool.
started_thread_count: u32,
+ /// The timeout duration that threads idle before being released via `BR_FINISHED`.
+ idle_timeout: Delta,
+ /// Whether the sole thread in `ready_threads` has a deferred idle timeout.
+ has_deferred_timeout: bool,
/// Bitmap of deferred work to do.
defer_work: DeferWorks,
@@ -162,6 +167,8 @@ fn new() -> Self {
requested_thread_count: 0,
max_threads: 0,
started_thread_count: 0,
+ idle_timeout: Delta::ZERO,
+ has_deferred_timeout: false,
defer_work: DeferWorks::default(),
outstanding_txns: 0,
is_frozen: IsFrozen::No,
@@ -190,6 +197,7 @@ pub(crate) fn push_work(
// Try to find a ready thread to which to push the work.
if let Some(thread) = self.ready_threads.pop_front() {
+ self.has_deferred_timeout = false;
// 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_inner(work, sync) {
@@ -297,7 +305,11 @@ fn get_existing_node(&self, ptr: u64, cookie: u64) -> Result<Option<DArc<Node>>>
}
}
- fn register_thread(&mut self) -> bool {
+ pub(crate) fn idle_timeout(&self) -> Delta {
+ self.idle_timeout
+ }
+
+ pub(crate) fn register_thread(&mut self) -> bool {
if self.requested_thread_count == 0 {
return false;
}
@@ -708,7 +720,14 @@ pub(crate) fn get_work_or_register<'a>(
}
// Register the thread as ready.
- GetWorkOrRegister::Register(Registration::new(thread, &mut inner))
+ let mut deferred = None;
+ let reg = Registration::new(thread, &mut inner, &mut deferred);
+ let idle_timeout = inner.idle_timeout;
+ drop(inner);
+ if let Some(prev) = deferred {
+ prev.notify_if_deferred_timeout();
+ }
+ GetWorkOrRegister::Register(reg, idle_timeout)
}
fn get_current_thread(self: ArcBorrow<'_, Self>) -> Result<Arc<Thread>> {
@@ -1194,12 +1213,22 @@ fn version(&self, data: UserSlice) -> Result {
data.writer().write(&BinderVersion::current())
}
- pub(crate) fn register_thread(&self) -> bool {
- self.inner.lock().register_thread()
- }
-
fn remove_thread(&self, thread: Arc<Thread>) {
- self.inner.lock().threads.remove(&thread.id);
+ {
+ let mut inner = self.inner.lock();
+ if inner.threads.remove(&thread.id).is_some() && thread.is_started_looper() {
+ inner.started_thread_count = match inner.started_thread_count.checked_sub(1) {
+ Some(val) => val,
+ None => {
+ pr_warn_ratelimited!(
+ "started_thread_count underflow in pid: {}.\n",
+ self.pid_in_current_ns()
+ );
+ 0
+ }
+ };
+ }
+ }
thread.release();
}
@@ -1207,6 +1236,22 @@ fn set_max_threads(&self, max: u32) {
self.inner.lock().max_threads = max;
}
+ fn set_idle_timeout(&self, timeout: i64) -> Result {
+ if timeout < 0 {
+ return Err(EINVAL);
+ }
+ let timeout_duration = Delta::from_millis(timeout);
+ let mut inner = self.inner.lock();
+ inner.idle_timeout = timeout_duration;
+ if timeout_duration.is_zero() && inner.has_deferred_timeout {
+ if let Some(thread) = inner.ready_threads.iter().next() {
+ thread.clear_deferred_timeout();
+ }
+ inner.has_deferred_timeout = false;
+ }
+ Ok(())
+ }
+
fn set_oneway_spam_detection_enabled(&self, enabled: u32) {
self.inner.lock().oneway_spam_detection_enabled = enabled != 0;
}
@@ -1678,6 +1723,7 @@ fn ioctl_write_only(
let thread = this.get_current_thread()?;
match cmd {
uapi::BINDER_SET_MAX_THREADS => this.set_max_threads(reader.read()?),
+ uapi::BINDER_SET_IDLE_TIMEOUT => this.set_idle_timeout(reader.read()?)?,
uapi::BINDER_THREAD_EXIT => this.remove_thread(thread),
uapi::BINDER_SET_CONTEXT_MGR => this.set_as_manager(None, &thread)?,
uapi::BINDER_SET_CONTEXT_MGR_EXT => {
@@ -1833,13 +1879,22 @@ pub(crate) fn poll(
/// The destructor of this type will unregister the thread from the list of ready threads.
pub(crate) struct Registration<'a> {
thread: &'a Arc<Thread>,
+ unregistered: bool,
}
impl<'a> Registration<'a> {
- fn new(thread: &'a Arc<Thread>, guard: &mut Guard<'_, ProcessInner, SpinLockBackend>) -> Self {
+ fn new(
+ thread: &'a Arc<Thread>,
+ guard: &mut Guard<'_, ProcessInner, SpinLockBackend>,
+ deferred: &mut Option<Arc<Thread>>,
+ ) -> Self {
assert!(core::ptr::eq(&thread.process.inner, guard.lock_ref()));
// INVARIANT: We are pushing this thread to the right `ready_threads` list.
if let Ok(list_arc) = ListArc::try_from_arc(thread.clone()) {
+ if guard.has_deferred_timeout {
+ *deferred = guard.ready_threads.iter().next().map(Arc::from);
+ guard.has_deferred_timeout = false;
+ }
guard.ready_threads.push_front(list_arc);
} else {
// It is an error to hit this branch, and it should not be reachable. We try to do
@@ -1847,17 +1902,52 @@ fn new(thread: &'a Arc<Thread>, guard: &mut Guard<'_, ProcessInner, SpinLockBack
// question will sleep forever.
pr_err_ratelimited!("Same thread registered with `ready_threads` twice.\n");
}
- Self { thread }
+ Self {
+ thread,
+ unregistered: false,
+ }
+ }
+
+ pub(crate) fn maybe_unregister(
+ &mut self,
+ guard: &mut Guard<'_, ProcessInner, SpinLockBackend>,
+ ) -> bool {
+ assert!(core::ptr::eq(&self.thread.process.inner, guard.lock_ref()));
+ if self.unregistered {
+ return true;
+ }
+ // SAFETY: We asserted above that `guard` is the lock for `self.thread.process.inner`, and
+ // the thread has the invariant that we never push it to any other linked list than the
+ // `ready_threads` list of its parent process. Therefore, the thread is either in that
+ // list, or in no list.
+ let Some(list_arc) = (unsafe { guard.ready_threads.remove(self.thread) }) else {
+ self.unregistered = true;
+ return true;
+ };
+ if guard.ready_threads.is_empty() {
+ guard.ready_threads.push_front(list_arc);
+ guard.has_deferred_timeout = true;
+ return false;
+ }
+ self.unregistered = true;
+ true
}
}
impl Drop for Registration<'_> {
fn drop(&mut self) {
+ if self.unregistered {
+ return;
+ }
let mut inner = self.thread.process.inner.lock();
// SAFETY: The thread has the invariant that we never push it to any other linked list than
// the `ready_threads` list of its parent process. Therefore, the thread is either in that
// list, or in no list.
unsafe { inner.ready_threads.remove(self.thread) };
+ if inner.ready_threads.is_empty() {
+ inner.has_deferred_timeout = false;
+ }
+ self.unregistered = true;
}
}
@@ -1877,5 +1967,5 @@ fn drop(&mut self) {
pub(crate) enum GetWorkOrRegister<'a> {
Work(DLArc<dyn DeliverToRead>),
- Register(Registration<'a>),
+ Register(Registration<'a>, Delta),
}
diff --git a/drivers/android/binder/thread.rs b/drivers/android/binder/thread.rs
index 8efda6e9ded1..b6318b276b07 100644
--- a/drivers/android/binder/thread.rs
+++ b/drivers/android/binder/thread.rs
@@ -17,7 +17,7 @@
seq_file::SeqFile,
seq_print,
sync::atomic::{ordering::Relaxed, Atomic},
- sync::{aref::ARef, Arc, CondVar, SpinLock},
+ sync::{aref::ARef, Arc, CondVar, CondVarTimeoutResult, SpinLock},
task::Task,
uaccess::{UserPtr, UserSlice, UserSliceReader},
uapi,
@@ -252,6 +252,9 @@ struct InnerThread {
/// Determines whether the looper should return.
looper_need_return: bool,
+ /// Determines whether an expired idle timeout was deferred while sole ready thread.
+ deferred_timeout: bool,
+
/// Determines if thread is dead.
is_dead: bool,
@@ -289,6 +292,7 @@ pub enum LooperFlag {
Waiting = bit_u32(4),
WaitingProc = bit_u32(5),
Poll = bit_u32(6),
+ Started = bit_u32(7),
}
);
@@ -302,6 +306,7 @@ fn next_err_id() -> u32 {
Ok(Self {
looper_flags: LooperFlags::default(),
looper_need_return: false,
+ deferred_timeout: false,
is_dead: false,
process_work_list: false,
reply_work: ThreadError::try_new(pid)?,
@@ -400,7 +405,9 @@ fn looper_enter(&mut self) {
fn looper_register(&mut self, valid: bool) {
self.looper_flags |= LooperFlag::Registered;
- if !valid || self.looper_flags.contains(LooperFlag::Entered) {
+ if valid {
+ self.looper_flags |= LooperFlag::Started;
+ } else {
self.looper_flags |= LooperFlag::Invalid;
}
}
@@ -415,6 +422,19 @@ fn is_looper(&self) -> bool {
.contains_any(LooperFlag::Entered | LooperFlag::Registered)
}
+ fn is_registered_looper(&self) -> bool {
+ self.looper_flags.contains(LooperFlag::Registered)
+ && !self.looper_flags.contains(LooperFlag::Invalid)
+ }
+
+ /// Ensures we don't time out the main thread as this would lead to needless wakeups.
+ fn can_timeout(&self) -> bool {
+ self.is_registered_looper()
+ && !self
+ .looper_flags
+ .contains_any(LooperFlag::Entered | LooperFlag::Exited | LooperFlag::Poll)
+ }
+
/// Determines whether the thread should attempt to fetch work items from the process queue.
/// This is generally case when the thread is registered as a looper and not part of a
/// transaction stack. But if there is local work, we want to return to userspace before we
@@ -625,31 +645,76 @@ fn get_work(self: &Arc<Self>, wait: bool) -> Result<Option<DLArc<dyn DeliverToRe
}
// Get work from the process queue. If none is available, atomically register as ready.
- let reg = match self
+ let (mut reg, idle_timeout) = match self
.process
.get_work_or_register(self, thread_has_deferred_work)
{
GetWorkOrRegister::Work(work) => return Ok(Some(work)),
- GetWorkOrRegister::Register(reg) => reg,
+ GetWorkOrRegister::Register(reg, idle_timeout) => (reg, idle_timeout),
};
+ // Updated on spurious wakeup with remaining timeout.
+ let mut timeout = if idle_timeout.is_zero() {
+ 0
+ } else {
+ idle_timeout.to_jiffies_timeout().as_jiffies_unsigned() as kernel::time::Jiffies
+ };
let mut inner = self.inner.lock();
loop {
if let Some(work) = inner.pop_work() {
+ inner.looper_flags &= !(LooperFlag::Waiting | LooperFlag::WaitingProc);
return Ok(Some(work));
}
inner.looper_flags |= LooperFlag::Waiting | LooperFlag::WaitingProc;
- let signal_pending = self.work_condvar.wait_interruptible_freezable(&mut inner);
- inner.looper_flags &= !(LooperFlag::Waiting | LooperFlag::WaitingProc);
+ let timeout_result = if inner.can_timeout() && timeout != 0 {
+ self.work_condvar
+ .wait_interruptible_freezable_timeout(&mut inner, timeout)
+ } else {
+ let signal_pending = self.work_condvar.wait_interruptible_freezable(&mut inner);
+ if signal_pending {
+ CondVarTimeoutResult::Signal { jiffies: 0 }
+ } else {
+ CondVarTimeoutResult::Woken { jiffies: 0 }
+ }
+ };
+ let deferred_timeout = inner.deferred_timeout;
+ inner.deferred_timeout = false;
+
+ let signal_pending = matches!(timeout_result, CondVarTimeoutResult::Signal { .. });
+ let timed_out = matches!(timeout_result, CondVarTimeoutResult::Timeout)
+ || (deferred_timeout && !signal_pending);
+
+ if timed_out && !signal_pending && !inner.looper_need_return && !inner.process_work_list
+ {
+ drop(inner);
+ let mut inner_process = self.process.inner.lock();
+ inner = self.inner.lock();
+ if !inner.looper_need_return && inner_process.idle_timeout().is_zero() {
+ timeout = 0;
+ drop(inner_process);
+ continue;
+ }
+ if !inner.looper_need_return
+ && !inner.process_work_list
+ && !reg.maybe_unregister(&mut inner_process)
+ {
+ timeout = 0;
+ inner.deferred_timeout = true;
+ drop(inner_process);
+ continue;
+ }
+ drop(inner_process);
+ }
- if signal_pending || inner.looper_need_return {
+ if signal_pending || timed_out || inner.looper_need_return {
// We need to return now.
//
// We need to pull the thread off the list of ready threads (by dropping `reg`),
// then check the state again after it's off the list to ensure that something was
// not queued in the meantime. If something has been queued (or if there is
// deferred work), we just return it (instead of the error).
+ inner.looper_flags &= !(LooperFlag::Waiting | LooperFlag::WaitingProc);
drop(inner);
drop(reg);
@@ -658,13 +723,30 @@ fn get_work(self: &Arc<Self>, wait: bool) -> Result<Option<DLArc<dyn DeliverToRe
let res = match inner.pop_work() {
Some(work) => Ok(Some(work)),
None if signal_pending => Err(EINTR),
+ None if timed_out && !inner.looper_need_return => Err(ETIMEDOUT),
None => Ok(None),
};
return res;
}
+
+ // Update timeout on spurious wake.
+ if let CondVarTimeoutResult::Woken { jiffies } = timeout_result {
+ timeout = jiffies;
+ }
+ }
+ }
+
+ pub(crate) fn notify_if_deferred_timeout(&self) {
+ let should_notify = self.inner.lock().deferred_timeout;
+ if should_notify {
+ self.work_condvar.notify_one();
}
}
+ pub(crate) fn clear_deferred_timeout(&self) {
+ self.inner.lock().deferred_timeout = false;
+ }
+
/// Push the provided work item to be delivered to user space via this thread.
///
/// Returns whether the item was successfully pushed. This can only fail if the thread is dead.
@@ -1567,8 +1649,10 @@ fn write(self: &Arc<Self>, req: &mut BinderWriteRead) -> Result {
BC_CLEAR_DEATH_NOTIFICATION => self.process.clear_death(&mut reader, self)?,
BC_DEAD_BINDER_DONE => self.process.dead_binder_done(reader.read()?, self),
BC_REGISTER_LOOPER => {
- let valid = self.process.register_thread();
- self.inner.lock().looper_register(valid);
+ let mut inner_process = self.process.inner.lock();
+ let mut inner = self.inner.lock();
+ let valid = !inner.is_looper() && inner_process.register_thread();
+ inner.looper_register(valid);
}
BC_ENTER_LOOPER => self.inner.lock().looper_enter(),
BC_EXIT_LOOPER => self.inner.lock().looper_exit(),
@@ -1625,6 +1709,7 @@ fn read(self: &Arc<Self>, req: &mut BinderWriteRead, wait: bool) -> Result {
// Loop doing work while there is room in the buffer.
let initial_len = writer.len();
+ let mut timed_out = false;
while writer.len() >= size_of::<uapi::binder_transaction_data_secctx>() + 4 {
match getter(self, wait && initial_len == writer.len()) {
Ok(Some(work)) => match work.into_arc().do_work(self, &mut writer) {
@@ -1638,6 +1723,13 @@ fn read(self: &Arc<Self>, req: &mut BinderWriteRead, wait: bool) -> Result {
break;
}
Err(err) => {
+ // Timeout isn't an error for the caller so swallow it here and instead
+ // write BR_FINISHED.
+ if err == ETIMEDOUT {
+ timed_out = true;
+ writer.write_code(BR_FINISHED)?;
+ break;
+ }
// Propagate the error if we haven't written anything else.
if err != EINTR && err != EAGAIN {
pr_warn_ratelimited!("Failure in work getter: {:?}\n", err);
@@ -1654,7 +1746,7 @@ fn read(self: &Arc<Self>, req: &mut BinderWriteRead, wait: bool) -> Result {
req.read_consumed += read_len - writer.len() as u64;
// Write BR_SPAWN_LOOPER if the process needs more threads for its pool.
- if has_noop_placeholder && in_pool && self.process.needs_thread() {
+ if has_noop_placeholder && in_pool && !timed_out && self.process.needs_thread() {
let mut writer = UserSlice::new(
UserPtr::from_addr(req.read_buffer as usize),
req.read_size as usize,
@@ -1662,6 +1754,7 @@ fn read(self: &Arc<Self>, req: &mut BinderWriteRead, wait: bool) -> Result {
.writer();
writer.write(&BR_SPAWN_LOOPER)?;
}
+
Ok(())
}
@@ -1708,6 +1801,10 @@ pub(crate) fn write_read(self: &Arc<Self>, data: UserSlice, wait: bool) -> Resul
ret
}
+ pub(crate) fn is_started_looper(&self) -> bool {
+ self.inner.lock().looper_flags.contains(LooperFlag::Started)
+ }
+
pub(crate) fn poll(&self) -> Result<(bool, u32)> {
let mut inner = self.inner.lock();
Ok((inner.should_use_process_work_queue(), inner.poll()))
diff --git a/include/uapi/linux/android/binder.h b/include/uapi/linux/android/binder.h
index 96e5b0184a1b..c205cfb9a515 100644
--- a/include/uapi/linux/android/binder.h
+++ b/include/uapi/linux/android/binder.h
@@ -259,6 +259,14 @@ struct binder_extended_error {
enum {
BINDER_WRITE_READ = _IOWR('b', 1, struct binder_write_read),
+ /*
+ * Configure the per-process idle timeout in milliseconds for registered
+ * looper threads (BC_REGISTER_LOOPER). A value of 0 disables spin-down
+ * (default); negative values return -EINVAL. Very large values saturate
+ * to the kernel's maximum timeout. Non-zero updates apply to subsequent
+ * waits; resetting to 0 also cancels pending spin-down for waiting and
+ * deferred threads.
+ */
BINDER_SET_IDLE_TIMEOUT = _IOW('b', 3, __s64),
BINDER_SET_MAX_THREADS = _IOW('b', 5, __u32),
BINDER_SET_IDLE_PRIORITY = _IOW('b', 6, __s32),
@@ -438,8 +446,10 @@ enum binder_driver_return_protocol {
BR_FINISHED = _IO('r', 14),
/*
- * not currently supported
- * stop threadpool thread
+ * No parameters. The driver has determined that a registered looper
+ * thread has been idle past the timeout configured via
+ * BINDER_SET_IDLE_TIMEOUT and should exit its looper loop via
+ * BC_EXIT_LOOPER and BINDER_THREAD_EXIT.
*/
BR_DEAD_BINDER = _IOR('r', 15, binder_uintptr_t),
--
2.56.1.915.g69d5ec7298-goog