ThreadBlockers.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/BuiltinWrappers.h>
  7. #include <Kernel/Debug.h>
  8. #include <Kernel/FileSystem/OpenFileDescription.h>
  9. #include <Kernel/Net/Socket.h>
  10. #include <Kernel/Process.h>
  11. #include <Kernel/Scheduler.h>
  12. #include <Kernel/Thread.h>
  13. namespace Kernel {
  14. Thread::BlockTimeout::BlockTimeout(bool is_absolute, const Time* time, const Time* start_time, clockid_t clock_id)
  15. : m_clock_id(clock_id)
  16. , m_infinite(!time)
  17. {
  18. if (m_infinite)
  19. return;
  20. if (*time > Time::zero())
  21. m_time = *time;
  22. m_start_time = start_time ? *start_time : TimeManagement::the().current_time(clock_id);
  23. if (!is_absolute)
  24. m_time += m_start_time;
  25. }
  26. bool Thread::Blocker::add_to_blocker_set(Thread::BlockerSet& blocker_set, void* data)
  27. {
  28. VERIFY(!m_blocker_set);
  29. if (blocker_set.add_blocker(*this, data)) {
  30. m_blocker_set = &blocker_set;
  31. return true;
  32. }
  33. return false;
  34. }
  35. Thread::Blocker::~Blocker()
  36. {
  37. VERIFY(!m_lock.is_locked());
  38. if (m_blocker_set)
  39. m_blocker_set->remove_blocker(*this);
  40. }
  41. bool Thread::Blocker::setup_blocker()
  42. {
  43. return true;
  44. }
  45. void Thread::Blocker::begin_blocking(Badge<Thread>)
  46. {
  47. SpinlockLocker lock(m_lock);
  48. VERIFY(!m_is_blocking);
  49. m_is_blocking = true;
  50. }
  51. auto Thread::Blocker::end_blocking(Badge<Thread>, bool did_timeout) -> BlockResult
  52. {
  53. SpinlockLocker lock(m_lock);
  54. // if m_is_blocking is false here, some thread forced to
  55. // unblock us when we get here. This is only called from the
  56. // thread that was blocked.
  57. VERIFY(Thread::current() == m_thread);
  58. m_is_blocking = false;
  59. was_unblocked(did_timeout);
  60. return block_result();
  61. }
  62. Thread::JoinBlocker::JoinBlocker(Thread& joinee, ErrorOr<void>& try_join_result, void*& joinee_exit_value)
  63. : m_joinee(joinee)
  64. , m_joinee_exit_value(joinee_exit_value)
  65. , m_try_join_result(try_join_result)
  66. {
  67. }
  68. bool Thread::JoinBlocker::setup_blocker()
  69. {
  70. // We need to hold our lock to avoid a race where try_join succeeds
  71. // but the joinee is joining immediately
  72. SpinlockLocker lock(m_lock);
  73. bool should_block = true;
  74. m_try_join_result = m_joinee->try_join([&]() {
  75. if (!add_to_blocker_set(m_joinee->m_join_blocker_set))
  76. should_block = false;
  77. });
  78. if (m_try_join_result.is_error())
  79. return false;
  80. return should_block;
  81. }
  82. void Thread::JoinBlocker::will_unblock_immediately_without_blocking(UnblockImmediatelyReason reason)
  83. {
  84. // If we should have blocked but got here it must have been that the
  85. // timeout was already in the past. So we need to ask the BlockerSet
  86. // to supply us the information. We cannot hold the lock as unblock
  87. // could be called by the BlockerSet at any time!
  88. if (reason == UnblockImmediatelyReason::TimeoutInThePast) {
  89. m_joinee->m_join_blocker_set.try_unblock(*this);
  90. }
  91. }
  92. bool Thread::JoinBlocker::unblock(void* value, bool from_add_blocker)
  93. {
  94. {
  95. SpinlockLocker lock(m_lock);
  96. if (m_did_unblock)
  97. return false;
  98. m_did_unblock = true;
  99. m_joinee_exit_value = value;
  100. do_set_interrupted_by_death();
  101. }
  102. if (!from_add_blocker)
  103. unblock_from_blocker();
  104. return true;
  105. }
  106. Thread::WaitQueueBlocker::WaitQueueBlocker(WaitQueue& wait_queue, StringView block_reason)
  107. : m_wait_queue(wait_queue)
  108. , m_block_reason(block_reason)
  109. {
  110. }
  111. bool Thread::WaitQueueBlocker::setup_blocker()
  112. {
  113. return add_to_blocker_set(m_wait_queue);
  114. }
  115. Thread::WaitQueueBlocker::~WaitQueueBlocker()
  116. {
  117. }
  118. bool Thread::WaitQueueBlocker::unblock()
  119. {
  120. {
  121. SpinlockLocker lock(m_lock);
  122. if (m_did_unblock)
  123. return false;
  124. m_did_unblock = true;
  125. }
  126. unblock_from_blocker();
  127. return true;
  128. }
  129. Thread::FutexBlocker::FutexBlocker(FutexQueue& futex_queue, u32 bitset)
  130. : m_futex_queue(futex_queue)
  131. , m_bitset(bitset)
  132. {
  133. }
  134. bool Thread::FutexBlocker::setup_blocker()
  135. {
  136. return add_to_blocker_set(m_futex_queue);
  137. }
  138. Thread::FutexBlocker::~FutexBlocker()
  139. {
  140. }
  141. void Thread::FutexBlocker::finish_requeue(FutexQueue& futex_queue)
  142. {
  143. VERIFY(m_lock.is_locked_by_current_processor());
  144. set_blocker_set_raw_locked(&futex_queue);
  145. // We can now release the lock
  146. m_lock.unlock(m_relock_flags);
  147. }
  148. bool Thread::FutexBlocker::unblock_bitset(u32 bitset)
  149. {
  150. {
  151. SpinlockLocker lock(m_lock);
  152. if (m_did_unblock || (bitset != FUTEX_BITSET_MATCH_ANY && (m_bitset & bitset) == 0))
  153. return false;
  154. m_did_unblock = true;
  155. }
  156. unblock_from_blocker();
  157. return true;
  158. }
  159. bool Thread::FutexBlocker::unblock(bool force)
  160. {
  161. {
  162. SpinlockLocker lock(m_lock);
  163. if (m_did_unblock)
  164. return force;
  165. m_did_unblock = true;
  166. }
  167. unblock_from_blocker();
  168. return true;
  169. }
  170. Thread::OpenFileDescriptionBlocker::OpenFileDescriptionBlocker(OpenFileDescription& description, BlockFlags flags, BlockFlags& unblocked_flags)
  171. : m_blocked_description(description)
  172. , m_flags(flags)
  173. , m_unblocked_flags(unblocked_flags)
  174. {
  175. }
  176. bool Thread::OpenFileDescriptionBlocker::setup_blocker()
  177. {
  178. m_unblocked_flags = BlockFlags::None;
  179. return add_to_blocker_set(m_blocked_description->blocker_set());
  180. }
  181. bool Thread::OpenFileDescriptionBlocker::unblock_if_conditions_are_met(bool from_add_blocker, void*)
  182. {
  183. auto unblock_flags = m_blocked_description->should_unblock(m_flags);
  184. if (unblock_flags == BlockFlags::None)
  185. return false;
  186. {
  187. SpinlockLocker lock(m_lock);
  188. if (m_did_unblock)
  189. return false;
  190. m_did_unblock = true;
  191. m_unblocked_flags = unblock_flags;
  192. }
  193. if (!from_add_blocker)
  194. unblock_from_blocker();
  195. return true;
  196. }
  197. void Thread::OpenFileDescriptionBlocker::will_unblock_immediately_without_blocking(UnblockImmediatelyReason reason)
  198. {
  199. if (reason == UnblockImmediatelyReason::UnblockConditionAlreadyMet)
  200. return;
  201. // If we should have blocked but got here it must have been that the
  202. // timeout was already in the past. So we need to ask the BlockerSet
  203. // to supply us the information. We cannot hold the lock as unblock
  204. // could be called by the BlockerSet at any time!
  205. VERIFY(reason == UnblockImmediatelyReason::TimeoutInThePast);
  206. // Just call unblock_if_conditions_are_met here because we will query the file description
  207. // for the data and don't need any input from the FileBlockerSet.
  208. // However, it's possible that if timeout_in_past is true then FileBlockerSet
  209. // may call us at any given time, so our call to unblock here may fail.
  210. // Either way, unblock will be called at least once, which provides
  211. // all the data we need.
  212. unblock_if_conditions_are_met(false, nullptr);
  213. }
  214. const OpenFileDescription& Thread::OpenFileDescriptionBlocker::blocked_description() const
  215. {
  216. return m_blocked_description;
  217. }
  218. Thread::AcceptBlocker::AcceptBlocker(OpenFileDescription& description, BlockFlags& unblocked_flags)
  219. : OpenFileDescriptionBlocker(description, BlockFlags::Accept | BlockFlags::Exception, unblocked_flags)
  220. {
  221. }
  222. Thread::ConnectBlocker::ConnectBlocker(OpenFileDescription& description, BlockFlags& unblocked_flags)
  223. : OpenFileDescriptionBlocker(description, BlockFlags::Connect | BlockFlags::Exception, unblocked_flags)
  224. {
  225. }
  226. Thread::WriteBlocker::WriteBlocker(OpenFileDescription& description, BlockFlags& unblocked_flags)
  227. : OpenFileDescriptionBlocker(description, BlockFlags::Write | BlockFlags::Exception, unblocked_flags)
  228. {
  229. }
  230. auto Thread::WriteBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout&
  231. {
  232. auto& description = blocked_description();
  233. if (description.is_socket()) {
  234. auto& socket = *description.socket();
  235. if (socket.has_send_timeout()) {
  236. Time send_timeout = socket.send_timeout();
  237. m_timeout = BlockTimeout(false, &send_timeout, timeout.start_time(), timeout.clock_id());
  238. if (timeout.is_infinite() || (!m_timeout.is_infinite() && m_timeout.absolute_time() < timeout.absolute_time()))
  239. return m_timeout;
  240. }
  241. }
  242. return timeout;
  243. }
  244. Thread::ReadBlocker::ReadBlocker(OpenFileDescription& description, BlockFlags& unblocked_flags)
  245. : OpenFileDescriptionBlocker(description, BlockFlags::Read | BlockFlags::Exception, unblocked_flags)
  246. {
  247. }
  248. auto Thread::ReadBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout&
  249. {
  250. auto& description = blocked_description();
  251. if (description.is_socket()) {
  252. auto& socket = *description.socket();
  253. if (socket.has_receive_timeout()) {
  254. Time receive_timeout = socket.receive_timeout();
  255. m_timeout = BlockTimeout(false, &receive_timeout, timeout.start_time(), timeout.clock_id());
  256. if (timeout.is_infinite() || (!m_timeout.is_infinite() && m_timeout.absolute_time() < timeout.absolute_time()))
  257. return m_timeout;
  258. }
  259. }
  260. return timeout;
  261. }
  262. Thread::SleepBlocker::SleepBlocker(const BlockTimeout& deadline, Time* remaining)
  263. : m_deadline(deadline)
  264. , m_remaining(remaining)
  265. {
  266. }
  267. auto Thread::SleepBlocker::override_timeout(const BlockTimeout& timeout) -> const BlockTimeout&
  268. {
  269. VERIFY(timeout.is_infinite()); // A timeout should not be provided
  270. // To simplify things only use the sleep deadline.
  271. return m_deadline;
  272. }
  273. void Thread::SleepBlocker::will_unblock_immediately_without_blocking(UnblockImmediatelyReason reason)
  274. {
  275. // SleepBlocker::should_block should always return true, so timeout
  276. // in the past is the only valid case when this function is called
  277. VERIFY(reason == UnblockImmediatelyReason::TimeoutInThePast);
  278. calculate_remaining();
  279. }
  280. void Thread::SleepBlocker::was_unblocked(bool did_timeout)
  281. {
  282. Blocker::was_unblocked(did_timeout);
  283. calculate_remaining();
  284. }
  285. void Thread::SleepBlocker::calculate_remaining()
  286. {
  287. if (!m_remaining)
  288. return;
  289. auto time_now = TimeManagement::the().current_time(m_deadline.clock_id());
  290. if (time_now < m_deadline.absolute_time())
  291. *m_remaining = m_deadline.absolute_time() - time_now;
  292. else
  293. *m_remaining = {};
  294. }
  295. Thread::BlockResult Thread::SleepBlocker::block_result()
  296. {
  297. auto result = Blocker::block_result();
  298. if (result == Thread::BlockResult::InterruptedByTimeout)
  299. return Thread::BlockResult::WokeNormally;
  300. return result;
  301. }
  302. Thread::SelectBlocker::SelectBlocker(FDVector& fds)
  303. : m_fds(fds)
  304. {
  305. }
  306. bool Thread::SelectBlocker::setup_blocker()
  307. {
  308. bool should_block = true;
  309. for (auto& fd_entry : m_fds) {
  310. fd_entry.unblocked_flags = FileBlocker::BlockFlags::None;
  311. if (!should_block)
  312. continue;
  313. if (!fd_entry.description->blocker_set().add_blocker(*this, &fd_entry))
  314. should_block = false;
  315. }
  316. return should_block;
  317. }
  318. Thread::SelectBlocker::~SelectBlocker()
  319. {
  320. for (auto& fd_entry : m_fds)
  321. fd_entry.description->blocker_set().remove_blocker(*this);
  322. }
  323. void Thread::SelectBlocker::will_unblock_immediately_without_blocking(UnblockImmediatelyReason reason)
  324. {
  325. SpinlockLocker lock(m_lock);
  326. if (m_did_unblock)
  327. return;
  328. m_did_unblock = true;
  329. if (reason == UnblockImmediatelyReason::UnblockConditionAlreadyMet) {
  330. auto count = collect_unblocked_flags();
  331. VERIFY(count > 0);
  332. }
  333. }
  334. bool Thread::SelectBlocker::unblock_if_conditions_are_met(bool from_add_blocker, void* data)
  335. {
  336. VERIFY(data); // data is a pointer to an entry in the m_fds vector
  337. auto& fd_info = *static_cast<FDInfo*>(data);
  338. {
  339. SpinlockLocker lock(m_lock);
  340. if (m_did_unblock)
  341. return false;
  342. auto unblock_flags = fd_info.description->should_unblock(fd_info.block_flags);
  343. if (unblock_flags == BlockFlags::None)
  344. return false;
  345. m_did_unblock = true;
  346. // We need to store unblock_flags here, otherwise someone else
  347. // affecting this file descriptor could change the information
  348. // between now and when was_unblocked is called!
  349. fd_info.unblocked_flags = unblock_flags;
  350. }
  351. // Only do this once for the first one
  352. if (!from_add_blocker)
  353. unblock_from_blocker();
  354. return true;
  355. }
  356. size_t Thread::SelectBlocker::collect_unblocked_flags()
  357. {
  358. size_t count = 0;
  359. for (auto& fd_entry : m_fds) {
  360. VERIFY(fd_entry.block_flags != FileBlocker::BlockFlags::None);
  361. // unblock will have set at least the first descriptor's unblock
  362. // flags that triggered the unblock. Make sure we don't discard that
  363. // information as it may have changed by now!
  364. if (fd_entry.unblocked_flags == FileBlocker::BlockFlags::None)
  365. fd_entry.unblocked_flags = fd_entry.description->should_unblock(fd_entry.block_flags);
  366. if (fd_entry.unblocked_flags != FileBlocker::BlockFlags::None)
  367. count++;
  368. }
  369. return count;
  370. }
  371. void Thread::SelectBlocker::was_unblocked(bool did_timeout)
  372. {
  373. Blocker::was_unblocked(did_timeout);
  374. if (!did_timeout && !was_interrupted()) {
  375. {
  376. SpinlockLocker lock(m_lock);
  377. VERIFY(m_did_unblock);
  378. }
  379. size_t count = collect_unblocked_flags();
  380. // If we were blocked and didn't time out, we should have at least one unblocked fd!
  381. VERIFY(count > 0);
  382. }
  383. }
  384. Thread::SignalBlocker::SignalBlocker(sigset_t pending_set, siginfo_t& result)
  385. : m_pending_set(pending_set)
  386. , m_result(result)
  387. {
  388. }
  389. void Thread::SignalBlocker::will_unblock_immediately_without_blocking(UnblockImmediatelyReason unblock_immediately_reason)
  390. {
  391. if (unblock_immediately_reason != UnblockImmediatelyReason::TimeoutInThePast)
  392. return;
  393. // If the specified timeout is 0 the caller is simply trying to poll once for pending signals,
  394. // so simply calling check_pending_signals should populate the requested information.
  395. check_pending_signals(false);
  396. }
  397. bool Thread::SignalBlocker::setup_blocker()
  398. {
  399. return add_to_blocker_set(thread().m_signal_blocker_set);
  400. }
  401. bool Thread::SignalBlocker::check_pending_signals(bool from_add_blocker)
  402. {
  403. {
  404. SpinlockLocker lock(m_lock);
  405. if (m_did_unblock)
  406. return false;
  407. auto matching_pending_signal = bit_scan_forward(thread().pending_signals() & m_pending_set);
  408. if (matching_pending_signal == 0)
  409. return false;
  410. m_did_unblock = true;
  411. m_result = {};
  412. m_result.si_signo = matching_pending_signal;
  413. m_result.si_code = 0; // FIXME: How can we determine this?
  414. }
  415. if (!from_add_blocker)
  416. unblock_from_blocker();
  417. return true;
  418. }
  419. Thread::WaitBlockerSet::ProcessBlockInfo::ProcessBlockInfo(NonnullRefPtr<Process>&& process, WaitBlocker::UnblockFlags flags, u8 signal)
  420. : process(move(process))
  421. , flags(flags)
  422. , signal(signal)
  423. {
  424. }
  425. Thread::WaitBlockerSet::ProcessBlockInfo::~ProcessBlockInfo()
  426. {
  427. }
  428. void Thread::WaitBlockerSet::try_unblock(Thread::WaitBlocker& blocker)
  429. {
  430. SpinlockLocker lock(m_lock);
  431. // We if we have any processes pending
  432. for (size_t i = 0; i < m_processes.size(); i++) {
  433. auto& info = m_processes[i];
  434. // We need to call unblock as if we were called from add_blocker
  435. // so that we don't trigger a context switch by yielding!
  436. if (info.was_waited && blocker.is_wait())
  437. continue; // This state was already waited on, do not unblock
  438. if (blocker.unblock(info.process, info.flags, info.signal, true)) {
  439. if (blocker.is_wait()) {
  440. if (info.flags == Thread::WaitBlocker::UnblockFlags::Terminated) {
  441. m_processes.remove(i);
  442. dbgln_if(WAITBLOCK_DEBUG, "WaitBlockerSet[{}] terminated, remove {}", m_process, *info.process);
  443. } else {
  444. dbgln_if(WAITBLOCK_DEBUG, "WaitBlockerSet[{}] terminated, mark as waited {}", m_process, *info.process);
  445. info.was_waited = true;
  446. }
  447. }
  448. break;
  449. }
  450. }
  451. }
  452. void Thread::WaitBlockerSet::disowned_by_waiter(Process& process)
  453. {
  454. SpinlockLocker lock(m_lock);
  455. if (m_finalized)
  456. return;
  457. for (size_t i = 0; i < m_processes.size();) {
  458. auto& info = m_processes[i];
  459. if (info.process == &process) {
  460. unblock_all_blockers_whose_conditions_are_met_locked([&](Blocker& b, void*, bool&) {
  461. VERIFY(b.blocker_type() == Blocker::Type::Wait);
  462. auto& blocker = static_cast<WaitBlocker&>(b);
  463. bool did_unblock = blocker.unblock(info.process, WaitBlocker::UnblockFlags::Disowned, 0, false);
  464. VERIFY(did_unblock); // disowning must unblock everyone
  465. return true;
  466. });
  467. dbgln_if(WAITBLOCK_DEBUG, "WaitBlockerSet[{}] disowned {}", m_process, *info.process);
  468. m_processes.remove(i);
  469. continue;
  470. }
  471. i++;
  472. }
  473. }
  474. bool Thread::WaitBlockerSet::unblock(Process& process, WaitBlocker::UnblockFlags flags, u8 signal)
  475. {
  476. VERIFY(flags != WaitBlocker::UnblockFlags::Disowned);
  477. bool did_unblock_any = false;
  478. bool did_wait = false;
  479. bool was_waited_already = false;
  480. SpinlockLocker lock(m_lock);
  481. if (m_finalized)
  482. return false;
  483. if (flags != WaitBlocker::UnblockFlags::Terminated) {
  484. // First check if this state was already waited on
  485. for (auto& info : m_processes) {
  486. if (info.process == &process) {
  487. was_waited_already = info.was_waited;
  488. break;
  489. }
  490. }
  491. }
  492. unblock_all_blockers_whose_conditions_are_met_locked([&](Blocker& b, void*, bool&) {
  493. VERIFY(b.blocker_type() == Blocker::Type::Wait);
  494. auto& blocker = static_cast<WaitBlocker&>(b);
  495. if (was_waited_already && blocker.is_wait())
  496. return false; // This state was already waited on, do not unblock
  497. if (blocker.unblock(process, flags, signal, false)) {
  498. did_wait |= blocker.is_wait(); // anyone requesting a wait
  499. did_unblock_any = true;
  500. return true;
  501. }
  502. return false;
  503. });
  504. // If no one has waited (yet), or this wasn't a wait, or if it's anything other than
  505. // UnblockFlags::Terminated then add it to your list
  506. if (!did_unblock_any || !did_wait || flags != WaitBlocker::UnblockFlags::Terminated) {
  507. bool updated_existing = false;
  508. for (auto& info : m_processes) {
  509. if (info.process == &process) {
  510. VERIFY(info.flags != WaitBlocker::UnblockFlags::Terminated);
  511. info.flags = flags;
  512. info.signal = signal;
  513. info.was_waited = did_wait;
  514. dbgln_if(WAITBLOCK_DEBUG, "WaitBlockerSet[{}] update {} flags={}, waited={}", m_process, process, (int)flags, info.was_waited);
  515. updated_existing = true;
  516. break;
  517. }
  518. }
  519. if (!updated_existing) {
  520. dbgln_if(WAITBLOCK_DEBUG, "WaitBlockerSet[{}] add {} flags: {}", m_process, process, (int)flags);
  521. m_processes.append(ProcessBlockInfo(process, flags, signal));
  522. }
  523. }
  524. return did_unblock_any;
  525. }
  526. bool Thread::WaitBlockerSet::should_add_blocker(Blocker& b, void*)
  527. {
  528. // NOTE: m_lock is held already!
  529. if (m_finalized)
  530. return false;
  531. VERIFY(b.blocker_type() == Blocker::Type::Wait);
  532. auto& blocker = static_cast<WaitBlocker&>(b);
  533. // See if we can match any process immediately
  534. for (size_t i = 0; i < m_processes.size(); i++) {
  535. auto& info = m_processes[i];
  536. if (blocker.unblock(info.process, info.flags, info.signal, true)) {
  537. // Only remove the entry if UnblockFlags::Terminated
  538. if (info.flags == Thread::WaitBlocker::UnblockFlags::Terminated && blocker.is_wait())
  539. m_processes.remove(i);
  540. return false;
  541. }
  542. }
  543. return true;
  544. }
  545. void Thread::WaitBlockerSet::finalize()
  546. {
  547. SpinlockLocker lock(m_lock);
  548. VERIFY(!m_finalized);
  549. m_finalized = true;
  550. // Clear the list of threads here so we can drop the references to them
  551. m_processes.clear();
  552. // NOTE: Kernel processes don't have a leaked ref on them.
  553. if (!m_process.is_kernel_process()) {
  554. // No more waiters, drop the last reference immediately. This may
  555. // cause us to be destructed ourselves!
  556. VERIFY(m_process.ref_count() > 0);
  557. m_process.unref();
  558. }
  559. }
  560. Thread::WaitBlocker::WaitBlocker(int wait_options, Variant<Empty, NonnullRefPtr<Process>, NonnullRefPtr<ProcessGroup>> waitee, ErrorOr<siginfo_t>& result)
  561. : m_wait_options(wait_options)
  562. , m_result(result)
  563. , m_waitee(move(waitee))
  564. {
  565. }
  566. bool Thread::WaitBlocker::setup_blocker()
  567. {
  568. if (m_wait_options & WNOHANG)
  569. return false;
  570. return add_to_blocker_set(Process::current().wait_blocker_set());
  571. }
  572. void Thread::WaitBlocker::will_unblock_immediately_without_blocking(UnblockImmediatelyReason)
  573. {
  574. Process::current().wait_blocker_set().try_unblock(*this);
  575. }
  576. void Thread::WaitBlocker::was_unblocked(bool)
  577. {
  578. bool got_sigchld, try_unblock;
  579. {
  580. SpinlockLocker lock(m_lock);
  581. try_unblock = !m_did_unblock;
  582. got_sigchld = m_got_sigchild;
  583. }
  584. if (try_unblock)
  585. Process::current().wait_blocker_set().try_unblock(*this);
  586. // If we were interrupted by SIGCHLD (which gets special handling
  587. // here) we're not going to return with EINTR. But we're going to
  588. // deliver SIGCHLD (only) here.
  589. auto* current_thread = Thread::current();
  590. if (got_sigchld && current_thread->state() != State::Stopped)
  591. current_thread->try_dispatch_one_pending_signal(SIGCHLD);
  592. }
  593. void Thread::WaitBlocker::do_was_disowned()
  594. {
  595. VERIFY(!m_did_unblock);
  596. m_did_unblock = true;
  597. m_result = ECHILD;
  598. }
  599. void Thread::WaitBlocker::do_set_result(const siginfo_t& result)
  600. {
  601. VERIFY(!m_did_unblock);
  602. m_did_unblock = true;
  603. m_result = result;
  604. if (do_get_interrupted_by_signal() == SIGCHLD) {
  605. // This makes it so that wait() will return normally despite the
  606. // fact that SIGCHLD was delivered. Calling do_clear_interrupted_by_signal
  607. // will disable dispatching signals in Thread::block and prevent
  608. // it from returning with EINTR. We will then manually dispatch
  609. // SIGCHLD (and only SIGCHLD) in was_unblocked.
  610. m_got_sigchild = true;
  611. do_clear_interrupted_by_signal();
  612. }
  613. }
  614. bool Thread::WaitBlocker::unblock(Process& process, UnblockFlags flags, u8 signal, bool from_add_blocker)
  615. {
  616. VERIFY(flags != UnblockFlags::Terminated || signal == 0); // signal argument should be ignored for Terminated
  617. bool do_not_unblock = m_waitee.visit(
  618. [&](NonnullRefPtr<Process> const& waitee_process) {
  619. return &process != waitee_process;
  620. },
  621. [&](NonnullRefPtr<ProcessGroup> const& waitee_process_group) {
  622. return waitee_process_group->pgid() != process.pgid();
  623. },
  624. [&](Empty const&) {
  625. // Generic waiter won't be unblocked by disown
  626. return flags == UnblockFlags::Disowned;
  627. });
  628. if (do_not_unblock)
  629. return false;
  630. switch (flags) {
  631. case UnblockFlags::Terminated:
  632. if (!(m_wait_options & WEXITED))
  633. return false;
  634. break;
  635. case UnblockFlags::Stopped:
  636. if (!(m_wait_options & WSTOPPED))
  637. return false;
  638. if (!(m_wait_options & WUNTRACED) && !process.is_traced())
  639. return false;
  640. break;
  641. case UnblockFlags::Continued:
  642. if (!(m_wait_options & WCONTINUED))
  643. return false;
  644. if (!(m_wait_options & WUNTRACED) && !process.is_traced())
  645. return false;
  646. break;
  647. case UnblockFlags::Disowned:
  648. SpinlockLocker lock(m_lock);
  649. // Disowning must unblock anyone waiting for this process explicitly
  650. if (!m_did_unblock)
  651. do_was_disowned();
  652. return true;
  653. }
  654. if (flags == UnblockFlags::Terminated) {
  655. VERIFY(process.is_dead());
  656. SpinlockLocker lock(m_lock);
  657. if (m_did_unblock)
  658. return false;
  659. // Up until this point, this function may have been called
  660. // more than once!
  661. do_set_result(process.wait_info());
  662. } else {
  663. siginfo_t siginfo {};
  664. {
  665. SpinlockLocker lock(g_scheduler_lock);
  666. // We need to gather the information before we release the scheduler lock!
  667. siginfo.si_signo = SIGCHLD;
  668. siginfo.si_pid = process.pid().value();
  669. siginfo.si_uid = process.uid().value();
  670. siginfo.si_status = signal;
  671. switch (flags) {
  672. case UnblockFlags::Terminated:
  673. case UnblockFlags::Disowned:
  674. VERIFY_NOT_REACHED();
  675. case UnblockFlags::Stopped:
  676. siginfo.si_code = CLD_STOPPED;
  677. break;
  678. case UnblockFlags::Continued:
  679. siginfo.si_code = CLD_CONTINUED;
  680. break;
  681. }
  682. }
  683. SpinlockLocker lock(m_lock);
  684. if (m_did_unblock)
  685. return false;
  686. // Up until this point, this function may have been called
  687. // more than once!
  688. do_set_result(siginfo);
  689. }
  690. if (!from_add_blocker) {
  691. // Only call unblock if we weren't called from within add_to_blocker_set!
  692. VERIFY(flags != UnblockFlags::Disowned);
  693. unblock_from_blocker();
  694. }
  695. // Because this may be called from add_blocker, in which case we should
  696. // not be actually trying to unblock the thread (because it hasn't actually
  697. // been blocked yet), we need to return true anyway
  698. return true;
  699. }
  700. }