Thread.h 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  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 is_in_alternative_signal_stack() const;
  736. FPUState& fpu_state() { return m_fpu_state; }
  737. ErrorOr<void> make_thread_specific_region(Badge<Process>);
  738. unsigned syscall_count() const { return m_syscall_count; }
  739. void did_syscall() { ++m_syscall_count; }
  740. unsigned inode_faults() const { return m_inode_faults; }
  741. void did_inode_fault() { ++m_inode_faults; }
  742. unsigned zero_faults() const { return m_zero_faults; }
  743. void did_zero_fault() { ++m_zero_faults; }
  744. unsigned cow_faults() const { return m_cow_faults; }
  745. void did_cow_fault() { ++m_cow_faults; }
  746. u64 file_read_bytes() const { return m_file_read_bytes; }
  747. u64 file_write_bytes() const { return m_file_write_bytes; }
  748. void did_file_read(u64 bytes)
  749. {
  750. m_file_read_bytes += bytes;
  751. }
  752. void did_file_write(u64 bytes)
  753. {
  754. m_file_write_bytes += bytes;
  755. }
  756. u64 unix_socket_read_bytes() const { return m_unix_socket_read_bytes; }
  757. u64 unix_socket_write_bytes() const { return m_unix_socket_write_bytes; }
  758. void did_unix_socket_read(u64 bytes)
  759. {
  760. m_unix_socket_read_bytes += bytes;
  761. }
  762. void did_unix_socket_write(u64 bytes)
  763. {
  764. m_unix_socket_write_bytes += bytes;
  765. }
  766. u64 ipv4_socket_read_bytes() const { return m_ipv4_socket_read_bytes; }
  767. u64 ipv4_socket_write_bytes() const { return m_ipv4_socket_write_bytes; }
  768. void did_ipv4_socket_read(u64 bytes)
  769. {
  770. m_ipv4_socket_read_bytes += bytes;
  771. }
  772. void did_ipv4_socket_write(u64 bytes)
  773. {
  774. m_ipv4_socket_write_bytes += bytes;
  775. }
  776. void set_active(bool active) { m_is_active = active; }
  777. u32 saved_critical() const { return m_saved_critical; }
  778. void save_critical(u32 critical) { m_saved_critical = critical; }
  779. void track_lock_acquire(LockRank rank);
  780. void track_lock_release(LockRank rank);
  781. [[nodiscard]] bool is_active() const { return m_is_active; }
  782. [[nodiscard]] bool is_finalizable() const
  783. {
  784. // We can't finalize as long as this thread is still running
  785. // Note that checking for Running state here isn't sufficient
  786. // as the thread may not be in Running state but switching out.
  787. // m_is_active is set to false once the context switch is
  788. // complete and the thread is not executing on any processor.
  789. if (m_is_active.load(AK::memory_order_acquire))
  790. return false;
  791. // We can't finalize until the thread is either detached or
  792. // a join has started. We can't make m_is_joinable atomic
  793. // because that would introduce a race in try_join.
  794. SpinlockLocker lock(m_lock);
  795. return !m_is_joinable;
  796. }
  797. ErrorOr<NonnullRefPtr<Thread>> clone(NonnullRefPtr<Process>);
  798. template<IteratorFunction<Thread&> Callback>
  799. static IterationDecision for_each_in_state_ignoring_jails(State, Callback);
  800. template<IteratorFunction<Thread&> Callback>
  801. static IterationDecision for_each_ignoring_jails(Callback);
  802. template<VoidFunction<Thread&> Callback>
  803. static IterationDecision for_each_in_state_ignoring_jails(State, Callback);
  804. template<VoidFunction<Thread&> Callback>
  805. static IterationDecision for_each_ignoring_jails(Callback);
  806. static constexpr u32 default_kernel_stack_size = 65536;
  807. static constexpr u32 default_userspace_stack_size = 1 * MiB;
  808. u64 time_in_user() const { return m_total_time_scheduled_user.load(AK::MemoryOrder::memory_order_relaxed); }
  809. u64 time_in_kernel() const { return m_total_time_scheduled_kernel.load(AK::MemoryOrder::memory_order_relaxed); }
  810. ExecutionMode previous_mode() const { return m_previous_mode; }
  811. bool set_previous_mode(ExecutionMode mode)
  812. {
  813. if (m_previous_mode == mode)
  814. return false;
  815. m_previous_mode = mode;
  816. return true;
  817. }
  818. TrapFrame*& current_trap() { return m_current_trap; }
  819. TrapFrame const* const& current_trap() const { return m_current_trap; }
  820. RecursiveSpinlock<LockRank::Thread>& get_lock() const { return m_lock; }
  821. #if LOCK_DEBUG
  822. void holding_lock(Mutex& lock, int refs_delta, LockLocation const& location)
  823. {
  824. VERIFY(refs_delta != 0);
  825. m_holding_locks.fetch_add(refs_delta, AK::MemoryOrder::memory_order_relaxed);
  826. SpinlockLocker list_lock(m_holding_locks_lock);
  827. if (refs_delta > 0) {
  828. bool have_existing = false;
  829. for (size_t i = 0; i < m_holding_locks_list.size(); i++) {
  830. auto& info = m_holding_locks_list[i];
  831. if (info.lock == &lock) {
  832. have_existing = true;
  833. info.count += refs_delta;
  834. break;
  835. }
  836. }
  837. if (!have_existing)
  838. m_holding_locks_list.append({ &lock, location, 1 });
  839. } else {
  840. VERIFY(refs_delta < 0);
  841. bool found = false;
  842. for (size_t i = 0; i < m_holding_locks_list.size(); i++) {
  843. auto& info = m_holding_locks_list[i];
  844. if (info.lock == &lock) {
  845. VERIFY(info.count >= (unsigned)-refs_delta);
  846. info.count -= (unsigned)-refs_delta;
  847. if (info.count == 0)
  848. m_holding_locks_list.remove(i);
  849. found = true;
  850. break;
  851. }
  852. }
  853. VERIFY(found);
  854. }
  855. }
  856. u32 lock_count() const
  857. {
  858. return m_holding_locks.load(AK::MemoryOrder::memory_order_relaxed);
  859. }
  860. #endif
  861. bool is_handling_page_fault() const
  862. {
  863. return m_handling_page_fault;
  864. }
  865. void set_handling_page_fault(bool b) { m_handling_page_fault = b; }
  866. void set_idle_thread() { m_is_idle_thread = true; }
  867. bool is_idle_thread() const { return m_is_idle_thread; }
  868. void set_crashing() { m_is_crashing = true; }
  869. [[nodiscard]] bool is_crashing() const { return m_is_crashing; }
  870. ALWAYS_INLINE u32 enter_profiler()
  871. {
  872. return m_nested_profiler_calls.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  873. }
  874. ALWAYS_INLINE u32 leave_profiler()
  875. {
  876. return m_nested_profiler_calls.fetch_sub(1, AK::MemoryOrder::memory_order_acquire);
  877. }
  878. bool is_profiling_suppressed() const { return m_is_profiling_suppressed; }
  879. void set_profiling_suppressed() { m_is_profiling_suppressed = true; }
  880. bool is_promise_violation_pending() const { return m_is_promise_violation_pending; }
  881. void set_promise_violation_pending(bool value) { m_is_promise_violation_pending = value; }
  882. bool is_allocation_enabled() const { return m_allocation_enabled; }
  883. void set_allocation_enabled(bool value) { m_allocation_enabled = value; }
  884. ErrorOr<NonnullOwnPtr<KString>> backtrace();
  885. Blocker const* blocker() const { return m_blocker; }
  886. Kernel::Mutex const* blocking_mutex() const { return m_blocking_mutex; }
  887. #if LOCK_DEBUG
  888. struct HoldingLockInfo {
  889. Mutex* lock;
  890. LockLocation lock_location;
  891. unsigned count;
  892. };
  893. template<IteratorFunction<HoldingLockInfo const&> Callback>
  894. void for_each_held_lock(Callback);
  895. template<VoidFunction<HoldingLockInfo const&> Callback>
  896. void for_each_held_lock(Callback);
  897. #endif
  898. private:
  899. Thread(NonnullRefPtr<Process>, NonnullOwnPtr<Memory::Region>, NonnullRefPtr<Timer>);
  900. BlockResult block_impl(BlockTimeout const&, Blocker&);
  901. IntrusiveListNode<Thread> m_process_thread_list_node;
  902. int m_runnable_priority { -1 };
  903. friend class WaitQueue;
  904. class JoinBlockerSet final : public BlockerSet {
  905. public:
  906. void thread_did_exit(void* exit_value)
  907. {
  908. SpinlockLocker lock(m_lock);
  909. VERIFY(!m_thread_did_exit);
  910. m_thread_did_exit = true;
  911. m_exit_value.store(exit_value, AK::MemoryOrder::memory_order_release);
  912. do_unblock_joiner();
  913. }
  914. void thread_finalizing()
  915. {
  916. SpinlockLocker lock(m_lock);
  917. do_unblock_joiner();
  918. }
  919. void* exit_value() const
  920. {
  921. VERIFY(m_thread_did_exit);
  922. return m_exit_value.load(AK::MemoryOrder::memory_order_acquire);
  923. }
  924. void try_unblock(JoinBlocker& blocker)
  925. {
  926. SpinlockLocker lock(m_lock);
  927. if (m_thread_did_exit)
  928. blocker.unblock(exit_value(), false);
  929. }
  930. protected:
  931. virtual bool should_add_blocker(Blocker& b, void*) override
  932. {
  933. VERIFY(b.blocker_type() == Blocker::Type::Join);
  934. auto& blocker = static_cast<JoinBlocker&>(b);
  935. // NOTE: m_lock is held already!
  936. if (m_thread_did_exit) {
  937. blocker.unblock(exit_value(), true);
  938. return false;
  939. }
  940. return true;
  941. }
  942. private:
  943. void do_unblock_joiner()
  944. {
  945. unblock_all_blockers_whose_conditions_are_met_locked([&](Blocker& b, void*, bool&) {
  946. VERIFY(b.blocker_type() == Blocker::Type::Join);
  947. auto& blocker = static_cast<JoinBlocker&>(b);
  948. return blocker.unblock(exit_value(), false);
  949. });
  950. }
  951. Atomic<void*> m_exit_value { nullptr };
  952. bool m_thread_did_exit { false };
  953. };
  954. LockMode unlock_process_if_locked(u32&);
  955. void relock_process(LockMode, u32);
  956. void reset_fpu_state();
  957. mutable RecursiveSpinlock<LockRank::Thread> m_lock {};
  958. mutable RecursiveSpinlock<LockRank::None> m_block_lock {};
  959. NonnullRefPtr<Process> const m_process;
  960. ThreadID m_tid { -1 };
  961. ThreadRegisters m_regs {};
  962. DebugRegisterState m_debug_register_state {};
  963. TrapFrame* m_current_trap { nullptr };
  964. u32 m_saved_critical { 1 };
  965. IntrusiveListNode<Thread> m_ready_queue_node;
  966. Atomic<u32> m_cpu { 0 };
  967. u32 m_cpu_affinity { THREAD_AFFINITY_DEFAULT };
  968. Optional<u64> m_last_time_scheduled;
  969. Atomic<u64> m_total_time_scheduled_user { 0 };
  970. Atomic<u64> m_total_time_scheduled_kernel { 0 };
  971. u32 m_ticks_left { 0 };
  972. u32 m_times_scheduled { 0 };
  973. u32 m_ticks_in_user { 0 };
  974. u32 m_ticks_in_kernel { 0 };
  975. u32 m_pending_signals { 0 };
  976. u8 m_currently_handled_signal { 0 };
  977. u32 m_signal_mask { 0 };
  978. Optional<Memory::VirtualRange> m_alternative_signal_stack;
  979. SignalBlockerSet m_signal_blocker_set;
  980. FlatPtr m_kernel_stack_base { 0 };
  981. FlatPtr m_kernel_stack_top { 0 };
  982. NonnullOwnPtr<Memory::Region> m_kernel_stack_region;
  983. VirtualAddress m_thread_specific_data;
  984. Optional<Memory::VirtualRange> m_thread_specific_range;
  985. Array<Optional<u32>, NSIG> m_signal_action_masks;
  986. Array<ProcessID, NSIG> m_signal_senders;
  987. Blocker* m_blocker { nullptr };
  988. Kernel::Mutex* m_blocking_mutex { nullptr };
  989. u32 m_lock_requested_count { 0 };
  990. IntrusiveListNode<Thread> m_blocked_threads_list_node;
  991. LockRank m_lock_rank_mask {};
  992. bool m_allocation_enabled { true };
  993. // FIXME: remove this after annihilating Process::m_big_lock
  994. IntrusiveListNode<Thread> m_big_lock_blocked_threads_list_node;
  995. #if LOCK_DEBUG
  996. Atomic<u32> m_holding_locks { 0 };
  997. Spinlock<LockRank::None> m_holding_locks_lock {};
  998. Vector<HoldingLockInfo> m_holding_locks_list;
  999. #endif
  1000. JoinBlockerSet m_join_blocker_set;
  1001. Atomic<bool, AK::MemoryOrder::memory_order_relaxed> m_is_active { false };
  1002. bool m_is_joinable { true };
  1003. bool m_handling_page_fault { false };
  1004. ExecutionMode m_previous_mode { ExecutionMode::Kernel }; // We always start out in kernel mode
  1005. unsigned m_syscall_count { 0 };
  1006. unsigned m_inode_faults { 0 };
  1007. unsigned m_zero_faults { 0 };
  1008. unsigned m_cow_faults { 0 };
  1009. u64 m_file_read_bytes { 0 };
  1010. u64 m_file_write_bytes { 0 };
  1011. u64 m_unix_socket_read_bytes { 0 };
  1012. u64 m_unix_socket_write_bytes { 0 };
  1013. u64 m_ipv4_socket_read_bytes { 0 };
  1014. u64 m_ipv4_socket_write_bytes { 0 };
  1015. FPUState m_fpu_state {};
  1016. State m_state { Thread::State::Invalid };
  1017. SpinlockProtected<Name, LockRank::None> m_name;
  1018. u32 m_priority { THREAD_PRIORITY_NORMAL };
  1019. State m_stop_state { Thread::State::Invalid };
  1020. bool m_dump_backtrace_on_finalization { false };
  1021. bool m_should_die { false };
  1022. bool m_initialized { false };
  1023. bool m_is_idle_thread { false };
  1024. bool m_is_crashing { false };
  1025. bool m_is_promise_violation_pending { false };
  1026. Atomic<bool> m_have_any_unmasked_pending_signals { false };
  1027. Atomic<u32> m_nested_profiler_calls { 0 };
  1028. NonnullRefPtr<Timer> const m_block_timer;
  1029. bool m_is_profiling_suppressed { false };
  1030. void yield_and_release_relock_big_lock();
  1031. enum class VerifyLockNotHeld {
  1032. Yes,
  1033. No
  1034. };
  1035. void yield_without_releasing_big_lock(VerifyLockNotHeld verify_lock_not_held = VerifyLockNotHeld::Yes);
  1036. void drop_thread_count();
  1037. mutable IntrusiveListNode<Thread> m_global_thread_list_node;
  1038. public:
  1039. using ListInProcess = IntrusiveList<&Thread::m_process_thread_list_node>;
  1040. using GlobalList = IntrusiveList<&Thread::m_global_thread_list_node>;
  1041. static SpinlockProtected<GlobalList, LockRank::None>& all_instances();
  1042. };
  1043. AK_ENUM_BITWISE_OPERATORS(Thread::FileBlocker::BlockFlags);
  1044. template<IteratorFunction<Thread&> Callback>
  1045. inline IterationDecision Thread::for_each_ignoring_jails(Callback callback)
  1046. {
  1047. return Thread::all_instances().with([&](auto& list) -> IterationDecision {
  1048. for (auto& thread : list) {
  1049. IterationDecision decision = callback(thread);
  1050. if (decision != IterationDecision::Continue)
  1051. return decision;
  1052. }
  1053. return IterationDecision::Continue;
  1054. });
  1055. }
  1056. template<IteratorFunction<Thread&> Callback>
  1057. inline IterationDecision Thread::for_each_in_state_ignoring_jails(State state, Callback callback)
  1058. {
  1059. return Thread::all_instances().with([&](auto& list) -> IterationDecision {
  1060. for (auto& thread : list) {
  1061. if (thread.state() != state)
  1062. continue;
  1063. IterationDecision decision = callback(thread);
  1064. if (decision != IterationDecision::Continue)
  1065. return decision;
  1066. }
  1067. return IterationDecision::Continue;
  1068. });
  1069. }
  1070. template<VoidFunction<Thread&> Callback>
  1071. inline IterationDecision Thread::for_each_ignoring_jails(Callback callback)
  1072. {
  1073. return Thread::all_instances().with([&](auto& list) {
  1074. for (auto& thread : list) {
  1075. if (callback(thread) == IterationDecision::Break)
  1076. return IterationDecision::Break;
  1077. }
  1078. return IterationDecision::Continue;
  1079. });
  1080. }
  1081. template<VoidFunction<Thread&> Callback>
  1082. inline IterationDecision Thread::for_each_in_state_ignoring_jails(State state, Callback callback)
  1083. {
  1084. return for_each_in_state_ignoring_jails(state, [&](auto& thread) {
  1085. callback(thread);
  1086. return IterationDecision::Continue;
  1087. });
  1088. }
  1089. #if LOCK_DEBUG
  1090. template<IteratorFunction<Thread::HoldingLockInfo const&> Callback>
  1091. inline void Thread::for_each_held_lock(Callback callback)
  1092. {
  1093. SpinlockLocker list_lock(m_holding_locks_lock);
  1094. for (auto const& lock_info : m_holding_locks_list) {
  1095. if (callback(lock_info) == IterationDecision::Break)
  1096. break;
  1097. }
  1098. }
  1099. template<VoidFunction<Thread::HoldingLockInfo const&> Callback>
  1100. inline void Thread::for_each_held_lock(Callback callback)
  1101. {
  1102. for_each_held_lock([&](auto const& lock_info) {
  1103. callback(lock_info);
  1104. return IterationDecision::Continue;
  1105. });
  1106. }
  1107. #endif
  1108. }
  1109. template<>
  1110. struct AK::Formatter<Kernel::Thread> : AK::Formatter<FormatString> {
  1111. ErrorOr<void> format(FormatBuilder&, Kernel::Thread const&);
  1112. };