ThreadBlockers.cpp 26 KB

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