1 // SPDX-License-Identifier: GPL-2.0 2 3 // Copyright (C) 2025 Google LLC. 4 5 //! This module defines the `Process` type, which represents a process using a particular binder 6 //! context. 7 //! 8 //! The `Process` object keeps track of all of the resources that this process owns in the binder 9 //! context. 10 //! 11 //! There is one `Process` object for each binder fd that a process has opened, so processes using 12 //! several binder contexts have several `Process` objects. This ensures that the contexts are 13 //! fully separated. 14 15 use core::mem::take; 16 17 use kernel::{ 18 bindings, 19 cred::Credential, 20 error::Error, 21 fs::file::{self, File}, 22 id_pool::IdPool, 23 list::{List, ListArc, ListArcField, ListLinks}, 24 mm, 25 prelude::*, 26 rbtree::{self, RBTree, RBTreeNode, RBTreeNodeReservation}, 27 seq_file::SeqFile, 28 seq_print, 29 sync::poll::PollTable, 30 sync::{ 31 aref::ARef, 32 lock::{spinlock::SpinLockBackend, Guard}, 33 Arc, ArcBorrow, CondVar, CondVarTimeoutResult, SpinLock, UniqueArc, 34 }, 35 task::{Pid, Task}, 36 uaccess::{UserSlice, UserSliceReader}, 37 uapi, 38 workqueue::{self, Work}, 39 }; 40 41 use crate::{ 42 allocation::{Allocation, AllocationInfo, NewAllocation}, 43 context::Context, 44 defs::*, 45 error::{BinderError, BinderResult}, 46 node::{CouldNotDeliverCriticalIncrement, CritIncrWrapper, Node, NodeDeath, NodeRef}, 47 page_range::ShrinkablePageRange, 48 range_alloc::{RangeAllocator, ReserveNew, ReserveNewArgs}, 49 stats::BinderStats, 50 thread::{PushWorkRes, Thread}, 51 transaction::TransactionInfo, 52 BinderfsProcFile, DArc, DLArc, DTRWrap, DeliverToRead, 53 }; 54 55 #[path = "freeze.rs"] 56 mod freeze; 57 use self::freeze::{FreezeCookie, FreezeListener}; 58 59 struct Mapping { 60 address: usize, 61 alloc: RangeAllocator<AllocationInfo>, 62 } 63 64 impl Mapping { 65 fn new(address: usize, size: usize) -> Self { 66 Self { 67 address, 68 alloc: RangeAllocator::new(size), 69 } 70 } 71 } 72 73 // bitflags for defer_work. 74 const PROC_DEFER_FLUSH: u8 = 1; 75 const PROC_DEFER_RELEASE: u8 = 2; 76 77 #[derive(Copy, Clone)] 78 pub(crate) enum IsFrozen { 79 Yes, 80 No, 81 InProgress, 82 } 83 84 impl IsFrozen { 85 /// Whether incoming transactions should be rejected due to freeze. 86 pub(crate) fn is_frozen(self) -> bool { 87 match self { 88 IsFrozen::Yes => true, 89 IsFrozen::No => false, 90 IsFrozen::InProgress => true, 91 } 92 } 93 94 /// Whether freeze notifications consider this process frozen. 95 pub(crate) fn is_fully_frozen(self) -> bool { 96 match self { 97 IsFrozen::Yes => true, 98 IsFrozen::No => false, 99 IsFrozen::InProgress => false, 100 } 101 } 102 } 103 104 /// The fields of `Process` protected by the spinlock. 105 pub(crate) struct ProcessInner { 106 is_manager: bool, 107 pub(crate) is_dead: bool, 108 threads: RBTree<i32, Arc<Thread>>, 109 /// INVARIANT: Threads pushed to this list must be owned by this process. 110 ready_threads: List<Thread>, 111 nodes: RBTree<u64, DArc<Node>>, 112 mapping: Option<Mapping>, 113 work: List<DTRWrap<dyn DeliverToRead>>, 114 delivered_deaths: List<DTRWrap<NodeDeath>, 2>, 115 116 /// The number of requested threads that haven't registered yet. 117 requested_thread_count: u32, 118 /// The maximum number of threads used by the process thread pool. 119 max_threads: u32, 120 /// The number of threads the started and registered with the thread pool. 121 started_thread_count: u32, 122 123 /// Bitmap of deferred work to do. 124 defer_work: u8, 125 126 /// Number of transactions to be transmitted before processes in freeze_wait 127 /// are woken up. 128 outstanding_txns: u32, 129 /// Process is frozen and unable to service binder transactions. 130 pub(crate) is_frozen: IsFrozen, 131 /// Process received sync transactions since last frozen. 132 pub(crate) sync_recv: bool, 133 /// Process received async transactions since last frozen. 134 pub(crate) async_recv: bool, 135 pub(crate) binderfs_file: Option<BinderfsProcFile>, 136 /// Check for oneway spam 137 oneway_spam_detection_enabled: bool, 138 } 139 140 impl ProcessInner { 141 fn new() -> Self { 142 Self { 143 is_manager: false, 144 is_dead: false, 145 threads: RBTree::new(), 146 ready_threads: List::new(), 147 mapping: None, 148 nodes: RBTree::new(), 149 work: List::new(), 150 delivered_deaths: List::new(), 151 requested_thread_count: 0, 152 max_threads: 0, 153 started_thread_count: 0, 154 defer_work: 0, 155 outstanding_txns: 0, 156 is_frozen: IsFrozen::No, 157 sync_recv: false, 158 async_recv: false, 159 binderfs_file: None, 160 oneway_spam_detection_enabled: false, 161 } 162 } 163 164 /// Schedule the work item for execution on this process. 165 /// 166 /// If any threads are ready for work, then the work item is given directly to that thread and 167 /// it is woken up. Otherwise, it is pushed to the process work list. 168 /// 169 /// This call can fail only if the process is dead. In this case, the work item is returned to 170 /// the caller so that the caller can drop it after releasing the inner process lock. This is 171 /// necessary since the destructor of `Transaction` will take locks that can't necessarily be 172 /// taken while holding the inner process lock. 173 pub(crate) fn push_work( 174 &mut self, 175 work: DLArc<dyn DeliverToRead>, 176 ) -> Result<(), (BinderError, DLArc<dyn DeliverToRead>)> { 177 // Try to find a ready thread to which to push the work. 178 if let Some(thread) = self.ready_threads.pop_front() { 179 // Push to thread while holding state lock. This prevents the thread from giving up 180 // (for example, because of a signal) when we're about to deliver work. 181 match thread.push_work(work) { 182 PushWorkRes::Ok => Ok(()), 183 PushWorkRes::FailedDead(work) => Err((BinderError::new_dead(), work)), 184 } 185 } else if self.is_dead { 186 Err((BinderError::new_dead(), work)) 187 } else { 188 let sync = work.should_sync_wakeup(); 189 190 // Didn't find a thread waiting for proc work; this can happen 191 // in two scenarios: 192 // 1. All threads are busy handling transactions 193 // In that case, one of those threads should call back into 194 // the kernel driver soon and pick up this work. 195 // 2. Threads are using the (e)poll interface, in which case 196 // they may be blocked on the waitqueue without having been 197 // added to waiting_threads. For this case, we just iterate 198 // over all threads not handling transaction work, and 199 // wake them all up. We wake all because we don't know whether 200 // a thread that called into (e)poll is handling non-binder 201 // work currently. 202 self.work.push_back(work); 203 204 // Wake up polling threads, if any. 205 for thread in self.threads.values() { 206 thread.notify_if_poll_ready(sync); 207 } 208 209 Ok(()) 210 } 211 } 212 213 pub(crate) fn remove_node(&mut self, ptr: u64) { 214 self.nodes.remove(&ptr); 215 } 216 217 /// Updates the reference count on the given node. 218 pub(crate) fn update_node_refcount( 219 &mut self, 220 node: &DArc<Node>, 221 inc: bool, 222 strong: bool, 223 count: usize, 224 othread: Option<&Thread>, 225 ) { 226 let push = node.update_refcount_locked(inc, strong, count, self); 227 228 // If we decided that we need to push work, push either to the process or to a thread if 229 // one is specified. 230 if let Some(node) = push { 231 if let Some(thread) = othread { 232 thread.push_work_deferred(node); 233 } else { 234 let _ = self.push_work(node); 235 // Nothing to do: `push_work` may fail if the process is dead, but that's ok as in 236 // that case, it doesn't care about the notification. 237 } 238 } 239 } 240 241 pub(crate) fn new_node_ref( 242 &mut self, 243 node: DArc<Node>, 244 strong: bool, 245 thread: Option<&Thread>, 246 ) -> NodeRef { 247 self.update_node_refcount(&node, true, strong, 1, thread); 248 let strong_count = if strong { 1 } else { 0 }; 249 NodeRef::new(node, strong_count, 1 - strong_count) 250 } 251 252 pub(crate) fn new_node_ref_with_thread( 253 &mut self, 254 node: DArc<Node>, 255 strong: bool, 256 thread: &Thread, 257 wrapper: Option<CritIncrWrapper>, 258 ) -> Result<NodeRef, CouldNotDeliverCriticalIncrement> { 259 let push = match wrapper { 260 None => node 261 .incr_refcount_allow_zero2one(strong, self)? 262 .map(|node| node as DLArc<dyn DeliverToRead>), 263 Some(wrapper) => node.incr_refcount_allow_zero2one_with_wrapper(strong, wrapper, self), 264 }; 265 if let Some(node) = push { 266 thread.push_work_deferred(node); 267 } 268 let strong_count = if strong { 1 } else { 0 }; 269 Ok(NodeRef::new(node, strong_count, 1 - strong_count)) 270 } 271 272 /// Returns an existing node with the given pointer and cookie, if one exists. 273 /// 274 /// Returns an error if a node with the given pointer but a different cookie exists. 275 fn get_existing_node(&self, ptr: u64, cookie: u64) -> Result<Option<DArc<Node>>> { 276 match self.nodes.get(&ptr) { 277 None => Ok(None), 278 Some(node) => { 279 let (_, node_cookie) = node.get_id(); 280 if node_cookie == cookie { 281 Ok(Some(node.clone())) 282 } else { 283 Err(EINVAL) 284 } 285 } 286 } 287 } 288 289 fn register_thread(&mut self) -> bool { 290 if self.requested_thread_count == 0 { 291 return false; 292 } 293 294 self.requested_thread_count -= 1; 295 self.started_thread_count += 1; 296 true 297 } 298 299 /// Finds a delivered death notification with the given cookie, removes it from the thread's 300 /// delivered list, and returns it. 301 fn pull_delivered_death(&mut self, cookie: u64) -> Option<DArc<NodeDeath>> { 302 let mut cursor = self.delivered_deaths.cursor_front(); 303 while let Some(next) = cursor.peek_next() { 304 if next.cookie == cookie { 305 return Some(next.remove().into_arc()); 306 } 307 cursor.move_next(); 308 } 309 None 310 } 311 312 pub(crate) fn death_delivered(&mut self, death: DArc<NodeDeath>) { 313 if let Some(death) = ListArc::try_from_arc_or_drop(death) { 314 self.delivered_deaths.push_back(death); 315 } else { 316 pr_warn!("Notification added to `delivered_deaths` twice."); 317 } 318 } 319 320 pub(crate) fn add_outstanding_txn(&mut self) { 321 self.outstanding_txns += 1; 322 } 323 324 fn txns_pending_locked(&self) -> bool { 325 if self.outstanding_txns > 0 { 326 return true; 327 } 328 for thread in self.threads.values() { 329 if thread.has_current_transaction() { 330 return true; 331 } 332 } 333 false 334 } 335 } 336 337 /// Used to keep track of a node that this process has a handle to. 338 #[pin_data] 339 pub(crate) struct NodeRefInfo { 340 debug_id: usize, 341 /// The refcount that this process owns to the node. 342 node_ref: ListArcField<NodeRef, { Self::LIST_PROC }>, 343 death: ListArcField<Option<DArc<NodeDeath>>, { Self::LIST_PROC }>, 344 /// Cookie of the active freeze listener for this node. 345 freeze: ListArcField<Option<FreezeCookie>, { Self::LIST_PROC }>, 346 /// Used to store this `NodeRefInfo` in the node's `refs` list. 347 #[pin] 348 links: ListLinks<{ Self::LIST_NODE }>, 349 /// The handle for this `NodeRefInfo`. 350 handle: u32, 351 /// The process that has a handle to the node. 352 pub(crate) process: Arc<Process>, 353 } 354 355 impl NodeRefInfo { 356 /// The id used for the `Node::refs` list. 357 pub(crate) const LIST_NODE: u64 = 0x2da16350fb724a10; 358 /// The id used for the `ListArc` in `ProcessNodeRefs`. 359 const LIST_PROC: u64 = 0xd703a5263dcc8650; 360 361 fn new(node_ref: NodeRef, handle: u32, process: Arc<Process>) -> impl PinInit<Self> { 362 pin_init!(Self { 363 debug_id: super::next_debug_id(), 364 node_ref: ListArcField::new(node_ref), 365 death: ListArcField::new(None), 366 freeze: ListArcField::new(None), 367 links <- ListLinks::new(), 368 handle, 369 process, 370 }) 371 } 372 373 kernel::list::define_list_arc_field_getter! { 374 pub(crate) fn death(&mut self<{Self::LIST_PROC}>) -> &mut Option<DArc<NodeDeath>> { death } 375 pub(crate) fn freeze(&mut self<{Self::LIST_PROC}>) -> &mut Option<FreezeCookie> { freeze } 376 pub(crate) fn node_ref(&mut self<{Self::LIST_PROC}>) -> &mut NodeRef { node_ref } 377 pub(crate) fn node_ref2(&self<{Self::LIST_PROC}>) -> &NodeRef { node_ref } 378 } 379 } 380 381 kernel::list::impl_list_arc_safe! { 382 impl ListArcSafe<{Self::LIST_NODE}> for NodeRefInfo { untracked; } 383 impl ListArcSafe<{Self::LIST_PROC}> for NodeRefInfo { untracked; } 384 } 385 kernel::list::impl_list_item! { 386 impl ListItem<{Self::LIST_NODE}> for NodeRefInfo { 387 using ListLinks { self.links }; 388 } 389 } 390 391 /// Keeps track of references this process has to nodes owned by other processes. 392 /// 393 /// TODO: Currently, the rbtree requires two allocations per node reference, and two tree 394 /// traversals to look up a node by `Node::global_id`. Once the rbtree is more powerful, these 395 /// extra costs should be eliminated. 396 struct ProcessNodeRefs { 397 /// Used to look up nodes using the 32-bit id that this process knows it by. 398 by_handle: RBTree<u32, ListArc<NodeRefInfo, { NodeRefInfo::LIST_PROC }>>, 399 /// Used to quickly find unused ids in `by_handle`. 400 handle_is_present: IdPool, 401 /// Used to look up nodes without knowing their local 32-bit id. The usize is the address of 402 /// the underlying `Node` struct as returned by `Node::global_id`. 403 by_node: RBTree<usize, u32>, 404 /// Used to look up a `FreezeListener` by cookie. 405 /// 406 /// There might be multiple freeze listeners for the same node, but at most one of them is 407 /// active. 408 freeze_listeners: RBTree<FreezeCookie, FreezeListener>, 409 } 410 411 impl ProcessNodeRefs { 412 fn new() -> Self { 413 Self { 414 by_handle: RBTree::new(), 415 handle_is_present: IdPool::new(), 416 by_node: RBTree::new(), 417 freeze_listeners: RBTree::new(), 418 } 419 } 420 } 421 422 use core::mem::offset_of; 423 use kernel::bindings::rb_process_layout; 424 pub(crate) const PROCESS_LAYOUT: rb_process_layout = rb_process_layout { 425 arc_offset: Arc::<Process>::DATA_OFFSET, 426 task: offset_of!(Process, task), 427 }; 428 429 /// A process using binder. 430 /// 431 /// Strictly speaking, there can be multiple of these per process. There is one for each binder fd 432 /// that a process has opened, so processes using several binder contexts have several `Process` 433 /// objects. This ensures that the contexts are fully separated. 434 #[pin_data] 435 pub(crate) struct Process { 436 pub(crate) ctx: Arc<Context>, 437 438 // The task leader (process). 439 pub(crate) task: ARef<Task>, 440 441 // Credential associated with file when `Process` is created. 442 pub(crate) cred: ARef<Credential>, 443 444 #[pin] 445 pub(crate) inner: SpinLock<ProcessInner>, 446 447 #[pin] 448 pub(crate) pages: ShrinkablePageRange, 449 450 // Waitqueue of processes waiting for all outstanding transactions to be 451 // processed. 452 #[pin] 453 freeze_wait: CondVar, 454 455 // Node references are in a different lock to avoid recursive acquisition when 456 // incrementing/decrementing a node in another process. 457 #[pin] 458 node_refs: SpinLock<ProcessNodeRefs>, 459 460 // Work node for deferred work item. 461 #[pin] 462 defer_work: Work<Process>, 463 464 // Links for process list in Context. 465 #[pin] 466 links: ListLinks, 467 468 pub(crate) stats: BinderStats, 469 } 470 471 kernel::impl_has_work! { 472 impl HasWork<Process> for Process { self.defer_work } 473 } 474 475 kernel::list::impl_list_arc_safe! { 476 impl ListArcSafe<0> for Process { untracked; } 477 } 478 kernel::list::impl_list_item! { 479 impl ListItem<0> for Process { 480 using ListLinks { self.links }; 481 } 482 } 483 484 impl workqueue::WorkItem for Process { 485 type Pointer = Arc<Process>; 486 487 fn run(me: Arc<Self>) { 488 let defer; 489 { 490 let mut inner = me.inner.lock(); 491 defer = inner.defer_work; 492 inner.defer_work = 0; 493 } 494 495 if defer & PROC_DEFER_FLUSH != 0 { 496 me.deferred_flush(); 497 } 498 if defer & PROC_DEFER_RELEASE != 0 { 499 me.deferred_release(); 500 } 501 } 502 } 503 504 impl Process { 505 fn new(ctx: Arc<Context>, cred: ARef<Credential>) -> Result<Arc<Self>> { 506 let current = kernel::current!(); 507 let process = Arc::pin_init::<Error>( 508 try_pin_init!(Process { 509 ctx, 510 cred, 511 inner <- kernel::new_spinlock!(ProcessInner::new(), "Process::inner"), 512 pages <- ShrinkablePageRange::new(&super::BINDER_SHRINKER), 513 node_refs <- kernel::new_spinlock!(ProcessNodeRefs::new(), "Process::node_refs"), 514 freeze_wait <- kernel::new_condvar!("Process::freeze_wait"), 515 task: current.group_leader().into(), 516 defer_work <- kernel::new_work!("Process::defer_work"), 517 links <- ListLinks::new(), 518 stats: BinderStats::new(), 519 }), 520 GFP_KERNEL, 521 )?; 522 523 process.ctx.register_process(process.clone())?; 524 525 Ok(process) 526 } 527 528 pub(crate) fn pid_in_current_ns(&self) -> kernel::task::Pid { 529 self.task.tgid_nr_ns(None) 530 } 531 532 #[inline(never)] 533 pub(crate) fn debug_print_stats(&self, m: &SeqFile, ctx: &Context) -> Result<()> { 534 seq_print!(m, "proc {}\n", self.pid_in_current_ns()); 535 seq_print!(m, "context {}\n", &*ctx.name); 536 537 let inner = self.inner.lock(); 538 seq_print!(m, " threads: {}\n", inner.threads.iter().count()); 539 seq_print!( 540 m, 541 " requested threads: {}+{}/{}\n", 542 inner.requested_thread_count, 543 inner.started_thread_count, 544 inner.max_threads, 545 ); 546 if let Some(mapping) = &inner.mapping { 547 seq_print!( 548 m, 549 " free oneway space: {}\n", 550 mapping.alloc.free_oneway_space() 551 ); 552 seq_print!(m, " buffers: {}\n", mapping.alloc.count_buffers()); 553 } 554 seq_print!( 555 m, 556 " outstanding transactions: {}\n", 557 inner.outstanding_txns 558 ); 559 seq_print!(m, " nodes: {}\n", inner.nodes.iter().count()); 560 drop(inner); 561 562 { 563 let mut refs = self.node_refs.lock(); 564 let (mut count, mut weak, mut strong) = (0, 0, 0); 565 for r in refs.by_handle.values_mut() { 566 let node_ref = r.node_ref(); 567 let (nstrong, nweak) = node_ref.get_count(); 568 count += 1; 569 weak += nweak; 570 strong += nstrong; 571 } 572 seq_print!(m, " refs: {count} s {strong} w {weak}\n"); 573 } 574 575 self.stats.debug_print(" ", m); 576 577 Ok(()) 578 } 579 580 #[inline(never)] 581 pub(crate) fn debug_print(&self, m: &SeqFile, ctx: &Context, print_all: bool) -> Result<()> { 582 seq_print!(m, "proc {}\n", self.pid_in_current_ns()); 583 seq_print!(m, "context {}\n", &*ctx.name); 584 585 let mut all_threads = KVec::new(); 586 let mut all_nodes = KVec::new(); 587 loop { 588 let inner = self.inner.lock(); 589 let num_threads = inner.threads.iter().count(); 590 let num_nodes = inner.nodes.iter().count(); 591 592 if all_threads.capacity() < num_threads || all_nodes.capacity() < num_nodes { 593 drop(inner); 594 all_threads.reserve(num_threads, GFP_KERNEL)?; 595 all_nodes.reserve(num_nodes, GFP_KERNEL)?; 596 continue; 597 } 598 599 for thread in inner.threads.values() { 600 assert!(all_threads.len() < all_threads.capacity()); 601 let _ = all_threads.push(thread.clone(), GFP_ATOMIC); 602 } 603 604 for node in inner.nodes.values() { 605 assert!(all_nodes.len() < all_nodes.capacity()); 606 let _ = all_nodes.push(node.clone(), GFP_ATOMIC); 607 } 608 609 break; 610 } 611 612 for thread in all_threads { 613 thread.debug_print(m, print_all)?; 614 } 615 616 let mut inner = self.inner.lock(); 617 for node in all_nodes { 618 if print_all || node.has_oneway_transaction(&mut inner) { 619 node.full_debug_print(m, &mut inner)?; 620 } 621 } 622 drop(inner); 623 624 if print_all { 625 let mut refs = self.node_refs.lock(); 626 for r in refs.by_handle.values_mut() { 627 let node_ref = r.node_ref(); 628 let dead = node_ref.node.owner.inner.lock().is_dead; 629 let (strong, weak) = node_ref.get_count(); 630 let debug_id = node_ref.node.debug_id; 631 632 seq_print!( 633 m, 634 " ref {}: desc {} {}node {debug_id} s {strong} w {weak}", 635 r.debug_id, 636 r.handle, 637 if dead { "dead " } else { "" } 638 ); 639 } 640 } 641 642 let inner = self.inner.lock(); 643 for work in &inner.work { 644 work.debug_print(m, " ", " pending transaction ")?; 645 } 646 for _death in &inner.delivered_deaths { 647 seq_print!(m, " has delivered dead binder\n"); 648 } 649 if let Some(mapping) = &inner.mapping { 650 mapping.alloc.debug_print(m)?; 651 } 652 drop(inner); 653 654 Ok(()) 655 } 656 657 /// Attempts to fetch a work item from the process queue. 658 pub(crate) fn get_work(&self) -> Option<DLArc<dyn DeliverToRead>> { 659 self.inner.lock().work.pop_front() 660 } 661 662 /// Attempts to fetch a work item from the process queue. If none is available, it registers the 663 /// given thread as ready to receive work directly. 664 /// 665 /// This must only be called when the thread is not participating in a transaction chain; when 666 /// it is, work will always be delivered directly to the thread (and not through the process 667 /// queue). 668 pub(crate) fn get_work_or_register<'a>( 669 &'a self, 670 thread: &'a Arc<Thread>, 671 ) -> GetWorkOrRegister<'a> { 672 let mut inner = self.inner.lock(); 673 // Try to get work from the process queue. 674 if let Some(work) = inner.work.pop_front() { 675 return GetWorkOrRegister::Work(work); 676 } 677 678 // Register the thread as ready. 679 GetWorkOrRegister::Register(Registration::new(thread, &mut inner)) 680 } 681 682 fn get_current_thread(self: ArcBorrow<'_, Self>) -> Result<Arc<Thread>> { 683 let id = { 684 let current = kernel::current!(); 685 if self.task != current.group_leader() { 686 pr_err!("get_current_thread was called from the wrong process."); 687 return Err(EINVAL); 688 } 689 current.pid() 690 }; 691 692 { 693 let inner = self.inner.lock(); 694 if let Some(thread) = inner.threads.get(&id) { 695 return Ok(thread.clone()); 696 } 697 } 698 699 // Allocate a new `Thread` without holding any locks. 700 let reservation = RBTreeNodeReservation::new(GFP_KERNEL)?; 701 let ta: Arc<Thread> = Thread::new(id, self.into())?; 702 703 let mut inner = self.inner.lock(); 704 match inner.threads.entry(id) { 705 rbtree::Entry::Vacant(entry) => { 706 entry.insert(ta.clone(), reservation); 707 Ok(ta) 708 } 709 rbtree::Entry::Occupied(_entry) => { 710 pr_err!("Cannot create two threads with the same id."); 711 Err(EINVAL) 712 } 713 } 714 } 715 716 pub(crate) fn push_work(&self, work: DLArc<dyn DeliverToRead>) -> BinderResult { 717 // If push_work fails, drop the work item outside the lock. 718 let res = self.inner.lock().push_work(work); 719 match res { 720 Ok(()) => Ok(()), 721 Err((err, work)) => { 722 drop(work); 723 Err(err) 724 } 725 } 726 } 727 728 fn set_as_manager( 729 self: ArcBorrow<'_, Self>, 730 info: Option<FlatBinderObject>, 731 thread: &Thread, 732 ) -> Result { 733 let (ptr, cookie, flags) = if let Some(obj) = info { 734 ( 735 // SAFETY: The object type for this ioctl is implicitly `BINDER_TYPE_BINDER`, so it 736 // is safe to access the `binder` field. 737 unsafe { obj.__bindgen_anon_1.binder }, 738 obj.cookie, 739 obj.flags, 740 ) 741 } else { 742 (0, 0, 0) 743 }; 744 let node_ref = self.get_node(ptr, cookie, flags, true, thread)?; 745 let node = node_ref.node.clone(); 746 self.ctx.set_manager_node(node_ref)?; 747 self.inner.lock().is_manager = true; 748 749 // Force the state of the node to prevent the delivery of acquire/increfs. 750 let mut owner_inner = node.owner.inner.lock(); 751 node.force_has_count(&mut owner_inner); 752 Ok(()) 753 } 754 755 fn get_node_inner( 756 self: ArcBorrow<'_, Self>, 757 ptr: u64, 758 cookie: u64, 759 flags: u32, 760 strong: bool, 761 thread: &Thread, 762 wrapper: Option<CritIncrWrapper>, 763 ) -> Result<Result<NodeRef, CouldNotDeliverCriticalIncrement>> { 764 // Try to find an existing node. 765 { 766 let mut inner = self.inner.lock(); 767 if let Some(node) = inner.get_existing_node(ptr, cookie)? { 768 return Ok(inner.new_node_ref_with_thread(node, strong, thread, wrapper)); 769 } 770 } 771 772 // Allocate the node before reacquiring the lock. 773 let node = DTRWrap::arc_pin_init(Node::new(ptr, cookie, flags, self.into()))?.into_arc(); 774 let rbnode = RBTreeNode::new(ptr, node.clone(), GFP_KERNEL)?; 775 let mut inner = self.inner.lock(); 776 if let Some(node) = inner.get_existing_node(ptr, cookie)? { 777 return Ok(inner.new_node_ref_with_thread(node, strong, thread, wrapper)); 778 } 779 780 inner.nodes.insert(rbnode); 781 // This can only fail if someone has already pushed the node to a list, but we just created 782 // it and still hold the lock, so it can't fail right now. 783 let node_ref = inner 784 .new_node_ref_with_thread(node, strong, thread, wrapper) 785 .unwrap(); 786 787 Ok(Ok(node_ref)) 788 } 789 790 pub(crate) fn get_node( 791 self: ArcBorrow<'_, Self>, 792 ptr: u64, 793 cookie: u64, 794 flags: u32, 795 strong: bool, 796 thread: &Thread, 797 ) -> Result<NodeRef> { 798 let mut wrapper = None; 799 for _ in 0..2 { 800 match self.get_node_inner(ptr, cookie, flags, strong, thread, wrapper) { 801 Err(err) => return Err(err), 802 Ok(Ok(node_ref)) => return Ok(node_ref), 803 Ok(Err(CouldNotDeliverCriticalIncrement)) => { 804 wrapper = Some(CritIncrWrapper::new()?); 805 } 806 } 807 } 808 // We only get a `CouldNotDeliverCriticalIncrement` error if `wrapper` is `None`, so the 809 // loop should run at most twice. 810 unreachable!() 811 } 812 813 pub(crate) fn insert_or_update_handle( 814 self: ArcBorrow<'_, Process>, 815 node_ref: NodeRef, 816 is_manager: bool, 817 ) -> Result<u32> { 818 { 819 let mut refs = self.node_refs.lock(); 820 821 // Do a lookup before inserting. 822 if let Some(handle_ref) = refs.by_node.get(&node_ref.node.global_id()) { 823 let handle = *handle_ref; 824 let info = refs.by_handle.get_mut(&handle).unwrap(); 825 info.node_ref().absorb(node_ref); 826 return Ok(handle); 827 } 828 } 829 830 // Reserve memory for tree nodes. 831 let reserve1 = RBTreeNodeReservation::new(GFP_KERNEL)?; 832 let reserve2 = RBTreeNodeReservation::new(GFP_KERNEL)?; 833 let info = UniqueArc::new_uninit(GFP_KERNEL)?; 834 835 let mut refs_lock = self.node_refs.lock(); 836 let mut refs = &mut *refs_lock; 837 838 let (unused_id, by_handle_slot) = loop { 839 // ID 0 may only be used by the manager. 840 let start = if is_manager { 0 } else { 1 }; 841 842 if let Some(res) = refs.handle_is_present.find_unused_id(start) { 843 match refs.by_handle.entry(res.as_u32()) { 844 rbtree::Entry::Vacant(entry) => break (res, entry), 845 rbtree::Entry::Occupied(_) => { 846 pr_err!("Detected mismatch between handle_is_present and by_handle"); 847 res.acquire(); 848 kernel::warn_on!(true); 849 return Err(EINVAL); 850 } 851 } 852 } 853 854 let grow_request = refs.handle_is_present.grow_request().ok_or(ENOMEM)?; 855 drop(refs_lock); 856 let resizer = grow_request.realloc(GFP_KERNEL)?; 857 refs_lock = self.node_refs.lock(); 858 refs = &mut *refs_lock; 859 refs.handle_is_present.grow(resizer); 860 }; 861 let handle = unused_id.as_u32(); 862 863 // Do a lookup again as node may have been inserted before the lock was reacquired. 864 let by_node_slot = match refs.by_node.entry(node_ref.node.global_id()) { 865 rbtree::Entry::Vacant(by_node_slot) => by_node_slot, 866 rbtree::Entry::Occupied(handle_ref) => { 867 // The node was inserted by another thread while we didn't hold the lock. 868 let handle = handle_ref.get(); 869 let info = refs.by_handle.get_mut(handle).unwrap(); 870 info.node_ref().absorb(node_ref); 871 return Ok(*handle); 872 } 873 }; 874 875 let (info_proc, info_node) = { 876 let info_init = NodeRefInfo::new(node_ref, handle, self.into()); 877 match info.pin_init_with(info_init) { 878 Ok(info) => ListArc::pair_from_pin_unique(info), 879 // error is infallible 880 Err(err) => match err {}, 881 } 882 }; 883 884 // Ensure the process is still alive while we insert a new reference. 885 // 886 // This releases the lock before inserting the nodes, but since `is_dead` is set as the 887 // first thing in `deferred_release`, process cleanup will not miss the items inserted into 888 // `refs` below. 889 if self.inner.lock().is_dead { 890 // Explicitly drop the lock so that `info_proc` and `info_node` are dropped outside of 891 // the lock. 892 drop(refs_lock); 893 return Err(ESRCH); 894 } 895 896 // SAFETY: `info_proc` and `info_node` reference the same node, so we are inserting 897 // `info_node` into the right node's `refs` list. 898 unsafe { info_proc.node_ref2().node.insert_node_info(info_node) }; 899 900 by_node_slot.insert(handle, reserve1); 901 by_handle_slot.insert(info_proc, reserve2); 902 unused_id.acquire(); 903 Ok(handle) 904 } 905 906 pub(crate) fn get_transaction_node(&self, handle: u32) -> BinderResult<NodeRef> { 907 // When handle is zero, try to get the context manager. 908 if handle == 0 { 909 let node_ref = self.ctx.get_manager_node(true)?; 910 if core::ptr::eq(self, &*node_ref.node.owner) { 911 return Err(EINVAL.into()); 912 } 913 Ok(node_ref) 914 } else { 915 Ok(self.get_node_from_handle(handle, true)?) 916 } 917 } 918 919 pub(crate) fn get_node_from_handle(&self, handle: u32, strong: bool) -> Result<NodeRef> { 920 self.node_refs 921 .lock() 922 .by_handle 923 .get_mut(&handle) 924 .ok_or(ENOENT)? 925 .node_ref() 926 .clone(strong) 927 } 928 929 pub(crate) fn remove_from_delivered_deaths(&self, death: &DArc<NodeDeath>) { 930 let mut inner = self.inner.lock(); 931 // SAFETY: By the invariant on the `delivered_links` field, this is the right linked list. 932 let removed = unsafe { inner.delivered_deaths.remove(death) }; 933 drop(inner); 934 drop(removed); 935 } 936 937 pub(crate) fn update_ref( 938 self: ArcBorrow<'_, Process>, 939 handle: u32, 940 inc: bool, 941 strong: bool, 942 ) -> Result { 943 if inc && handle == 0 { 944 if let Ok(node_ref) = self.ctx.get_manager_node(strong) { 945 if core::ptr::eq(&*self, &*node_ref.node.owner) { 946 return Err(EINVAL); 947 } 948 let _ = self.insert_or_update_handle(node_ref, true); 949 return Ok(()); 950 } 951 } 952 953 // To preserve original binder behaviour, we only fail requests where the manager tries to 954 // increment references on itself. 955 let _to_free_by_handle; 956 let _to_free_by_node; 957 let _to_free_freeze_listener; 958 let _to_free_freeze_listener_cleanup; 959 let mut refs = self.node_refs.lock(); 960 if let Some(info) = refs.by_handle.get_mut(&handle) { 961 if info.node_ref().update(inc, strong) { 962 // Clean up death if there is one attached to this node reference. 963 // 964 // We remove the entire `info` below, so no need to remove `death` from `info`. 965 if let Some(death) = info.death().as_ref() { 966 death.set_cleared(true); 967 self.remove_from_delivered_deaths(death); 968 } 969 970 // Remove reference from process tables, and from the node's `refs` list. 971 972 // SAFETY: We are removing the `NodeRefInfo` from the right node. 973 unsafe { info.node_ref2().node.remove_node_info(info) }; 974 975 let id = info.node_ref().node.global_id(); 976 977 if let Some(freeze) = *info.freeze() { 978 if let Some(fl) = refs.freeze_listeners.remove(&freeze) { 979 _to_free_freeze_listener_cleanup = fl.on_process_cleanup(&self); 980 _to_free_freeze_listener = fl; 981 } 982 } 983 984 _to_free_by_handle = refs.by_handle.remove_node(&handle); 985 _to_free_by_node = refs.by_node.remove_node(&id); 986 refs.handle_is_present.release_id(handle as usize); 987 988 if let Some(shrink) = refs.handle_is_present.shrink_request() { 989 drop(refs); 990 // This intentionally ignores allocation failures. 991 if let Ok(new_bitmap) = shrink.realloc(GFP_KERNEL) { 992 refs = self.node_refs.lock(); 993 refs.handle_is_present.shrink(new_bitmap); 994 } 995 } 996 } 997 } else { 998 // All refs are cleared in process exit, so this warning is expected in that case. 999 if !self.inner.lock().is_dead { 1000 pr_warn!("{}: no such ref {handle}\n", self.pid_in_current_ns()); 1001 } 1002 } 1003 Ok(()) 1004 } 1005 1006 /// Decrements the refcount of the given node, if one exists. 1007 pub(crate) fn update_node(&self, ptr: u64, cookie: u64, strong: bool) { 1008 let mut inner = self.inner.lock(); 1009 if let Ok(Some(node)) = inner.get_existing_node(ptr, cookie) { 1010 inner.update_node_refcount(&node, false, strong, 1, None); 1011 } 1012 } 1013 1014 pub(crate) fn inc_ref_done(&self, reader: &mut UserSliceReader, strong: bool) -> Result { 1015 let ptr = reader.read::<u64>()?; 1016 let cookie = reader.read::<u64>()?; 1017 let mut inner = self.inner.lock(); 1018 if let Ok(Some(node)) = inner.get_existing_node(ptr, cookie) { 1019 if let Some(node) = node.inc_ref_done_locked(strong, &mut inner) { 1020 // This only fails if the process is dead. 1021 let _ = inner.push_work(node); 1022 } 1023 } 1024 Ok(()) 1025 } 1026 1027 pub(crate) fn buffer_alloc( 1028 self: &Arc<Self>, 1029 debug_id: usize, 1030 size: usize, 1031 info: &mut TransactionInfo, 1032 ) -> BinderResult<NewAllocation> { 1033 use kernel::page::PAGE_SIZE; 1034 1035 let mut reserve_new_args = ReserveNewArgs { 1036 debug_id, 1037 size, 1038 is_oneway: info.is_oneway(), 1039 pid: info.from_pid, 1040 ..ReserveNewArgs::default() 1041 }; 1042 1043 let (new_alloc, addr) = loop { 1044 let mut inner = self.inner.lock(); 1045 let mapping = inner.mapping.as_mut().ok_or_else(BinderError::new_dead)?; 1046 let alloc_request = match mapping.alloc.reserve_new(reserve_new_args)? { 1047 ReserveNew::Success(new_alloc) => break (new_alloc, mapping.address), 1048 ReserveNew::NeedAlloc(request) => request, 1049 }; 1050 drop(inner); 1051 // We need to allocate memory and then call `reserve_new` again. 1052 reserve_new_args = alloc_request.make_alloc()?; 1053 }; 1054 1055 info.oneway_spam_suspect = new_alloc.oneway_spam_detected; 1056 let res = Allocation::new( 1057 self.clone(), 1058 debug_id, 1059 new_alloc.offset, 1060 size, 1061 addr + new_alloc.offset, 1062 ); 1063 1064 // This allocation will be marked as in use until the `Allocation` is used to free it. 1065 // 1066 // This method can't be called while holding a lock, so we release the lock first. It's 1067 // okay for several threads to use the method on the same index at the same time. In that 1068 // case, one of the calls will allocate the given page (if missing), and the other call 1069 // will wait for the other call to finish allocating the page. 1070 // 1071 // We will not call `stop_using_range` in parallel with this on the same page, because the 1072 // allocation can only be removed via the destructor of the `Allocation` object that we 1073 // currently own. 1074 match self.pages.use_range( 1075 new_alloc.offset / PAGE_SIZE, 1076 (new_alloc.offset + size).div_ceil(PAGE_SIZE), 1077 ) { 1078 Ok(()) => {} 1079 Err(err) => { 1080 pr_warn!("use_range failure {:?}", err); 1081 return Err(err.into()); 1082 } 1083 } 1084 1085 Ok(NewAllocation(res)) 1086 } 1087 1088 pub(crate) fn buffer_get(self: &Arc<Self>, ptr: usize) -> Option<Allocation> { 1089 let mut inner = self.inner.lock(); 1090 let mapping = inner.mapping.as_mut()?; 1091 let offset = ptr.checked_sub(mapping.address)?; 1092 let (size, debug_id, odata) = mapping.alloc.reserve_existing(offset).ok()?; 1093 let mut alloc = Allocation::new(self.clone(), debug_id, offset, size, ptr); 1094 if let Some(data) = odata { 1095 alloc.set_info(data); 1096 } 1097 Some(alloc) 1098 } 1099 1100 pub(crate) fn buffer_raw_free(&self, ptr: usize) { 1101 let mut inner = self.inner.lock(); 1102 if let Some(ref mut mapping) = &mut inner.mapping { 1103 let offset = match ptr.checked_sub(mapping.address) { 1104 Some(offset) => offset, 1105 None => return, 1106 }; 1107 1108 let freed_range = match mapping.alloc.reservation_abort(offset) { 1109 Ok(freed_range) => freed_range, 1110 Err(_) => { 1111 pr_warn!( 1112 "Pointer {:x} failed to free, base = {:x}\n", 1113 ptr, 1114 mapping.address 1115 ); 1116 return; 1117 } 1118 }; 1119 1120 // No more allocations in this range. Mark them as not in use. 1121 // 1122 // Must be done before we release the lock so that `use_range` is not used on these 1123 // indices until `stop_using_range` returns. 1124 self.pages 1125 .stop_using_range(freed_range.start_page_idx, freed_range.end_page_idx); 1126 } 1127 } 1128 1129 pub(crate) fn buffer_make_freeable(&self, offset: usize, mut data: Option<AllocationInfo>) { 1130 let mut inner = self.inner.lock(); 1131 if let Some(ref mut mapping) = &mut inner.mapping { 1132 if mapping.alloc.reservation_commit(offset, &mut data).is_err() { 1133 pr_warn!("Offset {} failed to be marked freeable\n", offset); 1134 } 1135 } 1136 } 1137 1138 fn create_mapping(&self, vma: &mm::virt::VmaNew) -> Result { 1139 use kernel::page::PAGE_SIZE; 1140 let size = usize::min(vma.end() - vma.start(), bindings::SZ_4M as usize); 1141 let mapping = Mapping::new(vma.start(), size); 1142 let page_count = self.pages.register_with_vma(vma)?; 1143 if page_count * PAGE_SIZE != size { 1144 return Err(EINVAL); 1145 } 1146 1147 // Save range allocator for later. 1148 self.inner.lock().mapping = Some(mapping); 1149 1150 Ok(()) 1151 } 1152 1153 fn version(&self, data: UserSlice) -> Result { 1154 data.writer().write(&BinderVersion::current()) 1155 } 1156 1157 pub(crate) fn register_thread(&self) -> bool { 1158 self.inner.lock().register_thread() 1159 } 1160 1161 fn remove_thread(&self, thread: Arc<Thread>) { 1162 self.inner.lock().threads.remove(&thread.id); 1163 thread.release(); 1164 } 1165 1166 fn set_max_threads(&self, max: u32) { 1167 self.inner.lock().max_threads = max; 1168 } 1169 1170 fn set_oneway_spam_detection_enabled(&self, enabled: u32) { 1171 self.inner.lock().oneway_spam_detection_enabled = enabled != 0; 1172 } 1173 1174 pub(crate) fn is_oneway_spam_detection_enabled(&self) -> bool { 1175 self.inner.lock().oneway_spam_detection_enabled 1176 } 1177 1178 fn get_node_debug_info(&self, data: UserSlice) -> Result { 1179 let (mut reader, mut writer) = data.reader_writer(); 1180 1181 // Read the starting point. 1182 let ptr = reader.read::<BinderNodeDebugInfo>()?.ptr; 1183 let mut out = BinderNodeDebugInfo::default(); 1184 1185 { 1186 let inner = self.inner.lock(); 1187 for (node_ptr, node) in &inner.nodes { 1188 if *node_ptr > ptr { 1189 node.populate_debug_info(&mut out, &inner); 1190 break; 1191 } 1192 } 1193 } 1194 1195 writer.write(&out) 1196 } 1197 1198 fn get_node_info_from_ref(&self, data: UserSlice) -> Result { 1199 let (mut reader, mut writer) = data.reader_writer(); 1200 let mut out = reader.read::<BinderNodeInfoForRef>()?; 1201 1202 if out.strong_count != 0 1203 || out.weak_count != 0 1204 || out.reserved1 != 0 1205 || out.reserved2 != 0 1206 || out.reserved3 != 0 1207 { 1208 return Err(EINVAL); 1209 } 1210 1211 // Only the context manager is allowed to use this ioctl. 1212 if !self.inner.lock().is_manager { 1213 return Err(EPERM); 1214 } 1215 1216 { 1217 let mut node_refs = self.node_refs.lock(); 1218 let node_info = node_refs.by_handle.get_mut(&out.handle).ok_or(ENOENT)?; 1219 let node_ref = node_info.node_ref(); 1220 let owner_inner = node_ref.node.owner.inner.lock(); 1221 node_ref.node.populate_counts(&mut out, &owner_inner); 1222 } 1223 1224 // Write the result back. 1225 writer.write(&out) 1226 } 1227 1228 pub(crate) fn needs_thread(&self) -> bool { 1229 let mut inner = self.inner.lock(); 1230 let ret = inner.requested_thread_count == 0 1231 && inner.ready_threads.is_empty() 1232 && inner.started_thread_count < inner.max_threads; 1233 if ret { 1234 inner.requested_thread_count += 1 1235 } 1236 ret 1237 } 1238 1239 pub(crate) fn request_death( 1240 self: &Arc<Self>, 1241 reader: &mut UserSliceReader, 1242 thread: &Thread, 1243 ) -> Result { 1244 let handle: u32 = reader.read()?; 1245 let cookie: u64 = reader.read()?; 1246 1247 // Queue BR_ERROR if we can't allocate memory for the death notification. 1248 let death = UniqueArc::new_uninit(GFP_KERNEL).inspect_err(|_| { 1249 thread.push_return_work(BR_ERROR); 1250 })?; 1251 let mut refs = self.node_refs.lock(); 1252 let Some(info) = refs.by_handle.get_mut(&handle) else { 1253 pr_warn!("BC_REQUEST_DEATH_NOTIFICATION invalid ref {handle}\n"); 1254 return Ok(()); 1255 }; 1256 1257 // Nothing to do if there is already a death notification request for this handle. 1258 if info.death().is_some() { 1259 pr_warn!("BC_REQUEST_DEATH_NOTIFICATION death notification already set\n"); 1260 return Ok(()); 1261 } 1262 1263 let death = { 1264 let death_init = NodeDeath::new(info.node_ref().node.clone(), self.clone(), cookie); 1265 match death.pin_init_with(death_init) { 1266 Ok(death) => death, 1267 // error is infallible 1268 Err(err) => match err {}, 1269 } 1270 }; 1271 1272 // Register the death notification. 1273 { 1274 let owner = info.node_ref2().node.owner.clone(); 1275 let mut owner_inner = owner.inner.lock(); 1276 if owner_inner.is_dead { 1277 let death = Arc::from(death); 1278 *info.death() = Some(death.clone()); 1279 drop(owner_inner); 1280 death.set_dead(); 1281 } else { 1282 let death = ListArc::from(death); 1283 *info.death() = Some(death.clone_arc()); 1284 info.node_ref().node.add_death(death, &mut owner_inner); 1285 } 1286 } 1287 Ok(()) 1288 } 1289 1290 pub(crate) fn clear_death(&self, reader: &mut UserSliceReader, thread: &Thread) -> Result { 1291 let handle: u32 = reader.read()?; 1292 let cookie: u64 = reader.read()?; 1293 1294 let mut refs = self.node_refs.lock(); 1295 let Some(info) = refs.by_handle.get_mut(&handle) else { 1296 pr_warn!("BC_CLEAR_DEATH_NOTIFICATION invalid ref {handle}\n"); 1297 return Ok(()); 1298 }; 1299 1300 let Some(death) = info.death().take() else { 1301 pr_warn!("BC_CLEAR_DEATH_NOTIFICATION death notification not active\n"); 1302 return Ok(()); 1303 }; 1304 if death.cookie != cookie { 1305 *info.death() = Some(death); 1306 pr_warn!("BC_CLEAR_DEATH_NOTIFICATION death notification cookie mismatch\n"); 1307 return Ok(()); 1308 } 1309 1310 // Update state and determine if we need to queue a work item. We only need to do it when 1311 // the node is not dead or if the user already completed the death notification. 1312 let should_schedule = death.set_cleared(false); 1313 drop(refs); 1314 1315 if should_schedule { 1316 if let Some(death) = ListArc::try_from_arc_or_drop(death) { 1317 let _ = thread.push_work_if_looper(death); 1318 } 1319 } 1320 1321 Ok(()) 1322 } 1323 1324 pub(crate) fn dead_binder_done(&self, cookie: u64, thread: &Thread) { 1325 let death = self.inner.lock().pull_delivered_death(cookie); 1326 if let Some(death) = death { 1327 death.set_notification_done(thread); 1328 } 1329 } 1330 1331 /// Locks the spinlock and move the `nodes` rbtree out. 1332 /// 1333 /// This allows you to iterate through `nodes` while also allowing you to give other parts of 1334 /// the codebase exclusive access to `ProcessInner`. 1335 pub(crate) fn lock_with_nodes(&self) -> WithNodes<'_> { 1336 let mut inner = self.inner.lock(); 1337 WithNodes { 1338 nodes: take(&mut inner.nodes), 1339 inner, 1340 } 1341 } 1342 1343 fn deferred_flush(&self) { 1344 let inner = self.inner.lock(); 1345 for thread in inner.threads.values() { 1346 thread.exit_looper(); 1347 } 1348 } 1349 1350 fn deferred_release(self: Arc<Self>) { 1351 let is_manager = { 1352 let mut inner = self.inner.lock(); 1353 inner.is_dead = true; 1354 inner.is_frozen = IsFrozen::No; 1355 inner.sync_recv = false; 1356 inner.async_recv = false; 1357 inner.is_manager 1358 }; 1359 1360 if is_manager { 1361 self.ctx.unset_manager_node(); 1362 } 1363 1364 self.ctx.deregister_process(&self); 1365 1366 let binderfs_file = self.inner.lock().binderfs_file.take(); 1367 drop(binderfs_file); 1368 1369 // Release threads. 1370 let threads = { 1371 let mut inner = self.inner.lock(); 1372 let threads = take(&mut inner.threads); 1373 let ready = take(&mut inner.ready_threads); 1374 drop(inner); 1375 drop(ready); 1376 1377 for thread in threads.values() { 1378 thread.release(); 1379 } 1380 threads 1381 }; 1382 1383 // Release nodes. 1384 { 1385 while let Some(node) = { 1386 let mut lock = self.inner.lock(); 1387 lock.nodes.cursor_front_mut().map(|c| c.remove_current().1) 1388 } { 1389 node.to_key_value().1.release(); 1390 } 1391 } 1392 1393 // Clean up death listeners and remove nodes from external node info lists. 1394 for info in self.node_refs.lock().by_handle.values_mut() { 1395 // SAFETY: We are removing the `NodeRefInfo` from the right node. 1396 unsafe { info.node_ref2().node.remove_node_info(info) }; 1397 1398 // Clear death notifications from the nodes (that belong to a different process). 1399 // No need to remove them from `info` as we clear info below. 1400 if let Some(death) = info.death().as_ref() { 1401 death.set_cleared(false); 1402 } 1403 } 1404 1405 // Clean up freeze listeners. 1406 let freeze_listeners = take(&mut self.node_refs.lock().freeze_listeners); 1407 for listener in freeze_listeners.values() { 1408 listener.on_process_cleanup(&self); 1409 } 1410 drop(freeze_listeners); 1411 1412 // Release refs on foreign nodes. 1413 { 1414 let mut refs = self.node_refs.lock(); 1415 let by_handle = take(&mut refs.by_handle); 1416 let by_node = take(&mut refs.by_node); 1417 drop(refs); 1418 drop(by_node); 1419 drop(by_handle); 1420 } 1421 1422 // Cancel all pending work items. 1423 while let Some(work) = self.get_work() { 1424 work.into_arc().cancel(); 1425 } 1426 1427 // Clear delivered_deaths list. 1428 // 1429 // Scope ensures that MutexGuard is dropped while executing the body. 1430 while let Some(delivered_death) = { 1431 // Explicitly bind to avoid tail expression lifetime extension of the lockguard 1432 // Can be removed when the kernel moves to edition 2024 1433 let maybe_death = self.inner.lock().delivered_deaths.pop_front(); 1434 maybe_death 1435 } { 1436 drop(delivered_death); 1437 } 1438 1439 // Free any resources kept alive by allocated buffers. 1440 let omapping = self.inner.lock().mapping.take(); 1441 if let Some(mut mapping) = omapping { 1442 let address = mapping.address; 1443 mapping 1444 .alloc 1445 .take_for_each(|offset, size, debug_id, odata| { 1446 let ptr = offset + address; 1447 let mut alloc = Allocation::new(self.clone(), debug_id, offset, size, ptr); 1448 if let Some(data) = odata { 1449 alloc.set_info(data); 1450 } 1451 drop(alloc) 1452 }); 1453 } 1454 1455 // calls to synchronize_rcu() in thread drop will happen here 1456 drop(threads); 1457 } 1458 1459 pub(crate) fn drop_outstanding_txn(&self) { 1460 let wake = { 1461 let mut inner = self.inner.lock(); 1462 if inner.outstanding_txns == 0 { 1463 pr_err!("outstanding_txns underflow"); 1464 return; 1465 } 1466 inner.outstanding_txns -= 1; 1467 inner.is_frozen.is_frozen() && inner.outstanding_txns == 0 1468 }; 1469 1470 if wake { 1471 self.freeze_wait.notify_all(); 1472 } 1473 } 1474 1475 // #[export_name] is a temporary workaround so that ps output does not become unreadable from 1476 // mangled symbol names. 1477 #[export_name = "rust_binder_freeze"] 1478 pub(crate) fn ioctl_freeze(&self, info: &BinderFreezeInfo) -> Result { 1479 if info.enable == 0 { 1480 let msgs = self.prepare_freeze_messages()?; 1481 let mut inner = self.inner.lock(); 1482 inner.sync_recv = false; 1483 inner.async_recv = false; 1484 inner.is_frozen = IsFrozen::No; 1485 drop(inner); 1486 msgs.send_messages(); 1487 return Ok(()); 1488 } 1489 1490 let mut inner = self.inner.lock(); 1491 inner.sync_recv = false; 1492 inner.async_recv = false; 1493 inner.is_frozen = IsFrozen::InProgress; 1494 1495 if info.timeout_ms > 0 { 1496 let mut jiffies = kernel::time::msecs_to_jiffies(info.timeout_ms); 1497 while jiffies > 0 { 1498 if inner.outstanding_txns == 0 { 1499 break; 1500 } 1501 1502 match self 1503 .freeze_wait 1504 .wait_interruptible_timeout(&mut inner, jiffies) 1505 { 1506 CondVarTimeoutResult::Signal { .. } => { 1507 inner.is_frozen = IsFrozen::No; 1508 return Err(ERESTARTSYS); 1509 } 1510 CondVarTimeoutResult::Woken { jiffies: remaining } => { 1511 jiffies = remaining; 1512 } 1513 CondVarTimeoutResult::Timeout => { 1514 jiffies = 0; 1515 } 1516 } 1517 } 1518 } 1519 1520 if inner.txns_pending_locked() { 1521 inner.is_frozen = IsFrozen::No; 1522 Err(EAGAIN) 1523 } else { 1524 drop(inner); 1525 match self.prepare_freeze_messages() { 1526 Ok(batch) => { 1527 self.inner.lock().is_frozen = IsFrozen::Yes; 1528 batch.send_messages(); 1529 Ok(()) 1530 } 1531 Err(kernel::alloc::AllocError) => { 1532 self.inner.lock().is_frozen = IsFrozen::No; 1533 Err(ENOMEM) 1534 } 1535 } 1536 } 1537 } 1538 } 1539 1540 fn get_frozen_status(data: UserSlice) -> Result { 1541 let (mut reader, mut writer) = data.reader_writer(); 1542 1543 let mut info = reader.read::<BinderFrozenStatusInfo>()?; 1544 info.sync_recv = 0; 1545 info.async_recv = 0; 1546 let mut found = false; 1547 1548 for ctx in crate::context::get_all_contexts()? { 1549 ctx.for_each_proc(|proc| { 1550 if proc.task.pid() == info.pid as Pid { 1551 found = true; 1552 let inner = proc.inner.lock(); 1553 let txns_pending = inner.txns_pending_locked(); 1554 info.async_recv |= u32::from(inner.async_recv); 1555 info.sync_recv |= u32::from(inner.sync_recv); 1556 info.sync_recv |= u32::from(txns_pending) << 1; 1557 } 1558 }); 1559 } 1560 1561 if found { 1562 writer.write(&info)?; 1563 Ok(()) 1564 } else { 1565 Err(EINVAL) 1566 } 1567 } 1568 1569 fn ioctl_freeze(reader: &mut UserSliceReader) -> Result { 1570 let info = reader.read::<BinderFreezeInfo>()?; 1571 1572 // Very unlikely for there to be more than 3, since a process normally uses at most binder and 1573 // hwbinder. 1574 let mut procs = KVec::with_capacity(3, GFP_KERNEL)?; 1575 1576 let ctxs = crate::context::get_all_contexts()?; 1577 for ctx in ctxs { 1578 for proc in ctx.get_procs_with_pid(info.pid as i32)? { 1579 procs.push(proc, GFP_KERNEL)?; 1580 } 1581 } 1582 1583 for proc in procs { 1584 proc.ioctl_freeze(&info)?; 1585 } 1586 Ok(()) 1587 } 1588 1589 /// The ioctl handler. 1590 impl Process { 1591 /// Ioctls that are write-only from the perspective of userspace. 1592 /// 1593 /// The kernel will only read from the pointer that userspace provided to us. 1594 fn ioctl_write_only( 1595 this: ArcBorrow<'_, Process>, 1596 _file: &File, 1597 cmd: u32, 1598 reader: &mut UserSliceReader, 1599 ) -> Result { 1600 let thread = this.get_current_thread()?; 1601 match cmd { 1602 uapi::BINDER_SET_MAX_THREADS => this.set_max_threads(reader.read()?), 1603 uapi::BINDER_THREAD_EXIT => this.remove_thread(thread), 1604 uapi::BINDER_SET_CONTEXT_MGR => this.set_as_manager(None, &thread)?, 1605 uapi::BINDER_SET_CONTEXT_MGR_EXT => { 1606 this.set_as_manager(Some(reader.read()?), &thread)? 1607 } 1608 uapi::BINDER_ENABLE_ONEWAY_SPAM_DETECTION => { 1609 this.set_oneway_spam_detection_enabled(reader.read()?) 1610 } 1611 uapi::BINDER_FREEZE => ioctl_freeze(reader)?, 1612 _ => return Err(EINVAL), 1613 } 1614 Ok(()) 1615 } 1616 1617 /// Ioctls that are read/write from the perspective of userspace. 1618 /// 1619 /// The kernel will both read from and write to the pointer that userspace provided to us. 1620 fn ioctl_write_read( 1621 this: ArcBorrow<'_, Process>, 1622 file: &File, 1623 cmd: u32, 1624 data: UserSlice, 1625 ) -> Result { 1626 let thread = this.get_current_thread()?; 1627 let blocking = (file.flags() & file::flags::O_NONBLOCK) == 0; 1628 match cmd { 1629 uapi::BINDER_WRITE_READ => thread.write_read(data, blocking)?, 1630 uapi::BINDER_GET_NODE_DEBUG_INFO => this.get_node_debug_info(data)?, 1631 uapi::BINDER_GET_NODE_INFO_FOR_REF => this.get_node_info_from_ref(data)?, 1632 uapi::BINDER_VERSION => this.version(data)?, 1633 uapi::BINDER_GET_FROZEN_INFO => get_frozen_status(data)?, 1634 uapi::BINDER_GET_EXTENDED_ERROR => thread.get_extended_error(data)?, 1635 _ => return Err(EINVAL), 1636 } 1637 Ok(()) 1638 } 1639 } 1640 1641 /// The file operations supported by `Process`. 1642 impl Process { 1643 pub(crate) fn open(ctx: ArcBorrow<'_, Context>, file: &File) -> Result<Arc<Process>> { 1644 Self::new(ctx.into(), ARef::from(file.cred())) 1645 } 1646 1647 pub(crate) fn release(this: Arc<Process>, _file: &File) { 1648 let binderfs_file; 1649 let should_schedule; 1650 { 1651 let mut inner = this.inner.lock(); 1652 should_schedule = inner.defer_work == 0; 1653 inner.defer_work |= PROC_DEFER_RELEASE; 1654 binderfs_file = inner.binderfs_file.take(); 1655 } 1656 1657 if should_schedule { 1658 // Ignore failures to schedule to the workqueue. Those just mean that we're already 1659 // scheduled for execution. 1660 let _ = workqueue::system().enqueue(this); 1661 } 1662 1663 drop(binderfs_file); 1664 } 1665 1666 pub(crate) fn flush(this: ArcBorrow<'_, Process>) -> Result { 1667 let should_schedule; 1668 { 1669 let mut inner = this.inner.lock(); 1670 should_schedule = inner.defer_work == 0; 1671 inner.defer_work |= PROC_DEFER_FLUSH; 1672 } 1673 1674 if should_schedule { 1675 // Ignore failures to schedule to the workqueue. Those just mean that we're already 1676 // scheduled for execution. 1677 let _ = workqueue::system().enqueue(Arc::from(this)); 1678 } 1679 Ok(()) 1680 } 1681 1682 pub(crate) fn ioctl(this: ArcBorrow<'_, Process>, file: &File, cmd: u32, arg: usize) -> Result { 1683 use kernel::ioctl::{_IOC_DIR, _IOC_SIZE}; 1684 use kernel::uapi::{_IOC_READ, _IOC_WRITE}; 1685 1686 crate::trace::trace_ioctl(cmd, arg); 1687 1688 let user_slice = UserSlice::new(UserPtr::from_addr(arg), _IOC_SIZE(cmd)); 1689 1690 const _IOC_READ_WRITE: u32 = _IOC_READ | _IOC_WRITE; 1691 1692 let res = match _IOC_DIR(cmd) { 1693 _IOC_WRITE => Self::ioctl_write_only(this, file, cmd, &mut user_slice.reader()), 1694 _IOC_READ_WRITE => Self::ioctl_write_read(this, file, cmd, user_slice), 1695 _ => Err(EINVAL), 1696 }; 1697 1698 crate::trace::trace_ioctl_done(res); 1699 res 1700 } 1701 1702 pub(crate) fn mmap( 1703 this: ArcBorrow<'_, Process>, 1704 _file: &File, 1705 vma: &mm::virt::VmaNew, 1706 ) -> Result { 1707 // We don't allow mmap to be used in a different process. 1708 if this.task != kernel::current!().group_leader() { 1709 return Err(EINVAL); 1710 } 1711 if vma.start() == 0 { 1712 return Err(EINVAL); 1713 } 1714 1715 vma.try_clear_maywrite().map_err(|_| EPERM)?; 1716 vma.set_dontcopy(); 1717 vma.set_mixedmap(); 1718 1719 // TODO: Set ops. We need to learn when the user unmaps so that we can stop using it. 1720 this.create_mapping(vma) 1721 } 1722 1723 pub(crate) fn poll( 1724 this: ArcBorrow<'_, Process>, 1725 file: &File, 1726 table: PollTable<'_>, 1727 ) -> Result<u32> { 1728 let thread = this.get_current_thread()?; 1729 let (from_proc, mut mask) = thread.poll(file, table); 1730 if mask == 0 && from_proc && !this.inner.lock().work.is_empty() { 1731 mask |= bindings::POLLIN; 1732 } 1733 Ok(mask) 1734 } 1735 } 1736 1737 /// Represents that a thread has registered with the `ready_threads` list of its process. 1738 /// 1739 /// The destructor of this type will unregister the thread from the list of ready threads. 1740 pub(crate) struct Registration<'a> { 1741 thread: &'a Arc<Thread>, 1742 } 1743 1744 impl<'a> Registration<'a> { 1745 fn new(thread: &'a Arc<Thread>, guard: &mut Guard<'_, ProcessInner, SpinLockBackend>) -> Self { 1746 assert!(core::ptr::eq(&thread.process.inner, guard.lock_ref())); 1747 // INVARIANT: We are pushing this thread to the right `ready_threads` list. 1748 if let Ok(list_arc) = ListArc::try_from_arc(thread.clone()) { 1749 guard.ready_threads.push_front(list_arc); 1750 } else { 1751 // It is an error to hit this branch, and it should not be reachable. We try to do 1752 // something reasonable when the failure path happens. Most likely, the thread in 1753 // question will sleep forever. 1754 pr_err!("Same thread registered with `ready_threads` twice."); 1755 } 1756 Self { thread } 1757 } 1758 } 1759 1760 impl Drop for Registration<'_> { 1761 fn drop(&mut self) { 1762 let mut inner = self.thread.process.inner.lock(); 1763 // SAFETY: The thread has the invariant that we never push it to any other linked list than 1764 // the `ready_threads` list of its parent process. Therefore, the thread is either in that 1765 // list, or in no list. 1766 unsafe { inner.ready_threads.remove(self.thread) }; 1767 } 1768 } 1769 1770 pub(crate) struct WithNodes<'a> { 1771 pub(crate) inner: Guard<'a, ProcessInner, SpinLockBackend>, 1772 pub(crate) nodes: RBTree<u64, DArc<Node>>, 1773 } 1774 1775 impl Drop for WithNodes<'_> { 1776 fn drop(&mut self) { 1777 core::mem::swap(&mut self.nodes, &mut self.inner.nodes); 1778 if self.nodes.iter().next().is_some() { 1779 pr_err!("nodes array was modified while using lock_with_nodes\n"); 1780 } 1781 } 1782 } 1783 1784 pub(crate) enum GetWorkOrRegister<'a> { 1785 Work(DLArc<dyn DeliverToRead>), 1786 Register(Registration<'a>), 1787 } 1788