process.rs 59 KB

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