From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.214.197 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796344388; b=iWLElnKPoSlvlInpjcDA9mOiuCZw7ksUS3EDOjX4lddb98JayS3RG8jaybCnbiW58RgI n0uK5y2wTcktMIGtPIoOz2bo85dyfeXirFy0pgYhqCMBk/CHKNMYKl7QnonuNYHuWDA7g Q2zSpAV4pPofe3ppcqIFR+nLtqlIULzqEVyM3HrBPTqGfY7z5UZGTjYzg9T2uLKmgeMvS c3QuNGOrgv3SuErKOdxJ64XCUMD9+YDqZWGLC66h2EzCysQdaS1SiuvYFBQaTuiKb9abp P5ICVD8nGRsC8ZXLE0F2xvff9KhiwOvseop/bQ6SpkIqWmkOrB1LRip0SlSJS8BCckQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796344388; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Developer-Key:X-Developer-Signature: X-Mailer:Message-ID:Subject:From:To:Cc:Content-Type; bh=y9ZEofVPjochR900ziI0NLsviZN3P608d70P7tkVNHY=; b=T1c+HNYvbEU9Pd43emPk9tIeM3N3LdP/wo1G+hvBfq6+yh3GmX0/WsoUuwVGyqRFKhh9 x2+dFXON2RR7dyV7gzwxXtHRvXoWlucsv+bBp1xWBHhg12ORS9Z8DadWfn+vPzu2LYOp5 QTg3xpd804bZrytVTqqIBzeRAnuLf9+YXTn6KNkRR/MJRRTGwfs8BZ2yhxNFb1oNbP9Oi EhN+4fZsJ8a8CMgxdcTCbr0/P3Pjp7QjYU0GomrRSb88yQxoiLoVfPZ9K/RvPTzPPJl/0 vJBTvVCvDYyYj881dF1lisFVQBvQjGr+Ei6ufQNL3+27c9YA5lyZRE07314mZbKTWOQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--grahalt.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=XfnKo17g; arc=none smtp.remote-ip=209.85.214.197 Received: from mail-pl1-f197.google.com (mail-pl1-f197.google.com [209.85.214.197]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 102A5606A687 for ; Fri, 4 Dec 2026 00:33:07 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 102A5606A687 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--grahalt.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=XfnKo17g Received: by mail-pl1-f197.google.com with SMTP id d9443c01a7336-2f074b87307so3761825ad.2 for ; Thu, 03 Dec 2026 16:33:07 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1796344387; x=1796949187; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=y9ZEofVPjochR900ziI0NLsviZN3P608d70P7tkVNHY=; b=XfnKo17gXYNE8eilS2KsPBgeUWuUSyKsBUw0jGM+aq95JdllsiwQpkM1D/hiKszNAq DdPga6xjKu9kdnb40XhjUihBLavbKNYdtRlLrkloXDV9SA5FcJqc169Bocmc0Ll0IT10 yM9ePWWrmsmgYgOfTbz8+SOt8/hujiA5o7yaeHCIobR5Iq+dRpepMWS3FYUIDOww2e8E h4ZoRKY0exOlG9kL+9eAfShOoOrEWaCv7m2f0D9R7lDZcK5IFBlrAdXajlEevjAybrzo TyYhxiwX0Q8Vx9jEGrnxHPCYfsE0i8mx0Nvm5lxoeLo6pa1J9DKslgcE8WdxCLpFpyfk QjSw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796344387; x=1796949187; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=y9ZEofVPjochR900ziI0NLsviZN3P608d70P7tkVNHY=; b=cLMok1yrpuh8iOCZT+F23Rxs/dqSnb+rStCBN+tgasZ1ysTXpvzPaJvReb6N++vi2M XxgX4XZfrNALbl3tBDuM2H1R8mJSoNEwep2XR5/xNGbCoTBxbsoTr6+lsSwknQts/yBz i05i3lKvi9wekWXIA6psPLlJcKWHJImq771ubEys1XcLyIDIzvdNfCNzL10Hfb8ee0xu c5v9Qsi4WfNNVHst1TJzcpm5WQN7fgFCnGWwwCWXP5+Sc/7p/EWQm9CjNGW22wzePvNL R6m1gxVrbMJZOZETIEaqcX5v2kjI3O8MKr7ioMhr62apQR09+hCUclZOzaCVeZ94xTTC FG4g== X-Forwarded-Encrypted: i=1; AL+hErFkF+q1PYjVq8YKcT2yqcYGlvx+sq1Y3uySB9S6rniwtGF0II2/+n7DrbkLZU58n6efbiWYWRq4K1Iuj+k=@vger.kernel.org X-Gm-Message-State: APuU4Z9tS8cBmZYJolatVZQiwVqj2sKbkCtY4jNBdTh8mMKu7uwKIts8 J7kVBKJMQUSodztNGmgJlEXIH+HkZqV2q5sqCVqUDCzroIB13lyuAk7j7AzNvfOGYzT2EB9u/MM JA/dNKWxeVA== X-Received: from plbjk4.prod.google.com ([2002:a17:903:3304:b0:2ed:e740:3702]) (user=grahalt job=prod-delivery.src-stubby-dispatcher) by 2002:a17:902:f549:b0:2e8:9820:80cf with SMTP id d9443c01a7336-2f1ba22372bmr2240075ad.58.1796344386970; Thu, 03 Dec 2026 16:33:06 -0800 (PST) Date: Fri, 04 Dec 2026 00:32:47 +0000 In-Reply-To: <20261204-rust-binder-thread-spindown-v1-0-8702c42d4437@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261204-rust-binder-thread-spindown-v1-0-8702c42d4437@google.com> X-Developer-Key: i=grahalt@google.com; a=ed25519; pk=Fdl8UB2iAFT3+RcdOulskhAYycOow7vcBsXiopOEuZQ= X-Developer-Signature: v=1; a=ed25519-sha256; t=1796344384; l=23771; i=grahalt@google.com; s=20261202; h=from:subject:message-id; bh=9MnNFQLQk1M2e6HwlSsv/12DFr5MTfrvLCQA4FluaoQ=; b=lYWWfzeGXFwKtnP8cULQufhFZg8Q2ilt5pg3YRZPxzU8kDEEOKDT97NmV7uJi/kvAZ7893gyx yuL3E8k5ZOHDUhCxoFuBaXgHidBzh8MH/1MLInmLnAlP9RXbTBhhdfM X-Mailer: b4 0.14.3 Message-ID: <20261204-rust-binder-thread-spindown-v1-2-8702c42d4437@google.com> Subject: [PATCH 2/4] rust_binder: add support for thread timeout From: Nicholas Giunta To: Greg Kroah-Hartman , Carlos Llamas , Alice Ryhl , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Christian Brauner , Boqun Feng , Gary Guo , Miguel Ojeda , Shuah Khan Cc: Lyude Paul , Daniel Almeida , "=?utf-8?q?Onur_=C3=96zkan?=" , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , Danilo Krummrich , Tamir Duberstein , Alexandre Courbot , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-api@vger.kernel.org, Nicholas Giunta Content-Type: text/plain; charset="utf-8" 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 --- 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>> } } - 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> { @@ -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) { - 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, + unregistered: bool, } impl<'a> Registration<'a> { - fn new(thread: &'a Arc, guard: &mut Guard<'_, ProcessInner, SpinLockBackend>) -> Self { + fn new( + thread: &'a Arc, + guard: &mut Guard<'_, ProcessInner, SpinLockBackend>, + deferred: &mut Option>, + ) -> 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, 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), - 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, wait: bool) -> Result 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, wait: bool) -> Result 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, 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, 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::() + 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, 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, 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, req: &mut BinderWriteRead, wait: bool) -> Result { .writer(); writer.write(&BR_SPAWN_LOOPER)?; } + Ok(()) } @@ -1708,6 +1801,10 @@ pub(crate) fn write_read(self: &Arc, 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