node.rs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (C) 2025 Google LLC.
  3. use kernel::{
  4. list::{AtomicTracker, List, ListArc, ListLinks, TryNewListArc},
  5. prelude::*,
  6. seq_file::SeqFile,
  7. seq_print,
  8. sync::lock::{spinlock::SpinLockBackend, Guard},
  9. sync::{Arc, LockedBy, SpinLock},
  10. };
  11. use crate::{
  12. defs::*,
  13. error::BinderError,
  14. process::{NodeRefInfo, Process, ProcessInner},
  15. thread::Thread,
  16. transaction::Transaction,
  17. BinderReturnWriter, DArc, DLArc, DTRWrap, DeliverToRead,
  18. };
  19. use core::mem;
  20. mod wrapper;
  21. pub(crate) use self::wrapper::CritIncrWrapper;
  22. #[derive(Debug)]
  23. pub(crate) struct CouldNotDeliverCriticalIncrement;
  24. /// Keeps track of how this node is scheduled.
  25. ///
  26. /// There are two ways to schedule a node to a work list. Just schedule the node itself, or
  27. /// allocate a wrapper that references the node and schedule the wrapper. These wrappers exists to
  28. /// make it possible to "move" a node from one list to another - when `do_work` is called directly
  29. /// on the `Node`, then it's a no-op if there's also a pending wrapper.
  30. ///
  31. /// Wrappers are generally only needed for zero-to-one refcount increments, and there are two cases
  32. /// of this: weak increments and strong increments. We call such increments "critical" because it
  33. /// is critical that they are delivered to the thread doing the increment. Some examples:
  34. ///
  35. /// * One thread makes a zero-to-one strong increment, and another thread makes a zero-to-one weak
  36. /// increment. Delivering the node to the thread doing the weak increment is wrong, since the
  37. /// thread doing the strong increment may have ended a long time ago when the command is actually
  38. /// processed by userspace.
  39. ///
  40. /// * We have a weak reference and are about to drop it on one thread. But then another thread does
  41. /// a zero-to-one strong increment. If the strong increment gets sent to the thread that was
  42. /// about to drop the weak reference, then the strong increment could be processed after the
  43. /// other thread has already exited, which would be too late.
  44. ///
  45. /// Note that trying to create a `ListArc` to the node can succeed even if `has_normal_push` is
  46. /// set. This is because another thread might just have popped the node from a todo list, but not
  47. /// yet called `do_work`. However, if `has_normal_push` is false, then creating a `ListArc` should
  48. /// always succeed.
  49. ///
  50. /// Like the other fields in `NodeInner`, the delivery state is protected by the process lock.
  51. struct DeliveryState {
  52. /// Is the `Node` currently scheduled?
  53. has_pushed_node: bool,
  54. /// Is a wrapper currently scheduled?
  55. ///
  56. /// The wrapper is used only for strong zero2one increments.
  57. has_pushed_wrapper: bool,
  58. /// Is the currently scheduled `Node` scheduled due to a weak zero2one increment?
  59. ///
  60. /// Weak zero2one operations are always scheduled using the `Node`.
  61. has_weak_zero2one: bool,
  62. /// Is the currently scheduled wrapper/`Node` scheduled due to a strong zero2one increment?
  63. ///
  64. /// If `has_pushed_wrapper` is set, then the strong zero2one increment was scheduled using the
  65. /// wrapper. Otherwise, `has_pushed_node` must be set and it was scheduled using the `Node`.
  66. has_strong_zero2one: bool,
  67. }
  68. impl DeliveryState {
  69. fn should_normal_push(&self) -> bool {
  70. !self.has_pushed_node && !self.has_pushed_wrapper
  71. }
  72. fn did_normal_push(&mut self) {
  73. assert!(self.should_normal_push());
  74. self.has_pushed_node = true;
  75. }
  76. fn should_push_weak_zero2one(&self) -> bool {
  77. !self.has_weak_zero2one && !self.has_strong_zero2one
  78. }
  79. fn can_push_weak_zero2one_normally(&self) -> bool {
  80. !self.has_pushed_node
  81. }
  82. fn did_push_weak_zero2one(&mut self) {
  83. assert!(self.should_push_weak_zero2one());
  84. assert!(self.can_push_weak_zero2one_normally());
  85. self.has_pushed_node = true;
  86. self.has_weak_zero2one = true;
  87. }
  88. fn should_push_strong_zero2one(&self) -> bool {
  89. !self.has_strong_zero2one
  90. }
  91. fn can_push_strong_zero2one_normally(&self) -> bool {
  92. !self.has_pushed_node
  93. }
  94. fn did_push_strong_zero2one(&mut self) {
  95. assert!(self.should_push_strong_zero2one());
  96. assert!(self.can_push_strong_zero2one_normally());
  97. self.has_pushed_node = true;
  98. self.has_strong_zero2one = true;
  99. }
  100. fn did_push_strong_zero2one_wrapper(&mut self) {
  101. assert!(self.should_push_strong_zero2one());
  102. assert!(!self.can_push_strong_zero2one_normally());
  103. self.has_pushed_wrapper = true;
  104. self.has_strong_zero2one = true;
  105. }
  106. }
  107. struct CountState {
  108. /// The reference count.
  109. count: usize,
  110. /// Whether the process that owns this node thinks that we hold a refcount on it. (Note that
  111. /// even if count is greater than one, we only increment it once in the owning process.)
  112. has_count: bool,
  113. }
  114. impl CountState {
  115. fn new() -> Self {
  116. Self {
  117. count: 0,
  118. has_count: false,
  119. }
  120. }
  121. }
  122. struct NodeInner {
  123. /// Strong refcounts held on this node by `NodeRef` objects.
  124. strong: CountState,
  125. /// Weak refcounts held on this node by `NodeRef` objects.
  126. weak: CountState,
  127. delivery_state: DeliveryState,
  128. /// The binder driver guarantees that oneway transactions sent to the same node are serialized,
  129. /// that is, userspace will not be given the next one until it has finished processing the
  130. /// previous oneway transaction. This is done to avoid the case where two oneway transactions
  131. /// arrive in opposite order from the order in which they were sent. (E.g., they could be
  132. /// delivered to two different threads, which could appear as-if they were sent in opposite
  133. /// order.)
  134. ///
  135. /// To fix that, we store pending oneway transactions in a separate list in the node, and don't
  136. /// deliver the next oneway transaction until userspace signals that it has finished processing
  137. /// the previous oneway transaction by calling the `BC_FREE_BUFFER` ioctl.
  138. oneway_todo: List<DTRWrap<Transaction>>,
  139. /// Keeps track of whether this node has a pending oneway transaction.
  140. ///
  141. /// When this is true, incoming oneway transactions are stored in `oneway_todo`, instead of
  142. /// being delivered directly to the process.
  143. has_oneway_transaction: bool,
  144. /// List of processes to deliver a notification to when this node is destroyed (usually due to
  145. /// the process dying).
  146. death_list: List<DTRWrap<NodeDeath>, 1>,
  147. /// List of processes to deliver freeze notifications to.
  148. freeze_list: KVVec<Arc<Process>>,
  149. /// The number of active BR_INCREFS or BR_ACQUIRE operations. (should be maximum two)
  150. ///
  151. /// If this is non-zero, then we postpone any BR_RELEASE or BR_DECREFS notifications until the
  152. /// active operations have ended. This avoids the situation an increment and decrement get
  153. /// reordered from userspace's perspective.
  154. active_inc_refs: u8,
  155. /// List of `NodeRefInfo` objects that reference this node.
  156. refs: List<NodeRefInfo, { NodeRefInfo::LIST_NODE }>,
  157. }
  158. use kernel::bindings::rb_node_layout;
  159. use mem::offset_of;
  160. pub(crate) const NODE_LAYOUT: rb_node_layout = rb_node_layout {
  161. arc_offset: Arc::<Node>::DATA_OFFSET + offset_of!(DTRWrap<Node>, wrapped),
  162. debug_id: offset_of!(Node, debug_id),
  163. ptr: offset_of!(Node, ptr),
  164. };
  165. #[pin_data]
  166. pub(crate) struct Node {
  167. pub(crate) debug_id: usize,
  168. ptr: u64,
  169. pub(crate) cookie: u64,
  170. pub(crate) flags: u32,
  171. pub(crate) owner: Arc<Process>,
  172. inner: LockedBy<NodeInner, ProcessInner>,
  173. #[pin]
  174. links_track: AtomicTracker,
  175. }
  176. kernel::list::impl_list_arc_safe! {
  177. impl ListArcSafe<0> for Node {
  178. tracked_by links_track: AtomicTracker;
  179. }
  180. }
  181. // Make `oneway_todo` work.
  182. kernel::list::impl_list_item! {
  183. impl ListItem<0> for DTRWrap<Transaction> {
  184. using ListLinks { self.links.inner };
  185. }
  186. }
  187. impl Node {
  188. pub(crate) fn new(
  189. ptr: u64,
  190. cookie: u64,
  191. flags: u32,
  192. owner: Arc<Process>,
  193. ) -> impl PinInit<Self> {
  194. pin_init!(Self {
  195. inner: LockedBy::new(
  196. &owner.inner,
  197. NodeInner {
  198. strong: CountState::new(),
  199. weak: CountState::new(),
  200. delivery_state: DeliveryState {
  201. has_pushed_node: false,
  202. has_pushed_wrapper: false,
  203. has_weak_zero2one: false,
  204. has_strong_zero2one: false,
  205. },
  206. death_list: List::new(),
  207. oneway_todo: List::new(),
  208. freeze_list: KVVec::new(),
  209. has_oneway_transaction: false,
  210. active_inc_refs: 0,
  211. refs: List::new(),
  212. },
  213. ),
  214. debug_id: super::next_debug_id(),
  215. ptr,
  216. cookie,
  217. flags,
  218. owner,
  219. links_track <- AtomicTracker::new(),
  220. })
  221. }
  222. pub(crate) fn has_oneway_transaction(&self, owner_inner: &mut ProcessInner) -> bool {
  223. let inner = self.inner.access_mut(owner_inner);
  224. inner.has_oneway_transaction
  225. }
  226. #[inline(never)]
  227. pub(crate) fn full_debug_print(
  228. &self,
  229. m: &SeqFile,
  230. owner_inner: &mut ProcessInner,
  231. ) -> Result<()> {
  232. let inner = self.inner.access_mut(owner_inner);
  233. seq_print!(
  234. m,
  235. " node {}: u{:016x} c{:016x} hs {} hw {} cs {} cw {}",
  236. self.debug_id,
  237. self.ptr,
  238. self.cookie,
  239. inner.strong.has_count,
  240. inner.weak.has_count,
  241. inner.strong.count,
  242. inner.weak.count,
  243. );
  244. if !inner.refs.is_empty() {
  245. seq_print!(m, " proc");
  246. for node_ref in &inner.refs {
  247. seq_print!(m, " {}", node_ref.process.task.pid());
  248. }
  249. }
  250. seq_print!(m, "\n");
  251. for t in &inner.oneway_todo {
  252. t.debug_print_inner(m, " pending async transaction ");
  253. }
  254. Ok(())
  255. }
  256. /// Insert the `NodeRef` into this `refs` list.
  257. ///
  258. /// # Safety
  259. ///
  260. /// It must be the case that `info.node_ref.node` is this node.
  261. pub(crate) unsafe fn insert_node_info(
  262. &self,
  263. info: ListArc<NodeRefInfo, { NodeRefInfo::LIST_NODE }>,
  264. ) {
  265. self.inner
  266. .access_mut(&mut self.owner.inner.lock())
  267. .refs
  268. .push_front(info);
  269. }
  270. /// Insert the `NodeRef` into this `refs` list.
  271. ///
  272. /// # Safety
  273. ///
  274. /// It must be the case that `info.node_ref.node` is this node.
  275. pub(crate) unsafe fn remove_node_info(
  276. &self,
  277. info: &NodeRefInfo,
  278. ) -> Option<ListArc<NodeRefInfo, { NodeRefInfo::LIST_NODE }>> {
  279. // SAFETY: We always insert `NodeRefInfo` objects into the `refs` list of the node that it
  280. // references in `info.node_ref.node`. That is this node, so `info` cannot possibly be in
  281. // the `refs` list of another node.
  282. unsafe {
  283. self.inner
  284. .access_mut(&mut self.owner.inner.lock())
  285. .refs
  286. .remove(info)
  287. }
  288. }
  289. /// An id that is unique across all binder nodes on the system. Used as the key in the
  290. /// `by_node` map.
  291. pub(crate) fn global_id(&self) -> usize {
  292. self as *const Node as usize
  293. }
  294. pub(crate) fn get_id(&self) -> (u64, u64) {
  295. (self.ptr, self.cookie)
  296. }
  297. pub(crate) fn add_death(
  298. &self,
  299. death: ListArc<DTRWrap<NodeDeath>, 1>,
  300. guard: &mut Guard<'_, ProcessInner, SpinLockBackend>,
  301. ) {
  302. self.inner.access_mut(guard).death_list.push_back(death);
  303. }
  304. pub(crate) fn inc_ref_done_locked(
  305. self: &DArc<Node>,
  306. _strong: bool,
  307. owner_inner: &mut ProcessInner,
  308. ) -> Option<DLArc<Node>> {
  309. let inner = self.inner.access_mut(owner_inner);
  310. if inner.active_inc_refs == 0 {
  311. pr_err!("inc_ref_done called when no active inc_refs");
  312. return None;
  313. }
  314. inner.active_inc_refs -= 1;
  315. if inner.active_inc_refs == 0 {
  316. // Having active inc_refs can inhibit dropping of ref-counts. Calculate whether we
  317. // would send a refcount decrement, and if so, tell the caller to schedule us.
  318. let strong = inner.strong.count > 0;
  319. let has_strong = inner.strong.has_count;
  320. let weak = strong || inner.weak.count > 0;
  321. let has_weak = inner.weak.has_count;
  322. let should_drop_weak = !weak && has_weak;
  323. let should_drop_strong = !strong && has_strong;
  324. // If we want to drop the ref-count again, tell the caller to schedule a work node for
  325. // that.
  326. let need_push = should_drop_weak || should_drop_strong;
  327. if need_push && inner.delivery_state.should_normal_push() {
  328. let list_arc = ListArc::try_from_arc(self.clone()).ok().unwrap();
  329. inner.delivery_state.did_normal_push();
  330. Some(list_arc)
  331. } else {
  332. None
  333. }
  334. } else {
  335. None
  336. }
  337. }
  338. pub(crate) fn update_refcount_locked(
  339. self: &DArc<Node>,
  340. inc: bool,
  341. strong: bool,
  342. count: usize,
  343. owner_inner: &mut ProcessInner,
  344. ) -> Option<DLArc<Node>> {
  345. let is_dead = owner_inner.is_dead;
  346. let inner = self.inner.access_mut(owner_inner);
  347. // Get a reference to the state we'll update.
  348. let state = if strong {
  349. &mut inner.strong
  350. } else {
  351. &mut inner.weak
  352. };
  353. // Update the count and determine whether we need to push work.
  354. let need_push = if inc {
  355. state.count += count;
  356. // TODO: This method shouldn't be used for zero-to-one increments.
  357. !is_dead && !state.has_count
  358. } else {
  359. if state.count < count {
  360. pr_err!("Failure: refcount underflow!");
  361. return None;
  362. }
  363. state.count -= count;
  364. !is_dead && state.count == 0 && state.has_count
  365. };
  366. if need_push && inner.delivery_state.should_normal_push() {
  367. let list_arc = ListArc::try_from_arc(self.clone()).ok().unwrap();
  368. inner.delivery_state.did_normal_push();
  369. Some(list_arc)
  370. } else {
  371. None
  372. }
  373. }
  374. pub(crate) fn incr_refcount_allow_zero2one(
  375. self: &DArc<Self>,
  376. strong: bool,
  377. owner_inner: &mut ProcessInner,
  378. ) -> Result<Option<DLArc<Node>>, CouldNotDeliverCriticalIncrement> {
  379. let is_dead = owner_inner.is_dead;
  380. let inner = self.inner.access_mut(owner_inner);
  381. // Get a reference to the state we'll update.
  382. let state = if strong {
  383. &mut inner.strong
  384. } else {
  385. &mut inner.weak
  386. };
  387. // Update the count and determine whether we need to push work.
  388. state.count += 1;
  389. if is_dead || state.has_count {
  390. return Ok(None);
  391. }
  392. // Userspace needs to be notified of this.
  393. if !strong && inner.delivery_state.should_push_weak_zero2one() {
  394. assert!(inner.delivery_state.can_push_weak_zero2one_normally());
  395. let list_arc = ListArc::try_from_arc(self.clone()).ok().unwrap();
  396. inner.delivery_state.did_push_weak_zero2one();
  397. Ok(Some(list_arc))
  398. } else if strong && inner.delivery_state.should_push_strong_zero2one() {
  399. if inner.delivery_state.can_push_strong_zero2one_normally() {
  400. let list_arc = ListArc::try_from_arc(self.clone()).ok().unwrap();
  401. inner.delivery_state.did_push_strong_zero2one();
  402. Ok(Some(list_arc))
  403. } else {
  404. state.count -= 1;
  405. Err(CouldNotDeliverCriticalIncrement)
  406. }
  407. } else {
  408. // Work is already pushed, and we don't need to push again.
  409. Ok(None)
  410. }
  411. }
  412. pub(crate) fn incr_refcount_allow_zero2one_with_wrapper(
  413. self: &DArc<Self>,
  414. strong: bool,
  415. wrapper: CritIncrWrapper,
  416. owner_inner: &mut ProcessInner,
  417. ) -> Option<DLArc<dyn DeliverToRead>> {
  418. match self.incr_refcount_allow_zero2one(strong, owner_inner) {
  419. Ok(Some(node)) => Some(node as _),
  420. Ok(None) => None,
  421. Err(CouldNotDeliverCriticalIncrement) => {
  422. assert!(strong);
  423. let inner = self.inner.access_mut(owner_inner);
  424. inner.strong.count += 1;
  425. inner.delivery_state.did_push_strong_zero2one_wrapper();
  426. Some(wrapper.init(self.clone()))
  427. }
  428. }
  429. }
  430. pub(crate) fn update_refcount(self: &DArc<Self>, inc: bool, count: usize, strong: bool) {
  431. self.owner
  432. .inner
  433. .lock()
  434. .update_node_refcount(self, inc, strong, count, None);
  435. }
  436. pub(crate) fn populate_counts(
  437. &self,
  438. out: &mut BinderNodeInfoForRef,
  439. guard: &Guard<'_, ProcessInner, SpinLockBackend>,
  440. ) {
  441. let inner = self.inner.access(guard);
  442. out.strong_count = inner.strong.count as _;
  443. out.weak_count = inner.weak.count as _;
  444. }
  445. pub(crate) fn populate_debug_info(
  446. &self,
  447. out: &mut BinderNodeDebugInfo,
  448. guard: &Guard<'_, ProcessInner, SpinLockBackend>,
  449. ) {
  450. out.ptr = self.ptr as _;
  451. out.cookie = self.cookie as _;
  452. let inner = self.inner.access(guard);
  453. if inner.strong.has_count {
  454. out.has_strong_ref = 1;
  455. }
  456. if inner.weak.has_count {
  457. out.has_weak_ref = 1;
  458. }
  459. }
  460. pub(crate) fn force_has_count(&self, guard: &mut Guard<'_, ProcessInner, SpinLockBackend>) {
  461. let inner = self.inner.access_mut(guard);
  462. inner.strong.has_count = true;
  463. inner.weak.has_count = true;
  464. }
  465. fn write(&self, writer: &mut BinderReturnWriter<'_>, code: u32) -> Result {
  466. writer.write_code(code)?;
  467. writer.write_payload(&self.ptr)?;
  468. writer.write_payload(&self.cookie)?;
  469. Ok(())
  470. }
  471. pub(crate) fn submit_oneway(
  472. &self,
  473. transaction: DLArc<Transaction>,
  474. guard: &mut Guard<'_, ProcessInner, SpinLockBackend>,
  475. ) -> Result<(), (BinderError, DLArc<dyn DeliverToRead>)> {
  476. if guard.is_dead {
  477. return Err((BinderError::new_dead(), transaction));
  478. }
  479. let inner = self.inner.access_mut(guard);
  480. if inner.has_oneway_transaction {
  481. inner.oneway_todo.push_back(transaction);
  482. } else {
  483. inner.has_oneway_transaction = true;
  484. guard.push_work(transaction)?;
  485. }
  486. Ok(())
  487. }
  488. pub(crate) fn release(&self) {
  489. let mut guard = self.owner.inner.lock();
  490. while let Some(work) = self.inner.access_mut(&mut guard).oneway_todo.pop_front() {
  491. drop(guard);
  492. work.into_arc().cancel();
  493. guard = self.owner.inner.lock();
  494. }
  495. while let Some(death) = self.inner.access_mut(&mut guard).death_list.pop_front() {
  496. drop(guard);
  497. death.into_arc().set_dead();
  498. guard = self.owner.inner.lock();
  499. }
  500. }
  501. pub(crate) fn pending_oneway_finished(&self) {
  502. let mut guard = self.owner.inner.lock();
  503. if guard.is_dead {
  504. // Cleanup will happen in `Process::deferred_release`.
  505. return;
  506. }
  507. let inner = self.inner.access_mut(&mut guard);
  508. let transaction = inner.oneway_todo.pop_front();
  509. inner.has_oneway_transaction = transaction.is_some();
  510. if let Some(transaction) = transaction {
  511. match guard.push_work(transaction) {
  512. Ok(()) => {}
  513. Err((_err, work)) => {
  514. // Process is dead.
  515. // This shouldn't happen due to the `is_dead` check, but if it does, just drop
  516. // the transaction and return.
  517. drop(guard);
  518. drop(work);
  519. }
  520. }
  521. }
  522. }
  523. /// Finds an outdated transaction that the given transaction can replace.
  524. ///
  525. /// If one is found, it is removed from the list and returned.
  526. pub(crate) fn take_outdated_transaction(
  527. &self,
  528. new: &Transaction,
  529. guard: &mut Guard<'_, ProcessInner, SpinLockBackend>,
  530. ) -> Option<DLArc<Transaction>> {
  531. let inner = self.inner.access_mut(guard);
  532. let mut cursor = inner.oneway_todo.cursor_front();
  533. while let Some(next) = cursor.peek_next() {
  534. if new.can_replace(&next) {
  535. return Some(next.remove());
  536. }
  537. cursor.move_next();
  538. }
  539. None
  540. }
  541. /// This is split into a separate function since it's called by both `Node::do_work` and
  542. /// `NodeWrapper::do_work`.
  543. fn do_work_locked(
  544. &self,
  545. writer: &mut BinderReturnWriter<'_>,
  546. mut guard: Guard<'_, ProcessInner, SpinLockBackend>,
  547. ) -> Result<bool> {
  548. let inner = self.inner.access_mut(&mut guard);
  549. let strong = inner.strong.count > 0;
  550. let has_strong = inner.strong.has_count;
  551. let weak = strong || inner.weak.count > 0;
  552. let has_weak = inner.weak.has_count;
  553. if weak && !has_weak {
  554. inner.weak.has_count = true;
  555. inner.active_inc_refs += 1;
  556. }
  557. if strong && !has_strong {
  558. inner.strong.has_count = true;
  559. inner.active_inc_refs += 1;
  560. }
  561. let no_active_inc_refs = inner.active_inc_refs == 0;
  562. let should_drop_weak = no_active_inc_refs && (!weak && has_weak);
  563. let should_drop_strong = no_active_inc_refs && (!strong && has_strong);
  564. if should_drop_weak {
  565. inner.weak.has_count = false;
  566. }
  567. if should_drop_strong {
  568. inner.strong.has_count = false;
  569. }
  570. if no_active_inc_refs && !weak {
  571. // Remove the node if there are no references to it.
  572. guard.remove_node(self.ptr);
  573. }
  574. drop(guard);
  575. if weak && !has_weak {
  576. self.write(writer, BR_INCREFS)?;
  577. }
  578. if strong && !has_strong {
  579. self.write(writer, BR_ACQUIRE)?;
  580. }
  581. if should_drop_strong {
  582. self.write(writer, BR_RELEASE)?;
  583. }
  584. if should_drop_weak {
  585. self.write(writer, BR_DECREFS)?;
  586. }
  587. Ok(true)
  588. }
  589. pub(crate) fn add_freeze_listener(
  590. &self,
  591. process: &Arc<Process>,
  592. flags: kernel::alloc::Flags,
  593. ) -> Result {
  594. let mut vec_alloc = KVVec::<Arc<Process>>::new();
  595. loop {
  596. let mut guard = self.owner.inner.lock();
  597. // Do not check for `guard.dead`. The `dead` flag that matters here is the owner of the
  598. // listener, no the target.
  599. let inner = self.inner.access_mut(&mut guard);
  600. let len = inner.freeze_list.len();
  601. if len >= inner.freeze_list.capacity() {
  602. if len >= vec_alloc.capacity() {
  603. drop(guard);
  604. vec_alloc = KVVec::with_capacity((1 + len).next_power_of_two(), flags)?;
  605. continue;
  606. }
  607. mem::swap(&mut inner.freeze_list, &mut vec_alloc);
  608. for elem in vec_alloc.drain_all() {
  609. inner.freeze_list.push_within_capacity(elem)?;
  610. }
  611. }
  612. inner.freeze_list.push_within_capacity(process.clone())?;
  613. return Ok(());
  614. }
  615. }
  616. pub(crate) fn remove_freeze_listener(&self, p: &Arc<Process>) {
  617. let _unused_capacity;
  618. let mut guard = self.owner.inner.lock();
  619. let inner = self.inner.access_mut(&mut guard);
  620. let len = inner.freeze_list.len();
  621. inner.freeze_list.retain(|proc| !Arc::ptr_eq(proc, p));
  622. if len == inner.freeze_list.len() {
  623. pr_warn!(
  624. "Could not remove freeze listener for {}\n",
  625. p.pid_in_current_ns()
  626. );
  627. }
  628. if inner.freeze_list.is_empty() {
  629. _unused_capacity = mem::take(&mut inner.freeze_list);
  630. }
  631. }
  632. pub(crate) fn freeze_list<'a>(&'a self, guard: &'a ProcessInner) -> &'a [Arc<Process>] {
  633. &self.inner.access(guard).freeze_list
  634. }
  635. }
  636. impl DeliverToRead for Node {
  637. fn do_work(
  638. self: DArc<Self>,
  639. _thread: &Thread,
  640. writer: &mut BinderReturnWriter<'_>,
  641. ) -> Result<bool> {
  642. let mut owner_inner = self.owner.inner.lock();
  643. let inner = self.inner.access_mut(&mut owner_inner);
  644. assert!(inner.delivery_state.has_pushed_node);
  645. if inner.delivery_state.has_pushed_wrapper {
  646. // If the wrapper is scheduled, then we are either a normal push or weak zero2one
  647. // increment, and the wrapper is a strong zero2one increment, so the wrapper always
  648. // takes precedence over us.
  649. assert!(inner.delivery_state.has_strong_zero2one);
  650. inner.delivery_state.has_pushed_node = false;
  651. inner.delivery_state.has_weak_zero2one = false;
  652. return Ok(true);
  653. }
  654. inner.delivery_state.has_pushed_node = false;
  655. inner.delivery_state.has_weak_zero2one = false;
  656. inner.delivery_state.has_strong_zero2one = false;
  657. self.do_work_locked(writer, owner_inner)
  658. }
  659. fn cancel(self: DArc<Self>) {}
  660. fn should_sync_wakeup(&self) -> bool {
  661. false
  662. }
  663. #[inline(never)]
  664. fn debug_print(&self, m: &SeqFile, prefix: &str, _tprefix: &str) -> Result<()> {
  665. seq_print!(
  666. m,
  667. "{}node work {}: u{:016x} c{:016x}\n",
  668. prefix,
  669. self.debug_id,
  670. self.ptr,
  671. self.cookie,
  672. );
  673. Ok(())
  674. }
  675. }
  676. /// Represents something that holds one or more ref-counts to a `Node`.
  677. ///
  678. /// Whenever process A holds a refcount to a node owned by a different process B, then process A
  679. /// will store a `NodeRef` that refers to the `Node` in process B. When process A releases the
  680. /// refcount, we destroy the NodeRef, which decrements the ref-count in process A.
  681. ///
  682. /// This type is also used for some other cases. For example, a transaction allocation holds a
  683. /// refcount on the target node, and this is implemented by storing a `NodeRef` in the allocation
  684. /// so that the destructor of the allocation will drop a refcount of the `Node`.
  685. pub(crate) struct NodeRef {
  686. pub(crate) node: DArc<Node>,
  687. /// How many times does this NodeRef hold a refcount on the Node?
  688. strong_node_count: usize,
  689. weak_node_count: usize,
  690. /// How many times does userspace hold a refcount on this NodeRef?
  691. strong_count: usize,
  692. weak_count: usize,
  693. }
  694. impl NodeRef {
  695. pub(crate) fn new(node: DArc<Node>, strong_count: usize, weak_count: usize) -> Self {
  696. Self {
  697. node,
  698. strong_node_count: strong_count,
  699. weak_node_count: weak_count,
  700. strong_count,
  701. weak_count,
  702. }
  703. }
  704. pub(crate) fn absorb(&mut self, mut other: Self) {
  705. assert!(
  706. Arc::ptr_eq(&self.node, &other.node),
  707. "absorb called with differing nodes"
  708. );
  709. self.strong_node_count += other.strong_node_count;
  710. self.weak_node_count += other.weak_node_count;
  711. self.strong_count += other.strong_count;
  712. self.weak_count += other.weak_count;
  713. other.strong_count = 0;
  714. other.weak_count = 0;
  715. other.strong_node_count = 0;
  716. other.weak_node_count = 0;
  717. if self.strong_node_count >= 2 || self.weak_node_count >= 2 {
  718. let mut guard = self.node.owner.inner.lock();
  719. let inner = self.node.inner.access_mut(&mut guard);
  720. if self.strong_node_count >= 2 {
  721. inner.strong.count -= self.strong_node_count - 1;
  722. self.strong_node_count = 1;
  723. assert_ne!(inner.strong.count, 0);
  724. }
  725. if self.weak_node_count >= 2 {
  726. inner.weak.count -= self.weak_node_count - 1;
  727. self.weak_node_count = 1;
  728. assert_ne!(inner.weak.count, 0);
  729. }
  730. }
  731. }
  732. pub(crate) fn get_count(&self) -> (usize, usize) {
  733. (self.strong_count, self.weak_count)
  734. }
  735. pub(crate) fn clone(&self, strong: bool) -> Result<NodeRef> {
  736. if strong && self.strong_count == 0 {
  737. return Err(EINVAL);
  738. }
  739. Ok(self
  740. .node
  741. .owner
  742. .inner
  743. .lock()
  744. .new_node_ref(self.node.clone(), strong, None))
  745. }
  746. /// Updates (increments or decrements) the number of references held against the node. If the
  747. /// count being updated transitions from 0 to 1 or from 1 to 0, the node is notified by having
  748. /// its `update_refcount` function called.
  749. ///
  750. /// Returns whether `self` should be removed (when both counts are zero).
  751. pub(crate) fn update(&mut self, inc: bool, strong: bool) -> bool {
  752. if strong && self.strong_count == 0 {
  753. return false;
  754. }
  755. let (count, node_count, other_count) = if strong {
  756. (
  757. &mut self.strong_count,
  758. &mut self.strong_node_count,
  759. self.weak_count,
  760. )
  761. } else {
  762. (
  763. &mut self.weak_count,
  764. &mut self.weak_node_count,
  765. self.strong_count,
  766. )
  767. };
  768. if inc {
  769. if *count == 0 {
  770. *node_count = 1;
  771. self.node.update_refcount(true, 1, strong);
  772. }
  773. *count += 1;
  774. } else {
  775. if *count == 0 {
  776. pr_warn!(
  777. "pid {} performed invalid decrement on ref\n",
  778. kernel::current!().pid()
  779. );
  780. return false;
  781. }
  782. *count -= 1;
  783. if *count == 0 {
  784. self.node.update_refcount(false, *node_count, strong);
  785. *node_count = 0;
  786. return other_count == 0;
  787. }
  788. }
  789. false
  790. }
  791. }
  792. impl Drop for NodeRef {
  793. // This destructor is called conditionally from `Allocation::drop`. That branch is often
  794. // mispredicted. Inlining this method call reduces the cost of those branch mispredictions.
  795. #[inline(always)]
  796. fn drop(&mut self) {
  797. if self.strong_node_count > 0 {
  798. self.node
  799. .update_refcount(false, self.strong_node_count, true);
  800. }
  801. if self.weak_node_count > 0 {
  802. self.node
  803. .update_refcount(false, self.weak_node_count, false);
  804. }
  805. }
  806. }
  807. struct NodeDeathInner {
  808. dead: bool,
  809. cleared: bool,
  810. notification_done: bool,
  811. /// Indicates whether the normal flow was interrupted by removing the handle. In this case, we
  812. /// need behave as if the death notification didn't exist (i.e., we don't deliver anything to
  813. /// the user.
  814. aborted: bool,
  815. }
  816. /// Used to deliver notifications when a process dies.
  817. ///
  818. /// A process can request to be notified when a process dies using `BC_REQUEST_DEATH_NOTIFICATION`.
  819. /// This will make the driver send a `BR_DEAD_BINDER` to userspace when the process dies (or
  820. /// immediately if it is already dead). Userspace is supposed to respond with `BC_DEAD_BINDER_DONE`
  821. /// once it has processed the notification.
  822. ///
  823. /// Userspace can unregister from death notifications using the `BC_CLEAR_DEATH_NOTIFICATION`
  824. /// command. In this case, the kernel will respond with `BR_CLEAR_DEATH_NOTIFICATION_DONE` once the
  825. /// notification has been removed. Note that if the remote process dies before the kernel has
  826. /// responded with `BR_CLEAR_DEATH_NOTIFICATION_DONE`, then the kernel will still send a
  827. /// `BR_DEAD_BINDER`, which userspace must be able to process. In this case, the kernel will wait
  828. /// for the `BC_DEAD_BINDER_DONE` command before it sends `BR_CLEAR_DEATH_NOTIFICATION_DONE`.
  829. ///
  830. /// Note that even if the kernel sends a `BR_DEAD_BINDER`, this does not remove the death
  831. /// notification. Userspace must still remove it manually using `BC_CLEAR_DEATH_NOTIFICATION`.
  832. ///
  833. /// If a process uses `BC_RELEASE` to destroy its last refcount on a node that has an active death
  834. /// registration, then the death registration is immediately deleted (we implement this using the
  835. /// `aborted` field). However, userspace is not supposed to delete a `NodeRef` without first
  836. /// deregistering death notifications, so this codepath is not executed under normal circumstances.
  837. #[pin_data]
  838. pub(crate) struct NodeDeath {
  839. node: DArc<Node>,
  840. process: Arc<Process>,
  841. pub(crate) cookie: u64,
  842. #[pin]
  843. links_track: AtomicTracker<0>,
  844. /// Used by the owner `Node` to store a list of registered death notifications.
  845. ///
  846. /// # Invariants
  847. ///
  848. /// Only ever used with the `death_list` list of `self.node`.
  849. #[pin]
  850. death_links: ListLinks<1>,
  851. /// Used by the process to keep track of the death notifications for which we have sent a
  852. /// `BR_DEAD_BINDER` but not yet received a `BC_DEAD_BINDER_DONE`.
  853. ///
  854. /// # Invariants
  855. ///
  856. /// Only ever used with the `delivered_deaths` list of `self.process`.
  857. #[pin]
  858. delivered_links: ListLinks<2>,
  859. #[pin]
  860. delivered_links_track: AtomicTracker<2>,
  861. #[pin]
  862. inner: SpinLock<NodeDeathInner>,
  863. }
  864. impl NodeDeath {
  865. /// Constructs a new node death notification object.
  866. pub(crate) fn new(
  867. node: DArc<Node>,
  868. process: Arc<Process>,
  869. cookie: u64,
  870. ) -> impl PinInit<DTRWrap<Self>> {
  871. DTRWrap::new(pin_init!(
  872. Self {
  873. node,
  874. process,
  875. cookie,
  876. links_track <- AtomicTracker::new(),
  877. death_links <- ListLinks::new(),
  878. delivered_links <- ListLinks::new(),
  879. delivered_links_track <- AtomicTracker::new(),
  880. inner <- kernel::new_spinlock!(NodeDeathInner {
  881. dead: false,
  882. cleared: false,
  883. notification_done: false,
  884. aborted: false,
  885. }, "NodeDeath::inner"),
  886. }
  887. ))
  888. }
  889. /// Sets the cleared flag to `true`.
  890. ///
  891. /// It removes `self` from the node's death notification list if needed.
  892. ///
  893. /// Returns whether it needs to be queued.
  894. pub(crate) fn set_cleared(self: &DArc<Self>, abort: bool) -> bool {
  895. let (needs_removal, needs_queueing) = {
  896. // Update state and determine if we need to queue a work item. We only need to do it
  897. // when the node is not dead or if the user already completed the death notification.
  898. let mut inner = self.inner.lock();
  899. if abort {
  900. inner.aborted = true;
  901. }
  902. if inner.cleared {
  903. // Already cleared.
  904. return false;
  905. }
  906. inner.cleared = true;
  907. (!inner.dead, !inner.dead || inner.notification_done)
  908. };
  909. // Remove death notification from node.
  910. if needs_removal {
  911. let mut owner_inner = self.node.owner.inner.lock();
  912. let node_inner = self.node.inner.access_mut(&mut owner_inner);
  913. // SAFETY: A `NodeDeath` is never inserted into the death list of any node other than
  914. // its owner, so it is either in this death list or in no death list.
  915. unsafe { node_inner.death_list.remove(self) };
  916. }
  917. needs_queueing
  918. }
  919. /// Sets the 'notification done' flag to `true`.
  920. pub(crate) fn set_notification_done(self: DArc<Self>, thread: &Thread) {
  921. let needs_queueing = {
  922. let mut inner = self.inner.lock();
  923. inner.notification_done = true;
  924. inner.cleared
  925. };
  926. if needs_queueing {
  927. if let Some(death) = ListArc::try_from_arc_or_drop(self) {
  928. let _ = thread.push_work_if_looper(death);
  929. }
  930. }
  931. }
  932. /// Sets the 'dead' flag to `true` and queues work item if needed.
  933. pub(crate) fn set_dead(self: DArc<Self>) {
  934. let needs_queueing = {
  935. let mut inner = self.inner.lock();
  936. if inner.cleared {
  937. false
  938. } else {
  939. inner.dead = true;
  940. true
  941. }
  942. };
  943. if needs_queueing {
  944. // Push the death notification to the target process. There is nothing else to do if
  945. // it's already dead.
  946. if let Some(death) = ListArc::try_from_arc_or_drop(self) {
  947. let process = death.process.clone();
  948. let _ = process.push_work(death);
  949. }
  950. }
  951. }
  952. }
  953. kernel::list::impl_list_arc_safe! {
  954. impl ListArcSafe<0> for NodeDeath {
  955. tracked_by links_track: AtomicTracker;
  956. }
  957. }
  958. kernel::list::impl_list_arc_safe! {
  959. impl ListArcSafe<1> for DTRWrap<NodeDeath> { untracked; }
  960. }
  961. kernel::list::impl_list_item! {
  962. impl ListItem<1> for DTRWrap<NodeDeath> {
  963. using ListLinks { self.wrapped.death_links };
  964. }
  965. }
  966. kernel::list::impl_list_arc_safe! {
  967. impl ListArcSafe<2> for DTRWrap<NodeDeath> {
  968. tracked_by wrapped: NodeDeath;
  969. }
  970. }
  971. kernel::list::impl_list_arc_safe! {
  972. impl ListArcSafe<2> for NodeDeath {
  973. tracked_by delivered_links_track: AtomicTracker<2>;
  974. }
  975. }
  976. kernel::list::impl_list_item! {
  977. impl ListItem<2> for DTRWrap<NodeDeath> {
  978. using ListLinks { self.wrapped.delivered_links };
  979. }
  980. }
  981. impl DeliverToRead for NodeDeath {
  982. fn do_work(
  983. self: DArc<Self>,
  984. _thread: &Thread,
  985. writer: &mut BinderReturnWriter<'_>,
  986. ) -> Result<bool> {
  987. let done = {
  988. let inner = self.inner.lock();
  989. if inner.aborted {
  990. return Ok(true);
  991. }
  992. inner.cleared && (!inner.dead || inner.notification_done)
  993. };
  994. let cookie = self.cookie;
  995. let cmd = if done {
  996. BR_CLEAR_DEATH_NOTIFICATION_DONE
  997. } else {
  998. let process = self.process.clone();
  999. let mut process_inner = process.inner.lock();
  1000. let inner = self.inner.lock();
  1001. if inner.aborted {
  1002. return Ok(true);
  1003. }
  1004. // We're still holding the inner lock, so it cannot be aborted while we insert it into
  1005. // the delivered list.
  1006. process_inner.death_delivered(self.clone());
  1007. BR_DEAD_BINDER
  1008. };
  1009. writer.write_code(cmd)?;
  1010. writer.write_payload(&cookie)?;
  1011. // DEAD_BINDER notifications can cause transactions, so stop processing work items when we
  1012. // get to a death notification.
  1013. Ok(cmd != BR_DEAD_BINDER)
  1014. }
  1015. fn cancel(self: DArc<Self>) {}
  1016. fn should_sync_wakeup(&self) -> bool {
  1017. false
  1018. }
  1019. #[inline(never)]
  1020. fn debug_print(&self, m: &SeqFile, prefix: &str, _tprefix: &str) -> Result<()> {
  1021. let inner = self.inner.lock();
  1022. let dead_binder = inner.dead && !inner.notification_done;
  1023. if dead_binder {
  1024. if inner.cleared {
  1025. seq_print!(m, "{}has cleared dead binder\n", prefix);
  1026. } else {
  1027. seq_print!(m, "{}has dead binder\n", prefix);
  1028. }
  1029. } else {
  1030. seq_print!(m, "{}has cleared death notification\n", prefix);
  1031. }
  1032. Ok(())
  1033. }
  1034. }