Thread.h 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Concepts.h>
  8. #include <AK/EnumBits.h>
  9. #include <AK/Error.h>
  10. #include <AK/FixedStringBuffer.h>
  11. #include <AK/IntrusiveList.h>
  12. #include <AK/Optional.h>
  13. #include <AK/OwnPtr.h>
  14. #include <AK/Time.h>
  15. #include <AK/Variant.h>
  16. #include <AK/Vector.h>
  17. #include <Kernel/API/POSIX/sched.h>
  18. #include <Kernel/API/POSIX/select.h>
  19. #include <Kernel/API/POSIX/signal_numbers.h>
  20. #include <Kernel/Arch/RegisterState.h>
  21. #include <Kernel/Arch/ThreadRegisters.h>
  22. #include <Kernel/Debug.h>
  23. #include <Kernel/Forward.h>
  24. #include <Kernel/Library/KString.h>
  25. #include <Kernel/Library/ListedRefCounted.h>
  26. #include <Kernel/Library/LockWeakPtr.h>
  27. #include <Kernel/Library/LockWeakable.h>
  28. #include <Kernel/Locking/LockLocation.h>
  29. #include <Kernel/Locking/LockMode.h>
  30. #include <Kernel/Locking/LockRank.h>
  31. #include <Kernel/Locking/SpinlockProtected.h>
  32. #include <Kernel/Memory/VirtualRange.h>
  33. #include <Kernel/UnixTypes.h>
  34. namespace Kernel {
  35. class Timer;
  36. enum class DispatchSignalResult {
  37. Deferred = 0,
  38. Yield,
  39. Terminate,
  40. Continue
  41. };
  42. struct ThreadSpecificData {
  43. ThreadSpecificData* self;
  44. };
  45. #define THREAD_AFFINITY_DEFAULT 0xffffffff
  46. class Thread
  47. : public ListedRefCounted<Thread, LockType::Spinlock>
  48. , public LockWeakable<Thread> {
  49. AK_MAKE_NONCOPYABLE(Thread);
  50. AK_MAKE_NONMOVABLE(Thread);
  51. friend class Mutex;
  52. friend class Process;
  53. friend class Scheduler;
  54. friend struct ThreadReadyQueue;
  55. public:
  56. static Thread* current()
  57. {
  58. return Processor::current_thread();
  59. }
  60. static ErrorOr<NonnullRefPtr<Thread>> create(NonnullRefPtr<Process>);
  61. ~Thread();
  62. static RefPtr<Thread> from_tid_ignoring_jails(ThreadID);
  63. static RefPtr<Thread> from_tid_in_same_jail(ThreadID);
  64. static void finalize_dying_threads();
  65. ThreadID tid() const { return m_tid; }
  66. ProcessID pid() const;
  67. void set_priority(u32 p) { m_priority = p; }
  68. u32 priority() const { return m_priority; }
  69. void detach()
  70. {
  71. SpinlockLocker lock(m_lock);
  72. m_is_joinable = false;
  73. }
  74. [[nodiscard]] bool is_joinable() const
  75. {
  76. SpinlockLocker lock(m_lock);
  77. return m_is_joinable;
  78. }
  79. Process& process() { return m_process; }
  80. Process const& process() const { return m_process; }
  81. using Name = FixedStringBuffer<64>;
  82. SpinlockProtected<Name, LockRank::None> const& name() const
  83. {
  84. return m_name;
  85. }
  86. void set_name(StringView);
  87. void finalize();
  88. enum class State : u8 {
  89. Invalid = 0,
  90. Runnable,
  91. Running,
  92. Dying,
  93. Dead,
  94. Stopped,
  95. Blocked,
  96. };
  97. class [[nodiscard]] BlockResult {
  98. public:
  99. enum Type {
  100. WokeNormally,
  101. NotBlocked,
  102. InterruptedBySignal,
  103. InterruptedByDeath,
  104. InterruptedByTimeout,
  105. };
  106. BlockResult() = delete;
  107. BlockResult(Type type)
  108. : m_type(type)
  109. {
  110. }
  111. bool operator==(Type type) const
  112. {
  113. return m_type == type;
  114. }
  115. bool operator!=(Type type) const
  116. {
  117. return m_type != type;
  118. }
  119. [[nodiscard]] bool was_interrupted() const
  120. {
  121. switch (m_type) {
  122. case InterruptedBySignal:
  123. case InterruptedByDeath:
  124. return true;
  125. default:
  126. return false;
  127. }
  128. }
  129. private:
  130. Type m_type;
  131. };
  132. class BlockTimeout {
  133. public:
  134. BlockTimeout()
  135. : m_infinite(true)
  136. {
  137. }
  138. explicit BlockTimeout(bool is_absolute, Duration const* time, Duration const* start_time = nullptr, clockid_t clock_id = CLOCK_MONOTONIC_COARSE);
  139. Duration const& absolute_time() const { return m_time; }
  140. Duration const* start_time() const { return !m_infinite ? &m_start_time : nullptr; }
  141. clockid_t clock_id() const { return m_clock_id; }
  142. bool is_infinite() const { return m_infinite; }
  143. private:
  144. Duration m_time {};
  145. Duration m_start_time {};
  146. clockid_t m_clock_id { CLOCK_MONOTONIC_COARSE };
  147. bool m_infinite { false };
  148. };
  149. class BlockerSet;
  150. class Blocker {
  151. AK_MAKE_NONMOVABLE(Blocker);
  152. AK_MAKE_NONCOPYABLE(Blocker);
  153. public:
  154. enum class Type {
  155. Unknown = 0,
  156. File,
  157. Futex,
  158. Plan9FS,
  159. Join,
  160. Queue,
  161. Routing,
  162. Sleep,
  163. Signal,
  164. Wait,
  165. Flock
  166. };
  167. virtual ~Blocker();
  168. virtual StringView state_string() const = 0;
  169. virtual Type blocker_type() const = 0;
  170. virtual BlockTimeout const& override_timeout(BlockTimeout const& timeout) { return timeout; }
  171. virtual bool can_be_interrupted() const { return true; }
  172. virtual bool setup_blocker();
  173. virtual void finalize();
  174. Thread& thread() { return m_thread; }
  175. enum class UnblockImmediatelyReason {
  176. UnblockConditionAlreadyMet,
  177. TimeoutInThePast,
  178. };
  179. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) = 0;
  180. virtual void was_unblocked(bool did_timeout)
  181. {
  182. if (did_timeout) {
  183. SpinlockLocker lock(m_lock);
  184. m_did_timeout = true;
  185. }
  186. }
  187. void set_interrupted_by_death()
  188. {
  189. SpinlockLocker lock(m_lock);
  190. do_set_interrupted_by_death();
  191. }
  192. void set_interrupted_by_signal(u8 signal)
  193. {
  194. SpinlockLocker lock(m_lock);
  195. do_set_interrupted_by_signal(signal);
  196. }
  197. u8 was_interrupted_by_signal() const
  198. {
  199. SpinlockLocker lock(m_lock);
  200. return do_get_interrupted_by_signal();
  201. }
  202. virtual Thread::BlockResult block_result()
  203. {
  204. SpinlockLocker lock(m_lock);
  205. if (m_was_interrupted_by_death)
  206. return Thread::BlockResult::InterruptedByDeath;
  207. if (m_was_interrupted_by_signal != 0)
  208. return Thread::BlockResult::InterruptedBySignal;
  209. if (m_did_timeout)
  210. return Thread::BlockResult::InterruptedByTimeout;
  211. return Thread::BlockResult::WokeNormally;
  212. }
  213. void begin_blocking(Badge<Thread>);
  214. BlockResult end_blocking(Badge<Thread>, bool);
  215. protected:
  216. Blocker()
  217. : m_thread(*Thread::current())
  218. {
  219. }
  220. void do_set_interrupted_by_death()
  221. {
  222. m_was_interrupted_by_death = true;
  223. }
  224. void do_set_interrupted_by_signal(u8 signal)
  225. {
  226. VERIFY(signal != 0);
  227. m_was_interrupted_by_signal = signal;
  228. }
  229. void do_clear_interrupted_by_signal()
  230. {
  231. m_was_interrupted_by_signal = 0;
  232. }
  233. u8 do_get_interrupted_by_signal() const
  234. {
  235. return m_was_interrupted_by_signal;
  236. }
  237. [[nodiscard]] bool was_interrupted() const
  238. {
  239. return m_was_interrupted_by_death || m_was_interrupted_by_signal != 0;
  240. }
  241. void unblock_from_blocker()
  242. {
  243. {
  244. SpinlockLocker lock(m_lock);
  245. if (!m_is_blocking)
  246. return;
  247. m_is_blocking = false;
  248. }
  249. m_thread->unblock_from_blocker(*this);
  250. }
  251. bool add_to_blocker_set(BlockerSet&, void* = nullptr);
  252. void set_blocker_set_raw_locked(BlockerSet* blocker_set) { m_blocker_set = blocker_set; }
  253. // FIXME: Figure out whether this can be Thread.
  254. mutable RecursiveSpinlock<LockRank::None> m_lock {};
  255. private:
  256. BlockerSet* m_blocker_set { nullptr };
  257. NonnullRefPtr<Thread> const m_thread;
  258. u8 m_was_interrupted_by_signal { 0 };
  259. bool m_is_blocking { false };
  260. bool m_was_interrupted_by_death { false };
  261. bool m_did_timeout { false };
  262. };
  263. class BlockerSet {
  264. AK_MAKE_NONCOPYABLE(BlockerSet);
  265. AK_MAKE_NONMOVABLE(BlockerSet);
  266. public:
  267. BlockerSet() = default;
  268. virtual ~BlockerSet()
  269. {
  270. VERIFY(!m_lock.is_locked());
  271. VERIFY(m_blockers.is_empty());
  272. }
  273. bool add_blocker(Blocker& blocker, void* data)
  274. {
  275. SpinlockLocker lock(m_lock);
  276. if (!should_add_blocker(blocker, data))
  277. return false;
  278. m_blockers.append({ &blocker, data });
  279. return true;
  280. }
  281. void remove_blocker(Blocker& blocker)
  282. {
  283. SpinlockLocker lock(m_lock);
  284. // NOTE: it's possible that the blocker is no longer present
  285. m_blockers.remove_all_matching([&](auto& info) {
  286. return info.blocker == &blocker;
  287. });
  288. }
  289. bool is_empty() const
  290. {
  291. SpinlockLocker lock(m_lock);
  292. return is_empty_locked();
  293. }
  294. protected:
  295. template<typename Callback>
  296. bool unblock_all_blockers_whose_conditions_are_met(Callback try_to_unblock_one)
  297. {
  298. SpinlockLocker lock(m_lock);
  299. return unblock_all_blockers_whose_conditions_are_met_locked(try_to_unblock_one);
  300. }
  301. template<typename Callback>
  302. bool unblock_all_blockers_whose_conditions_are_met_locked(Callback try_to_unblock_one)
  303. {
  304. VERIFY(m_lock.is_locked());
  305. bool stop_iterating = false;
  306. bool did_unblock_any = false;
  307. for (size_t i = 0; i < m_blockers.size() && !stop_iterating;) {
  308. auto& info = m_blockers[i];
  309. if (bool did_unblock = try_to_unblock_one(*info.blocker, info.data, stop_iterating)) {
  310. m_blockers.remove(i);
  311. did_unblock_any = true;
  312. continue;
  313. }
  314. i++;
  315. }
  316. return did_unblock_any;
  317. }
  318. bool is_empty_locked() const
  319. {
  320. VERIFY(m_lock.is_locked());
  321. return m_blockers.is_empty();
  322. }
  323. virtual bool should_add_blocker(Blocker&, void*) { return true; }
  324. struct BlockerInfo {
  325. Blocker* blocker;
  326. void* data;
  327. };
  328. Vector<BlockerInfo, 4> do_take_blockers(size_t count)
  329. {
  330. if (m_blockers.size() <= count)
  331. return move(m_blockers);
  332. size_t move_count = (count <= m_blockers.size()) ? count : m_blockers.size();
  333. VERIFY(move_count > 0);
  334. Vector<BlockerInfo, 4> taken_blockers;
  335. taken_blockers.ensure_capacity(move_count);
  336. for (size_t i = 0; i < move_count; i++)
  337. taken_blockers.append(m_blockers.take(i));
  338. m_blockers.remove(0, move_count);
  339. return taken_blockers;
  340. }
  341. void do_append_blockers(Vector<BlockerInfo, 4>&& blockers_to_append)
  342. {
  343. if (blockers_to_append.is_empty())
  344. return;
  345. if (m_blockers.is_empty()) {
  346. m_blockers = move(blockers_to_append);
  347. return;
  348. }
  349. m_blockers.ensure_capacity(m_blockers.size() + blockers_to_append.size());
  350. for (size_t i = 0; i < blockers_to_append.size(); i++)
  351. m_blockers.append(blockers_to_append.take(i));
  352. blockers_to_append.clear();
  353. }
  354. // FIXME: Check whether this can be Thread.
  355. mutable Spinlock<LockRank::None> m_lock {};
  356. private:
  357. Vector<BlockerInfo, 4> m_blockers;
  358. };
  359. friend class JoinBlocker;
  360. class JoinBlocker final : public Blocker {
  361. public:
  362. explicit JoinBlocker(Thread& joinee, ErrorOr<void>& try_join_result, void*& joinee_exit_value);
  363. virtual Type blocker_type() const override { return Type::Join; }
  364. virtual StringView state_string() const override { return "Joining"sv; }
  365. virtual bool can_be_interrupted() const override { return false; }
  366. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  367. virtual bool setup_blocker() override;
  368. bool unblock(void*, bool);
  369. private:
  370. NonnullRefPtr<Thread> const m_joinee;
  371. void*& m_joinee_exit_value;
  372. ErrorOr<void>& m_try_join_result;
  373. bool m_did_unblock { false };
  374. };
  375. class WaitQueueBlocker final : public Blocker {
  376. public:
  377. explicit WaitQueueBlocker(WaitQueue&, StringView block_reason = {});
  378. virtual ~WaitQueueBlocker();
  379. virtual Type blocker_type() const override { return Type::Queue; }
  380. virtual StringView state_string() const override { return m_block_reason.is_null() ? m_block_reason : "Queue"sv; }
  381. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override { }
  382. virtual bool setup_blocker() override;
  383. bool unblock();
  384. protected:
  385. WaitQueue& m_wait_queue;
  386. StringView m_block_reason;
  387. bool m_did_unblock { false };
  388. };
  389. class FutexBlocker final : public Blocker {
  390. public:
  391. explicit FutexBlocker(FutexQueue&, u32);
  392. virtual ~FutexBlocker();
  393. virtual Type blocker_type() const override { return Type::Futex; }
  394. virtual StringView state_string() const override { return "Futex"sv; }
  395. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override { }
  396. virtual bool setup_blocker() override;
  397. u32 bitset() const { return m_bitset; }
  398. void begin_requeue()
  399. {
  400. // We need to hold the lock until we moved it over
  401. m_previous_interrupts_state = m_lock.lock();
  402. }
  403. void finish_requeue(FutexQueue&);
  404. bool unblock_bitset(u32 bitset);
  405. bool unblock(bool force = false);
  406. protected:
  407. FutexQueue& m_futex_queue;
  408. u32 m_bitset { 0 };
  409. InterruptsState m_previous_interrupts_state { InterruptsState::Disabled };
  410. bool m_did_unblock { false };
  411. };
  412. class FileBlocker : public Blocker {
  413. public:
  414. enum class BlockFlags : u16 {
  415. None = 0,
  416. Read = 1 << 0,
  417. Write = 1 << 1,
  418. ReadPriority = 1 << 2,
  419. WritePriority = 1 << 3,
  420. Accept = 1 << 4,
  421. Connect = 1 << 5,
  422. SocketFlags = Accept | Connect,
  423. WriteError = 1 << 6,
  424. WriteHangUp = 1 << 7,
  425. ReadHangUp = 1 << 8,
  426. Exception = WriteError | WriteHangUp | ReadHangUp,
  427. };
  428. virtual Type blocker_type() const override { return Type::File; }
  429. virtual bool unblock_if_conditions_are_met(bool, void*) = 0;
  430. };
  431. class OpenFileDescriptionBlocker : public FileBlocker {
  432. public:
  433. OpenFileDescription const& blocked_description() const;
  434. virtual bool unblock_if_conditions_are_met(bool, void*) override;
  435. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  436. virtual bool setup_blocker() override;
  437. protected:
  438. explicit OpenFileDescriptionBlocker(OpenFileDescription&, BlockFlags, BlockFlags&);
  439. private:
  440. NonnullRefPtr<OpenFileDescription> m_blocked_description;
  441. const BlockFlags m_flags;
  442. BlockFlags& m_unblocked_flags;
  443. bool m_did_unblock { false };
  444. };
  445. class AcceptBlocker final : public OpenFileDescriptionBlocker {
  446. public:
  447. explicit AcceptBlocker(OpenFileDescription&, BlockFlags&);
  448. virtual StringView state_string() const override { return "Accepting"sv; }
  449. };
  450. class ConnectBlocker final : public OpenFileDescriptionBlocker {
  451. public:
  452. explicit ConnectBlocker(OpenFileDescription&, BlockFlags&);
  453. virtual StringView state_string() const override { return "Connecting"sv; }
  454. };
  455. class WriteBlocker final : public OpenFileDescriptionBlocker {
  456. public:
  457. explicit WriteBlocker(OpenFileDescription&, BlockFlags&);
  458. virtual StringView state_string() const override { return "Writing"sv; }
  459. virtual BlockTimeout const& override_timeout(BlockTimeout const&) override;
  460. private:
  461. BlockTimeout m_timeout;
  462. };
  463. class ReadBlocker final : public OpenFileDescriptionBlocker {
  464. public:
  465. explicit ReadBlocker(OpenFileDescription&, BlockFlags&);
  466. virtual StringView state_string() const override { return "Reading"sv; }
  467. virtual BlockTimeout const& override_timeout(BlockTimeout const&) override;
  468. private:
  469. BlockTimeout m_timeout;
  470. };
  471. class SleepBlocker final : public Blocker {
  472. public:
  473. explicit SleepBlocker(BlockTimeout const&, Duration* = nullptr);
  474. virtual StringView state_string() const override { return "Sleeping"sv; }
  475. virtual Type blocker_type() const override { return Type::Sleep; }
  476. virtual BlockTimeout const& override_timeout(BlockTimeout const&) override;
  477. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  478. virtual void was_unblocked(bool) override;
  479. virtual Thread::BlockResult block_result() override;
  480. private:
  481. void calculate_remaining();
  482. BlockTimeout m_deadline;
  483. Duration* m_remaining;
  484. };
  485. class SelectBlocker final : public FileBlocker {
  486. public:
  487. struct FDInfo {
  488. RefPtr<OpenFileDescription> description;
  489. BlockFlags block_flags { BlockFlags::None };
  490. BlockFlags unblocked_flags { BlockFlags::None };
  491. };
  492. using FDVector = Vector<FDInfo, FD_SETSIZE>;
  493. explicit SelectBlocker(FDVector&);
  494. virtual ~SelectBlocker();
  495. virtual bool unblock_if_conditions_are_met(bool, void*) override;
  496. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  497. virtual void was_unblocked(bool) override;
  498. virtual StringView state_string() const override { return "Selecting"sv; }
  499. virtual bool setup_blocker() override;
  500. virtual void finalize() override;
  501. private:
  502. size_t collect_unblocked_flags();
  503. FDVector& m_fds;
  504. bool m_did_unblock { false };
  505. };
  506. class SignalBlocker final : public Blocker {
  507. public:
  508. explicit SignalBlocker(sigset_t pending_set, siginfo_t& result);
  509. virtual StringView state_string() const override { return "Pending Signal"sv; }
  510. virtual Type blocker_type() const override { return Type::Signal; }
  511. void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  512. virtual bool setup_blocker() override;
  513. bool check_pending_signals(bool from_add_blocker);
  514. private:
  515. sigset_t m_pending_set { 0 };
  516. siginfo_t& m_result;
  517. bool m_did_unblock { false };
  518. };
  519. class SignalBlockerSet final : public BlockerSet {
  520. public:
  521. void unblock_all_blockers_whose_conditions_are_met()
  522. {
  523. BlockerSet::unblock_all_blockers_whose_conditions_are_met([&](auto& b, void*, bool&) {
  524. VERIFY(b.blocker_type() == Blocker::Type::Signal);
  525. auto& blocker = static_cast<Thread::SignalBlocker&>(b);
  526. return blocker.check_pending_signals(false);
  527. });
  528. }
  529. private:
  530. bool should_add_blocker(Blocker& b, void*) override
  531. {
  532. VERIFY(b.blocker_type() == Blocker::Type::Signal);
  533. auto& blocker = static_cast<Thread::SignalBlocker&>(b);
  534. return !blocker.check_pending_signals(true);
  535. }
  536. };
  537. class WaitBlocker final : public Blocker {
  538. public:
  539. enum class UnblockFlags {
  540. Terminated,
  541. Stopped,
  542. Continued,
  543. Disowned
  544. };
  545. WaitBlocker(int wait_options, Variant<Empty, NonnullRefPtr<Process>, NonnullRefPtr<ProcessGroup>> waitee, ErrorOr<siginfo_t>& result);
  546. virtual StringView state_string() const override { return "Waiting"sv; }
  547. virtual Type blocker_type() const override { return Type::Wait; }
  548. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  549. virtual void was_unblocked(bool) override;
  550. virtual bool setup_blocker() override;
  551. bool unblock(Process& process, UnblockFlags flags, u8 signal, bool from_add_blocker);
  552. bool is_wait() const { return (m_wait_options & WNOWAIT) != WNOWAIT; }
  553. private:
  554. void do_was_disowned();
  555. void do_set_result(siginfo_t const&);
  556. int const m_wait_options;
  557. ErrorOr<siginfo_t>& m_result;
  558. Variant<Empty, NonnullRefPtr<Process>, NonnullRefPtr<ProcessGroup>> const m_waitee;
  559. bool m_did_unblock { false };
  560. bool m_got_sigchild { false };
  561. };
  562. class WaitBlockerSet final : public BlockerSet {
  563. friend class WaitBlocker;
  564. public:
  565. explicit WaitBlockerSet(Process& process)
  566. : m_process(process)
  567. {
  568. }
  569. void disowned_by_waiter(Process&);
  570. bool unblock(Process&, WaitBlocker::UnblockFlags, u8);
  571. void try_unblock(WaitBlocker&);
  572. void finalize();
  573. protected:
  574. virtual bool should_add_blocker(Blocker&, void*) override;
  575. private:
  576. struct ProcessBlockInfo {
  577. NonnullRefPtr<Process> const process;
  578. WaitBlocker::UnblockFlags flags;
  579. u8 signal;
  580. bool was_waited { false };
  581. explicit ProcessBlockInfo(NonnullRefPtr<Process>&&, WaitBlocker::UnblockFlags, u8);
  582. ~ProcessBlockInfo();
  583. };
  584. Process& m_process;
  585. Vector<ProcessBlockInfo, 2> m_processes;
  586. bool m_finalized { false };
  587. };
  588. class FlockBlocker final : public Blocker {
  589. public:
  590. FlockBlocker(NonnullRefPtr<Inode>, flock const&);
  591. virtual StringView state_string() const override { return "Locking File"sv; }
  592. virtual Type blocker_type() const override { return Type::Flock; }
  593. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  594. virtual bool setup_blocker() override;
  595. bool try_unblock(bool from_add_blocker);
  596. private:
  597. NonnullRefPtr<Inode> m_inode;
  598. flock const& m_flock;
  599. bool m_did_unblock { false };
  600. };
  601. class FlockBlockerSet final : public BlockerSet {
  602. public:
  603. void unblock_all_blockers_whose_conditions_are_met()
  604. {
  605. BlockerSet::unblock_all_blockers_whose_conditions_are_met([&](auto& b, void*, bool&) {
  606. VERIFY(b.blocker_type() == Blocker::Type::Flock);
  607. auto& blocker = static_cast<Thread::FlockBlocker&>(b);
  608. return blocker.try_unblock(false);
  609. });
  610. }
  611. private:
  612. bool should_add_blocker(Blocker& b, void*) override
  613. {
  614. VERIFY(b.blocker_type() == Blocker::Type::Flock);
  615. auto& blocker = static_cast<Thread::FlockBlocker&>(b);
  616. return !blocker.try_unblock(true);
  617. }
  618. };
  619. template<typename AddBlockerHandler>
  620. ErrorOr<void> try_join(AddBlockerHandler add_blocker)
  621. {
  622. if (Thread::current() == this)
  623. return EDEADLK;
  624. SpinlockLocker lock(m_lock);
  625. // Joining dead threads is allowed for two main reasons:
  626. // - Thread join behavior should not be racy when a thread is joined and exiting at roughly the same time.
  627. // This is common behavior when threads are given a signal to end (meaning they are going to exit ASAP) and then joined.
  628. // - POSIX requires that exited threads are joinable (at least, there is no language in the specification forbidding it).
  629. if (!m_is_joinable || state() == Thread::State::Invalid)
  630. return EINVAL;
  631. add_blocker();
  632. // From this point on the thread is no longer joinable by anyone
  633. // else. It also means that if the join is timed, it becomes
  634. // detached when a timeout happens.
  635. m_is_joinable = false;
  636. return {};
  637. }
  638. void did_schedule() { ++m_times_scheduled; }
  639. u32 times_scheduled() const { return m_times_scheduled; }
  640. void resume_from_stopped();
  641. [[nodiscard]] bool should_be_stopped() const;
  642. [[nodiscard]] bool is_stopped() const { return m_state == Thread::State::Stopped; }
  643. [[nodiscard]] bool is_blocked() const { return m_state == Thread::State::Blocked; }
  644. u32 cpu() const { return m_cpu.load(AK::MemoryOrder::memory_order_consume); }
  645. void set_cpu(u32 cpu) { m_cpu.store(cpu, AK::MemoryOrder::memory_order_release); }
  646. u32 affinity() const { return m_cpu_affinity; }
  647. void set_affinity(u32 affinity) { m_cpu_affinity = affinity; }
  648. RegisterState& get_register_dump_from_stack();
  649. RegisterState const& get_register_dump_from_stack() const { return const_cast<Thread*>(this)->get_register_dump_from_stack(); }
  650. DebugRegisterState& debug_register_state() { return m_debug_register_state; }
  651. DebugRegisterState const& debug_register_state() const { return m_debug_register_state; }
  652. ThreadRegisters& regs() { return m_regs; }
  653. ThreadRegisters const& regs() const { return m_regs; }
  654. State state() const { return m_state; }
  655. StringView state_string() const;
  656. VirtualAddress thread_specific_data() const { return m_thread_specific_data; }
  657. size_t thread_specific_region_size() const;
  658. size_t thread_specific_region_alignment() const;
  659. ALWAYS_INLINE void yield_if_stopped()
  660. {
  661. // If some thread stopped us, we need to yield to someone else
  662. // We check this when entering/exiting a system call. A thread
  663. // may continue to execute in user land until the next timer
  664. // tick or entering the next system call, or if it's in kernel
  665. // mode then we will intercept prior to returning back to user
  666. // mode.
  667. SpinlockLocker lock(m_lock);
  668. while (state() == Thread::State::Stopped) {
  669. lock.unlock();
  670. // We shouldn't be holding the big lock here
  671. yield_without_releasing_big_lock();
  672. lock.lock();
  673. }
  674. }
  675. void block(Kernel::Mutex&, SpinlockLocker<Spinlock<LockRank::None>>&, u32);
  676. template<typename BlockerType, class... Args>
  677. BlockResult block(BlockTimeout const& timeout, Args&&... args)
  678. {
  679. BlockerType blocker(forward<Args>(args)...);
  680. return block_impl(timeout, blocker);
  681. }
  682. u32 unblock_from_mutex(Kernel::Mutex&);
  683. void unblock_from_blocker(Blocker&);
  684. void unblock(u8 signal = 0);
  685. template<class... Args>
  686. Thread::BlockResult wait_on(WaitQueue& wait_queue, Thread::BlockTimeout const& timeout, Args&&... args)
  687. {
  688. VERIFY(this == Thread::current());
  689. return block<Thread::WaitQueueBlocker>(timeout, wait_queue, forward<Args>(args)...);
  690. }
  691. BlockResult sleep(clockid_t, Duration const&, Duration* = nullptr);
  692. BlockResult sleep(Duration const& duration, Duration* remaining_time = nullptr)
  693. {
  694. return sleep(CLOCK_MONOTONIC_COARSE, duration, remaining_time);
  695. }
  696. BlockResult sleep_until(clockid_t, Duration const&);
  697. BlockResult sleep_until(Duration const& duration)
  698. {
  699. return sleep_until(CLOCK_MONOTONIC_COARSE, duration);
  700. }
  701. // Tell this thread to unblock if needed,
  702. // gracefully unwind the stack and die.
  703. void set_should_die();
  704. [[nodiscard]] bool should_die() const { return m_should_die; }
  705. void die_if_needed();
  706. void exit(void* = nullptr);
  707. void update_time_scheduled(u64, bool, bool);
  708. bool tick();
  709. void set_ticks_left(u32 t) { m_ticks_left = t; }
  710. u32 ticks_left() const { return m_ticks_left; }
  711. FlatPtr kernel_stack_base() const { return m_kernel_stack_base; }
  712. FlatPtr kernel_stack_top() const { return m_kernel_stack_top; }
  713. void set_state(State, u8 = 0);
  714. [[nodiscard]] bool is_initialized() const { return m_initialized; }
  715. void set_initialized(bool initialized) { m_initialized = initialized; }
  716. void send_urgent_signal_to_self(u8 signal);
  717. void send_signal(u8 signal, Process* sender);
  718. u32 update_signal_mask(u32 signal_mask);
  719. u32 signal_mask_block(sigset_t signal_set, bool block);
  720. u32 signal_mask() const;
  721. void reset_signals_for_exec();
  722. ErrorOr<FlatPtr> peek_debug_register(u32 register_index);
  723. ErrorOr<void> poke_debug_register(u32 register_index, FlatPtr data);
  724. void set_dump_backtrace_on_finalization() { m_dump_backtrace_on_finalization = true; }
  725. DispatchSignalResult dispatch_one_pending_signal();
  726. DispatchSignalResult try_dispatch_one_pending_signal(u8 signal);
  727. DispatchSignalResult dispatch_signal(u8 signal);
  728. void check_dispatch_pending_signal();
  729. [[nodiscard]] bool has_unmasked_pending_signals() const { return m_have_any_unmasked_pending_signals.load(AK::memory_order_consume); }
  730. [[nodiscard]] bool should_ignore_signal(u8 signal) const;
  731. [[nodiscard]] bool has_signal_handler(u8 signal) const;
  732. [[nodiscard]] bool is_signal_masked(u8 signal) const;
  733. u32 pending_signals() const;
  734. u32 pending_signals_for_state() const;
  735. [[nodiscard]] bool has_alternative_signal_stack() const;
  736. [[nodiscard]] bool is_in_alternative_signal_stack() const;
  737. FPUState& fpu_state() { return m_fpu_state; }
  738. ErrorOr<void> make_thread_specific_region(Badge<Process>);
  739. unsigned syscall_count() const { return m_syscall_count; }
  740. void did_syscall() { ++m_syscall_count; }
  741. unsigned inode_faults() const { return m_inode_faults; }
  742. void did_inode_fault() { ++m_inode_faults; }
  743. unsigned zero_faults() const { return m_zero_faults; }
  744. void did_zero_fault() { ++m_zero_faults; }
  745. unsigned cow_faults() const { return m_cow_faults; }
  746. void did_cow_fault() { ++m_cow_faults; }
  747. u64 file_read_bytes() const { return m_file_read_bytes; }
  748. u64 file_write_bytes() const { return m_file_write_bytes; }
  749. void did_file_read(u64 bytes)
  750. {
  751. m_file_read_bytes += bytes;
  752. }
  753. void did_file_write(u64 bytes)
  754. {
  755. m_file_write_bytes += bytes;
  756. }
  757. u64 unix_socket_read_bytes() const { return m_unix_socket_read_bytes; }
  758. u64 unix_socket_write_bytes() const { return m_unix_socket_write_bytes; }
  759. void did_unix_socket_read(u64 bytes)
  760. {
  761. m_unix_socket_read_bytes += bytes;
  762. }
  763. void did_unix_socket_write(u64 bytes)
  764. {
  765. m_unix_socket_write_bytes += bytes;
  766. }
  767. u64 ipv4_socket_read_bytes() const { return m_ipv4_socket_read_bytes; }
  768. u64 ipv4_socket_write_bytes() const { return m_ipv4_socket_write_bytes; }
  769. void did_ipv4_socket_read(u64 bytes)
  770. {
  771. m_ipv4_socket_read_bytes += bytes;
  772. }
  773. void did_ipv4_socket_write(u64 bytes)
  774. {
  775. m_ipv4_socket_write_bytes += bytes;
  776. }
  777. void set_active(bool active) { m_is_active = active; }
  778. u32 saved_critical() const { return m_saved_critical; }
  779. void save_critical(u32 critical) { m_saved_critical = critical; }
  780. void track_lock_acquire(LockRank rank);
  781. void track_lock_release(LockRank rank);
  782. [[nodiscard]] bool is_active() const { return m_is_active; }
  783. [[nodiscard]] bool is_finalizable() const
  784. {
  785. // We can't finalize as long as this thread is still running
  786. // Note that checking for Running state here isn't sufficient
  787. // as the thread may not be in Running state but switching out.
  788. // m_is_active is set to false once the context switch is
  789. // complete and the thread is not executing on any processor.
  790. if (m_is_active.load(AK::memory_order_acquire))
  791. return false;
  792. // We can't finalize until the thread is either detached or
  793. // a join has started. We can't make m_is_joinable atomic
  794. // because that would introduce a race in try_join.
  795. SpinlockLocker lock(m_lock);
  796. return !m_is_joinable;
  797. }
  798. ErrorOr<NonnullRefPtr<Thread>> clone(NonnullRefPtr<Process>);
  799. template<IteratorFunction<Thread&> Callback>
  800. static IterationDecision for_each_in_state_ignoring_jails(State, Callback);
  801. template<IteratorFunction<Thread&> Callback>
  802. static IterationDecision for_each_ignoring_jails(Callback);
  803. template<VoidFunction<Thread&> Callback>
  804. static IterationDecision for_each_in_state_ignoring_jails(State, Callback);
  805. template<VoidFunction<Thread&> Callback>
  806. static IterationDecision for_each_ignoring_jails(Callback);
  807. static constexpr u32 default_kernel_stack_size = 65536;
  808. static constexpr u32 default_userspace_stack_size = 1 * MiB;
  809. u64 time_in_user() const { return m_total_time_scheduled_user.load(AK::MemoryOrder::memory_order_relaxed); }
  810. u64 time_in_kernel() const { return m_total_time_scheduled_kernel.load(AK::MemoryOrder::memory_order_relaxed); }
  811. ExecutionMode previous_mode() const { return m_previous_mode; }
  812. bool set_previous_mode(ExecutionMode mode)
  813. {
  814. if (m_previous_mode == mode)
  815. return false;
  816. m_previous_mode = mode;
  817. return true;
  818. }
  819. TrapFrame*& current_trap() { return m_current_trap; }
  820. TrapFrame const* const& current_trap() const { return m_current_trap; }
  821. RecursiveSpinlock<LockRank::Thread>& get_lock() const { return m_lock; }
  822. #if LOCK_DEBUG
  823. void holding_lock(Mutex& lock, int refs_delta, LockLocation const& location)
  824. {
  825. VERIFY(refs_delta != 0);
  826. m_holding_locks.fetch_add(refs_delta, AK::MemoryOrder::memory_order_relaxed);
  827. SpinlockLocker list_lock(m_holding_locks_lock);
  828. if (refs_delta > 0) {
  829. bool have_existing = false;
  830. for (size_t i = 0; i < m_holding_locks_list.size(); i++) {
  831. auto& info = m_holding_locks_list[i];
  832. if (info.lock == &lock) {
  833. have_existing = true;
  834. info.count += refs_delta;
  835. break;
  836. }
  837. }
  838. if (!have_existing)
  839. m_holding_locks_list.append({ &lock, location, 1 });
  840. } else {
  841. VERIFY(refs_delta < 0);
  842. bool found = false;
  843. for (size_t i = 0; i < m_holding_locks_list.size(); i++) {
  844. auto& info = m_holding_locks_list[i];
  845. if (info.lock == &lock) {
  846. VERIFY(info.count >= (unsigned)-refs_delta);
  847. info.count -= (unsigned)-refs_delta;
  848. if (info.count == 0)
  849. m_holding_locks_list.remove(i);
  850. found = true;
  851. break;
  852. }
  853. }
  854. VERIFY(found);
  855. }
  856. }
  857. u32 lock_count() const
  858. {
  859. return m_holding_locks.load(AK::MemoryOrder::memory_order_relaxed);
  860. }
  861. #endif
  862. bool is_handling_page_fault() const
  863. {
  864. return m_handling_page_fault;
  865. }
  866. void set_handling_page_fault(bool b) { m_handling_page_fault = b; }
  867. void set_idle_thread() { m_is_idle_thread = true; }
  868. bool is_idle_thread() const { return m_is_idle_thread; }
  869. void set_crashing() { m_is_crashing = true; }
  870. [[nodiscard]] bool is_crashing() const { return m_is_crashing; }
  871. ALWAYS_INLINE u32 enter_profiler()
  872. {
  873. return m_nested_profiler_calls.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  874. }
  875. ALWAYS_INLINE u32 leave_profiler()
  876. {
  877. return m_nested_profiler_calls.fetch_sub(1, AK::MemoryOrder::memory_order_acquire);
  878. }
  879. bool is_profiling_suppressed() const { return m_is_profiling_suppressed; }
  880. void set_profiling_suppressed() { m_is_profiling_suppressed = true; }
  881. bool is_promise_violation_pending() const { return m_is_promise_violation_pending; }
  882. void set_promise_violation_pending(bool value) { m_is_promise_violation_pending = value; }
  883. bool is_allocation_enabled() const { return m_allocation_enabled; }
  884. void set_allocation_enabled(bool value) { m_allocation_enabled = value; }
  885. ErrorOr<NonnullOwnPtr<KString>> backtrace();
  886. Blocker const* blocker() const { return m_blocker; }
  887. Kernel::Mutex const* blocking_mutex() const { return m_blocking_mutex; }
  888. #if LOCK_DEBUG
  889. struct HoldingLockInfo {
  890. Mutex* lock;
  891. LockLocation lock_location;
  892. unsigned count;
  893. };
  894. template<IteratorFunction<HoldingLockInfo const&> Callback>
  895. void for_each_held_lock(Callback);
  896. template<VoidFunction<HoldingLockInfo const&> Callback>
  897. void for_each_held_lock(Callback);
  898. #endif
  899. private:
  900. Thread(NonnullRefPtr<Process>, NonnullOwnPtr<Memory::Region>, NonnullRefPtr<Timer>);
  901. BlockResult block_impl(BlockTimeout const&, Blocker&);
  902. IntrusiveListNode<Thread> m_process_thread_list_node;
  903. int m_runnable_priority { -1 };
  904. friend class WaitQueue;
  905. class JoinBlockerSet final : public BlockerSet {
  906. public:
  907. void thread_did_exit(void* exit_value)
  908. {
  909. SpinlockLocker lock(m_lock);
  910. VERIFY(!m_thread_did_exit);
  911. m_thread_did_exit = true;
  912. m_exit_value.store(exit_value, AK::MemoryOrder::memory_order_release);
  913. do_unblock_joiner();
  914. }
  915. void thread_finalizing()
  916. {
  917. SpinlockLocker lock(m_lock);
  918. do_unblock_joiner();
  919. }
  920. void* exit_value() const
  921. {
  922. VERIFY(m_thread_did_exit);
  923. return m_exit_value.load(AK::MemoryOrder::memory_order_acquire);
  924. }
  925. void try_unblock(JoinBlocker& blocker)
  926. {
  927. SpinlockLocker lock(m_lock);
  928. if (m_thread_did_exit)
  929. blocker.unblock(exit_value(), false);
  930. }
  931. protected:
  932. virtual bool should_add_blocker(Blocker& b, void*) override
  933. {
  934. VERIFY(b.blocker_type() == Blocker::Type::Join);
  935. auto& blocker = static_cast<JoinBlocker&>(b);
  936. // NOTE: m_lock is held already!
  937. if (m_thread_did_exit) {
  938. blocker.unblock(exit_value(), true);
  939. return false;
  940. }
  941. return true;
  942. }
  943. private:
  944. void do_unblock_joiner()
  945. {
  946. unblock_all_blockers_whose_conditions_are_met_locked([&](Blocker& b, void*, bool&) {
  947. VERIFY(b.blocker_type() == Blocker::Type::Join);
  948. auto& blocker = static_cast<JoinBlocker&>(b);
  949. return blocker.unblock(exit_value(), false);
  950. });
  951. }
  952. Atomic<void*> m_exit_value { nullptr };
  953. bool m_thread_did_exit { false };
  954. };
  955. LockMode unlock_process_if_locked(u32&);
  956. void relock_process(LockMode, u32);
  957. void reset_fpu_state();
  958. mutable RecursiveSpinlock<LockRank::Thread> m_lock {};
  959. mutable RecursiveSpinlock<LockRank::None> m_block_lock {};
  960. NonnullRefPtr<Process> const m_process;
  961. ThreadID m_tid { -1 };
  962. ThreadRegisters m_regs {};
  963. DebugRegisterState m_debug_register_state {};
  964. TrapFrame* m_current_trap { nullptr };
  965. u32 m_saved_critical { 1 };
  966. IntrusiveListNode<Thread> m_ready_queue_node;
  967. Atomic<u32> m_cpu { 0 };
  968. u32 m_cpu_affinity { THREAD_AFFINITY_DEFAULT };
  969. Optional<u64> m_last_time_scheduled;
  970. Atomic<u64> m_total_time_scheduled_user { 0 };
  971. Atomic<u64> m_total_time_scheduled_kernel { 0 };
  972. u32 m_ticks_left { 0 };
  973. u32 m_times_scheduled { 0 };
  974. u32 m_ticks_in_user { 0 };
  975. u32 m_ticks_in_kernel { 0 };
  976. u32 m_pending_signals { 0 };
  977. u8 m_currently_handled_signal { 0 };
  978. u32 m_signal_mask { 0 };
  979. FlatPtr m_alternative_signal_stack { 0 };
  980. FlatPtr m_alternative_signal_stack_size { 0 };
  981. SignalBlockerSet m_signal_blocker_set;
  982. FlatPtr m_kernel_stack_base { 0 };
  983. FlatPtr m_kernel_stack_top { 0 };
  984. NonnullOwnPtr<Memory::Region> m_kernel_stack_region;
  985. VirtualAddress m_thread_specific_data;
  986. Optional<Memory::VirtualRange> m_thread_specific_range;
  987. Array<Optional<u32>, NSIG> m_signal_action_masks;
  988. Array<ProcessID, NSIG> m_signal_senders;
  989. Blocker* m_blocker { nullptr };
  990. Kernel::Mutex* m_blocking_mutex { nullptr };
  991. u32 m_lock_requested_count { 0 };
  992. IntrusiveListNode<Thread> m_blocked_threads_list_node;
  993. LockRank m_lock_rank_mask {};
  994. bool m_allocation_enabled { true };
  995. // FIXME: remove this after annihilating Process::m_big_lock
  996. IntrusiveListNode<Thread> m_big_lock_blocked_threads_list_node;
  997. #if LOCK_DEBUG
  998. Atomic<u32> m_holding_locks { 0 };
  999. Spinlock<LockRank::None> m_holding_locks_lock {};
  1000. Vector<HoldingLockInfo> m_holding_locks_list;
  1001. #endif
  1002. JoinBlockerSet m_join_blocker_set;
  1003. Atomic<bool, AK::MemoryOrder::memory_order_relaxed> m_is_active { false };
  1004. bool m_is_joinable { true };
  1005. bool m_handling_page_fault { false };
  1006. ExecutionMode m_previous_mode { ExecutionMode::Kernel }; // We always start out in kernel mode
  1007. unsigned m_syscall_count { 0 };
  1008. unsigned m_inode_faults { 0 };
  1009. unsigned m_zero_faults { 0 };
  1010. unsigned m_cow_faults { 0 };
  1011. u64 m_file_read_bytes { 0 };
  1012. u64 m_file_write_bytes { 0 };
  1013. u64 m_unix_socket_read_bytes { 0 };
  1014. u64 m_unix_socket_write_bytes { 0 };
  1015. u64 m_ipv4_socket_read_bytes { 0 };
  1016. u64 m_ipv4_socket_write_bytes { 0 };
  1017. FPUState m_fpu_state {};
  1018. State m_state { Thread::State::Invalid };
  1019. SpinlockProtected<Name, LockRank::None> m_name;
  1020. u32 m_priority { THREAD_PRIORITY_NORMAL };
  1021. State m_stop_state { Thread::State::Invalid };
  1022. bool m_dump_backtrace_on_finalization { false };
  1023. bool m_should_die { false };
  1024. bool m_initialized { false };
  1025. bool m_is_idle_thread { false };
  1026. bool m_is_crashing { false };
  1027. bool m_is_promise_violation_pending { false };
  1028. Atomic<bool> m_have_any_unmasked_pending_signals { false };
  1029. Atomic<u32> m_nested_profiler_calls { 0 };
  1030. NonnullRefPtr<Timer> const m_block_timer;
  1031. bool m_is_profiling_suppressed { false };
  1032. void yield_and_release_relock_big_lock();
  1033. enum class VerifyLockNotHeld {
  1034. Yes,
  1035. No
  1036. };
  1037. void yield_without_releasing_big_lock(VerifyLockNotHeld verify_lock_not_held = VerifyLockNotHeld::Yes);
  1038. void drop_thread_count();
  1039. mutable IntrusiveListNode<Thread> m_global_thread_list_node;
  1040. public:
  1041. using ListInProcess = IntrusiveList<&Thread::m_process_thread_list_node>;
  1042. using GlobalList = IntrusiveList<&Thread::m_global_thread_list_node>;
  1043. static SpinlockProtected<GlobalList, LockRank::None>& all_instances();
  1044. };
  1045. AK_ENUM_BITWISE_OPERATORS(Thread::FileBlocker::BlockFlags);
  1046. template<IteratorFunction<Thread&> Callback>
  1047. inline IterationDecision Thread::for_each_ignoring_jails(Callback callback)
  1048. {
  1049. return Thread::all_instances().with([&](auto& list) -> IterationDecision {
  1050. for (auto& thread : list) {
  1051. IterationDecision decision = callback(thread);
  1052. if (decision != IterationDecision::Continue)
  1053. return decision;
  1054. }
  1055. return IterationDecision::Continue;
  1056. });
  1057. }
  1058. template<IteratorFunction<Thread&> Callback>
  1059. inline IterationDecision Thread::for_each_in_state_ignoring_jails(State state, Callback callback)
  1060. {
  1061. return Thread::all_instances().with([&](auto& list) -> IterationDecision {
  1062. for (auto& thread : list) {
  1063. if (thread.state() != state)
  1064. continue;
  1065. IterationDecision decision = callback(thread);
  1066. if (decision != IterationDecision::Continue)
  1067. return decision;
  1068. }
  1069. return IterationDecision::Continue;
  1070. });
  1071. }
  1072. template<VoidFunction<Thread&> Callback>
  1073. inline IterationDecision Thread::for_each_ignoring_jails(Callback callback)
  1074. {
  1075. return Thread::all_instances().with([&](auto& list) {
  1076. for (auto& thread : list) {
  1077. if (callback(thread) == IterationDecision::Break)
  1078. return IterationDecision::Break;
  1079. }
  1080. return IterationDecision::Continue;
  1081. });
  1082. }
  1083. template<VoidFunction<Thread&> Callback>
  1084. inline IterationDecision Thread::for_each_in_state_ignoring_jails(State state, Callback callback)
  1085. {
  1086. return for_each_in_state_ignoring_jails(state, [&](auto& thread) {
  1087. callback(thread);
  1088. return IterationDecision::Continue;
  1089. });
  1090. }
  1091. #if LOCK_DEBUG
  1092. template<IteratorFunction<Thread::HoldingLockInfo const&> Callback>
  1093. inline void Thread::for_each_held_lock(Callback callback)
  1094. {
  1095. SpinlockLocker list_lock(m_holding_locks_lock);
  1096. for (auto const& lock_info : m_holding_locks_list) {
  1097. if (callback(lock_info) == IterationDecision::Break)
  1098. break;
  1099. }
  1100. }
  1101. template<VoidFunction<Thread::HoldingLockInfo const&> Callback>
  1102. inline void Thread::for_each_held_lock(Callback callback)
  1103. {
  1104. for_each_held_lock([&](auto const& lock_info) {
  1105. callback(lock_info);
  1106. return IterationDecision::Continue;
  1107. });
  1108. }
  1109. #endif
  1110. }
  1111. template<>
  1112. struct AK::Formatter<Kernel::Thread> : AK::Formatter<FormatString> {
  1113. ErrorOr<void> format(FormatBuilder&, Kernel::Thread const&);
  1114. };