Thread.h 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  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/Platform.h>
  15. #include <AK/Time.h>
  16. #include <AK/Variant.h>
  17. #include <AK/Vector.h>
  18. #include <Kernel/API/POSIX/sched.h>
  19. #include <Kernel/API/POSIX/select.h>
  20. #include <Kernel/API/POSIX/signal_numbers.h>
  21. #include <Kernel/Arch/RegisterState.h>
  22. #include <Kernel/Arch/ThreadRegisters.h>
  23. #include <Kernel/Debug.h>
  24. #include <Kernel/Forward.h>
  25. #include <Kernel/Library/KString.h>
  26. #include <Kernel/Library/ListedRefCounted.h>
  27. #include <Kernel/Library/LockWeakPtr.h>
  28. #include <Kernel/Library/LockWeakable.h>
  29. #include <Kernel/Locking/LockLocation.h>
  30. #include <Kernel/Locking/LockMode.h>
  31. #include <Kernel/Locking/LockRank.h>
  32. #include <Kernel/Locking/SpinlockProtected.h>
  33. #include <Kernel/Memory/VirtualRange.h>
  34. #include <Kernel/Tasks/Scheduler.h>
  35. #include <Kernel/UnixTypes.h>
  36. namespace Kernel {
  37. class Timer;
  38. enum class DispatchSignalResult {
  39. Deferred = 0,
  40. Yield,
  41. Terminate,
  42. Continue
  43. };
  44. struct ThreadSpecificData {
  45. ThreadSpecificData* self;
  46. };
  47. #define THREAD_AFFINITY_DEFAULT 0xffffffff
  48. class Thread
  49. : public ListedRefCounted<Thread, LockType::Spinlock>
  50. , public LockWeakable<Thread> {
  51. AK_MAKE_NONCOPYABLE(Thread);
  52. AK_MAKE_NONMOVABLE(Thread);
  53. friend class Mutex;
  54. friend class Process;
  55. friend class Scheduler;
  56. friend struct ThreadReadyQueue;
  57. public:
  58. static Thread* current()
  59. {
  60. return Processor::current_thread();
  61. }
  62. static ErrorOr<NonnullRefPtr<Thread>> create(NonnullRefPtr<Process>);
  63. ~Thread();
  64. static RefPtr<Thread> from_tid_ignoring_jails(ThreadID);
  65. static RefPtr<Thread> from_tid_in_same_jail(ThreadID);
  66. static void finalize_dying_threads();
  67. ThreadID tid() const { return m_tid; }
  68. ProcessID pid() const;
  69. void set_priority(u32 p) { m_priority = p; }
  70. u32 priority() const { return m_priority; }
  71. void detach()
  72. {
  73. SpinlockLocker lock(m_lock);
  74. m_is_joinable = false;
  75. }
  76. [[nodiscard]] bool is_joinable() const
  77. {
  78. SpinlockLocker lock(m_lock);
  79. return m_is_joinable;
  80. }
  81. NO_SANITIZE_COVERAGE Process& process() { return m_process; }
  82. NO_SANITIZE_COVERAGE Process const& process() const { return m_process; }
  83. using Name = FixedStringBuffer<64>;
  84. SpinlockProtected<Name, LockRank::None> const& name() const
  85. {
  86. return m_name;
  87. }
  88. void set_name(StringView);
  89. void finalize();
  90. enum class State : u8 {
  91. Invalid = 0,
  92. Runnable,
  93. Running,
  94. Dying,
  95. Dead,
  96. Stopped,
  97. Blocked,
  98. };
  99. class [[nodiscard]] BlockResult {
  100. public:
  101. enum Type {
  102. WokeNormally,
  103. NotBlocked,
  104. InterruptedBySignal,
  105. InterruptedByDeath,
  106. InterruptedByTimeout,
  107. };
  108. BlockResult() = delete;
  109. BlockResult(Type type)
  110. : m_type(type)
  111. {
  112. }
  113. bool operator==(Type type) const
  114. {
  115. return m_type == type;
  116. }
  117. bool operator!=(Type type) const
  118. {
  119. return m_type != type;
  120. }
  121. [[nodiscard]] bool was_interrupted() const
  122. {
  123. switch (m_type) {
  124. case InterruptedBySignal:
  125. case InterruptedByDeath:
  126. return true;
  127. default:
  128. return false;
  129. }
  130. }
  131. private:
  132. Type m_type;
  133. };
  134. class BlockTimeout {
  135. public:
  136. BlockTimeout()
  137. : m_infinite(true)
  138. {
  139. }
  140. explicit BlockTimeout(bool is_absolute, Duration const* time, Duration const* start_time = nullptr, clockid_t clock_id = CLOCK_MONOTONIC_COARSE);
  141. Duration const& absolute_time() const { return m_time; }
  142. Duration const* start_time() const { return !m_infinite ? &m_start_time : nullptr; }
  143. clockid_t clock_id() const { return m_clock_id; }
  144. bool is_infinite() const { return m_infinite; }
  145. private:
  146. Duration m_time {};
  147. Duration m_start_time {};
  148. clockid_t m_clock_id { CLOCK_MONOTONIC_COARSE };
  149. bool m_infinite { false };
  150. };
  151. class BlockerSet;
  152. class Blocker {
  153. AK_MAKE_NONMOVABLE(Blocker);
  154. AK_MAKE_NONCOPYABLE(Blocker);
  155. public:
  156. enum class Type {
  157. Unknown = 0,
  158. File,
  159. Futex,
  160. Plan9FS,
  161. Join,
  162. Queue,
  163. Routing,
  164. Sleep,
  165. Signal,
  166. Wait,
  167. Flock
  168. };
  169. virtual ~Blocker();
  170. virtual StringView state_string() const = 0;
  171. virtual Type blocker_type() const = 0;
  172. virtual BlockTimeout const& override_timeout(BlockTimeout const& timeout) { return timeout; }
  173. virtual bool can_be_interrupted() const { return true; }
  174. virtual bool setup_blocker();
  175. virtual void finalize();
  176. Thread& thread() { return m_thread; }
  177. enum class UnblockImmediatelyReason {
  178. UnblockConditionAlreadyMet,
  179. TimeoutInThePast,
  180. };
  181. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) = 0;
  182. virtual void was_unblocked(bool did_timeout)
  183. {
  184. if (did_timeout) {
  185. SpinlockLocker lock(m_lock);
  186. m_did_timeout = true;
  187. }
  188. }
  189. void set_interrupted_by_death()
  190. {
  191. SpinlockLocker lock(m_lock);
  192. do_set_interrupted_by_death();
  193. }
  194. void set_interrupted_by_signal(u8 signal)
  195. {
  196. SpinlockLocker lock(m_lock);
  197. do_set_interrupted_by_signal(signal);
  198. }
  199. u8 was_interrupted_by_signal() const
  200. {
  201. SpinlockLocker lock(m_lock);
  202. return do_get_interrupted_by_signal();
  203. }
  204. virtual Thread::BlockResult block_result()
  205. {
  206. SpinlockLocker lock(m_lock);
  207. if (m_was_interrupted_by_death)
  208. return Thread::BlockResult::InterruptedByDeath;
  209. if (m_was_interrupted_by_signal != 0)
  210. return Thread::BlockResult::InterruptedBySignal;
  211. if (m_did_timeout)
  212. return Thread::BlockResult::InterruptedByTimeout;
  213. return Thread::BlockResult::WokeNormally;
  214. }
  215. void begin_blocking(Badge<Thread>);
  216. BlockResult end_blocking(Badge<Thread>, bool);
  217. protected:
  218. Blocker()
  219. : m_thread(*Thread::current())
  220. {
  221. }
  222. void do_set_interrupted_by_death()
  223. {
  224. m_was_interrupted_by_death = true;
  225. }
  226. void do_set_interrupted_by_signal(u8 signal)
  227. {
  228. VERIFY(signal != 0);
  229. m_was_interrupted_by_signal = signal;
  230. }
  231. void do_clear_interrupted_by_signal()
  232. {
  233. m_was_interrupted_by_signal = 0;
  234. }
  235. u8 do_get_interrupted_by_signal() const
  236. {
  237. return m_was_interrupted_by_signal;
  238. }
  239. [[nodiscard]] bool was_interrupted() const
  240. {
  241. return m_was_interrupted_by_death || m_was_interrupted_by_signal != 0;
  242. }
  243. void unblock_from_blocker()
  244. {
  245. {
  246. SpinlockLocker lock(m_lock);
  247. if (!m_is_blocking)
  248. return;
  249. m_is_blocking = false;
  250. }
  251. m_thread->unblock_from_blocker(*this);
  252. }
  253. bool add_to_blocker_set(BlockerSet&, void* = nullptr);
  254. void set_blocker_set_raw_locked(BlockerSet* blocker_set) { m_blocker_set = blocker_set; }
  255. // FIXME: Figure out whether this can be Thread.
  256. mutable RecursiveSpinlock<LockRank::None> m_lock {};
  257. private:
  258. BlockerSet* m_blocker_set { nullptr };
  259. NonnullRefPtr<Thread> const m_thread;
  260. u8 m_was_interrupted_by_signal { 0 };
  261. bool m_is_blocking { false };
  262. bool m_was_interrupted_by_death { false };
  263. bool m_did_timeout { false };
  264. };
  265. class BlockerSet {
  266. AK_MAKE_NONCOPYABLE(BlockerSet);
  267. AK_MAKE_NONMOVABLE(BlockerSet);
  268. public:
  269. BlockerSet() = default;
  270. virtual ~BlockerSet()
  271. {
  272. VERIFY(!m_lock.is_locked());
  273. VERIFY(m_blockers.is_empty());
  274. }
  275. bool add_blocker(Blocker& blocker, void* data)
  276. {
  277. SpinlockLocker lock(m_lock);
  278. if (!should_add_blocker(blocker, data))
  279. return false;
  280. m_blockers.append({ &blocker, data });
  281. return true;
  282. }
  283. void remove_blocker(Blocker& blocker)
  284. {
  285. SpinlockLocker lock(m_lock);
  286. // NOTE: it's possible that the blocker is no longer present
  287. m_blockers.remove_all_matching([&](auto& info) {
  288. return info.blocker == &blocker;
  289. });
  290. }
  291. bool is_empty() const
  292. {
  293. SpinlockLocker lock(m_lock);
  294. return is_empty_locked();
  295. }
  296. protected:
  297. template<typename Callback>
  298. bool unblock_all_blockers_whose_conditions_are_met(Callback try_to_unblock_one)
  299. {
  300. SpinlockLocker lock(m_lock);
  301. return unblock_all_blockers_whose_conditions_are_met_locked(try_to_unblock_one);
  302. }
  303. template<typename Callback>
  304. bool unblock_all_blockers_whose_conditions_are_met_locked(Callback try_to_unblock_one)
  305. {
  306. VERIFY(m_lock.is_locked());
  307. bool stop_iterating = false;
  308. bool did_unblock_any = false;
  309. for (size_t i = 0; i < m_blockers.size() && !stop_iterating;) {
  310. auto& info = m_blockers[i];
  311. if (bool did_unblock = try_to_unblock_one(*info.blocker, info.data, stop_iterating)) {
  312. m_blockers.remove(i);
  313. did_unblock_any = true;
  314. continue;
  315. }
  316. i++;
  317. }
  318. return did_unblock_any;
  319. }
  320. bool is_empty_locked() const
  321. {
  322. VERIFY(m_lock.is_locked());
  323. return m_blockers.is_empty();
  324. }
  325. virtual bool should_add_blocker(Blocker&, void*) { return true; }
  326. struct BlockerInfo {
  327. Blocker* blocker;
  328. void* data;
  329. };
  330. Vector<BlockerInfo, 4> do_take_blockers(size_t count)
  331. {
  332. if (m_blockers.size() <= count)
  333. return move(m_blockers);
  334. size_t move_count = (count <= m_blockers.size()) ? count : m_blockers.size();
  335. VERIFY(move_count > 0);
  336. Vector<BlockerInfo, 4> taken_blockers;
  337. taken_blockers.ensure_capacity(move_count);
  338. for (size_t i = 0; i < move_count; i++)
  339. taken_blockers.append(m_blockers.take(i));
  340. m_blockers.remove(0, move_count);
  341. return taken_blockers;
  342. }
  343. void do_append_blockers(Vector<BlockerInfo, 4>&& blockers_to_append)
  344. {
  345. if (blockers_to_append.is_empty())
  346. return;
  347. if (m_blockers.is_empty()) {
  348. m_blockers = move(blockers_to_append);
  349. return;
  350. }
  351. m_blockers.ensure_capacity(m_blockers.size() + blockers_to_append.size());
  352. for (size_t i = 0; i < blockers_to_append.size(); i++)
  353. m_blockers.append(blockers_to_append.take(i));
  354. blockers_to_append.clear();
  355. }
  356. // FIXME: Check whether this can be Thread.
  357. mutable Spinlock<LockRank::None> m_lock {};
  358. private:
  359. Vector<BlockerInfo, 4> m_blockers;
  360. };
  361. friend class JoinBlocker;
  362. class JoinBlocker final : public Blocker {
  363. public:
  364. explicit JoinBlocker(Thread& joinee, ErrorOr<void>& try_join_result, void*& joinee_exit_value);
  365. virtual Type blocker_type() const override { return Type::Join; }
  366. virtual StringView state_string() const override { return "Joining"sv; }
  367. virtual bool can_be_interrupted() const override { return false; }
  368. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  369. virtual bool setup_blocker() override;
  370. bool unblock(void*, bool);
  371. private:
  372. NonnullRefPtr<Thread> const m_joinee;
  373. void*& m_joinee_exit_value;
  374. ErrorOr<void>& m_try_join_result;
  375. bool m_did_unblock { false };
  376. };
  377. class WaitQueueBlocker final : public Blocker {
  378. public:
  379. explicit WaitQueueBlocker(WaitQueue&, StringView block_reason = {});
  380. virtual ~WaitQueueBlocker();
  381. virtual Type blocker_type() const override { return Type::Queue; }
  382. virtual StringView state_string() const override { return m_block_reason.is_null() ? m_block_reason : "Queue"sv; }
  383. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override { }
  384. virtual bool setup_blocker() override;
  385. bool unblock();
  386. protected:
  387. WaitQueue& m_wait_queue;
  388. StringView m_block_reason;
  389. bool m_did_unblock { false };
  390. };
  391. class FutexBlocker final : public Blocker {
  392. public:
  393. explicit FutexBlocker(FutexQueue&, u32);
  394. virtual ~FutexBlocker();
  395. virtual Type blocker_type() const override { return Type::Futex; }
  396. virtual StringView state_string() const override { return "Futex"sv; }
  397. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override { }
  398. virtual bool setup_blocker() override;
  399. u32 bitset() const { return m_bitset; }
  400. void begin_requeue()
  401. {
  402. // We need to hold the lock until we moved it over
  403. m_previous_interrupts_state = m_lock.lock();
  404. }
  405. void finish_requeue(FutexQueue&);
  406. bool unblock_bitset(u32 bitset);
  407. bool unblock(bool force = false);
  408. protected:
  409. FutexQueue& m_futex_queue;
  410. u32 m_bitset { 0 };
  411. InterruptsState m_previous_interrupts_state { InterruptsState::Disabled };
  412. bool m_did_unblock { false };
  413. };
  414. class FileBlocker : public Blocker {
  415. public:
  416. enum class BlockFlags : u16 {
  417. None = 0,
  418. Read = 1 << 0,
  419. Write = 1 << 1,
  420. ReadPriority = 1 << 2,
  421. WritePriority = 1 << 3,
  422. Accept = 1 << 4,
  423. Connect = 1 << 5,
  424. SocketFlags = Accept | Connect,
  425. WriteError = 1 << 6,
  426. WriteHangUp = 1 << 7,
  427. ReadHangUp = 1 << 8,
  428. Exception = WriteError | WriteHangUp | ReadHangUp,
  429. };
  430. virtual Type blocker_type() const override { return Type::File; }
  431. virtual bool unblock_if_conditions_are_met(bool, void*) = 0;
  432. };
  433. class OpenFileDescriptionBlocker : public FileBlocker {
  434. public:
  435. OpenFileDescription const& blocked_description() const;
  436. virtual bool unblock_if_conditions_are_met(bool, void*) override;
  437. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  438. virtual bool setup_blocker() override;
  439. protected:
  440. explicit OpenFileDescriptionBlocker(OpenFileDescription&, BlockFlags, BlockFlags&);
  441. private:
  442. NonnullRefPtr<OpenFileDescription> m_blocked_description;
  443. BlockFlags const m_flags;
  444. BlockFlags& m_unblocked_flags;
  445. bool m_did_unblock { false };
  446. };
  447. class AcceptBlocker final : public OpenFileDescriptionBlocker {
  448. public:
  449. explicit AcceptBlocker(OpenFileDescription&, BlockFlags&);
  450. virtual StringView state_string() const override { return "Accepting"sv; }
  451. };
  452. class ConnectBlocker final : public OpenFileDescriptionBlocker {
  453. public:
  454. explicit ConnectBlocker(OpenFileDescription&, BlockFlags&);
  455. virtual StringView state_string() const override { return "Connecting"sv; }
  456. };
  457. class WriteBlocker final : public OpenFileDescriptionBlocker {
  458. public:
  459. explicit WriteBlocker(OpenFileDescription&, BlockFlags&);
  460. virtual StringView state_string() const override { return "Writing"sv; }
  461. virtual BlockTimeout const& override_timeout(BlockTimeout const&) override;
  462. private:
  463. BlockTimeout m_timeout;
  464. };
  465. class ReadBlocker final : public OpenFileDescriptionBlocker {
  466. public:
  467. explicit ReadBlocker(OpenFileDescription&, BlockFlags&);
  468. virtual StringView state_string() const override { return "Reading"sv; }
  469. virtual BlockTimeout const& override_timeout(BlockTimeout const&) override;
  470. private:
  471. BlockTimeout m_timeout;
  472. };
  473. class SleepBlocker final : public Blocker {
  474. public:
  475. explicit SleepBlocker(BlockTimeout const&, Duration* = nullptr);
  476. virtual StringView state_string() const override { return "Sleeping"sv; }
  477. virtual Type blocker_type() const override { return Type::Sleep; }
  478. virtual BlockTimeout const& override_timeout(BlockTimeout const&) override;
  479. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  480. virtual void was_unblocked(bool) override;
  481. virtual Thread::BlockResult block_result() override;
  482. private:
  483. void calculate_remaining();
  484. BlockTimeout m_deadline;
  485. Duration* m_remaining;
  486. };
  487. class SelectBlocker final : public FileBlocker {
  488. public:
  489. struct FDInfo {
  490. RefPtr<OpenFileDescription> description;
  491. BlockFlags block_flags { BlockFlags::None };
  492. BlockFlags unblocked_flags { BlockFlags::None };
  493. };
  494. using FDVector = Vector<FDInfo, FD_SETSIZE>;
  495. explicit SelectBlocker(FDVector&);
  496. virtual ~SelectBlocker();
  497. virtual bool unblock_if_conditions_are_met(bool, void*) override;
  498. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  499. virtual void was_unblocked(bool) override;
  500. virtual StringView state_string() const override { return "Selecting"sv; }
  501. virtual bool setup_blocker() override;
  502. virtual void finalize() override;
  503. private:
  504. size_t collect_unblocked_flags();
  505. FDVector& m_fds;
  506. bool m_did_unblock { false };
  507. };
  508. class SignalBlocker final : public Blocker {
  509. public:
  510. explicit SignalBlocker(sigset_t pending_set, siginfo_t& result);
  511. virtual StringView state_string() const override { return "Pending Signal"sv; }
  512. virtual Type blocker_type() const override { return Type::Signal; }
  513. void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  514. virtual bool setup_blocker() override;
  515. bool check_pending_signals(bool from_add_blocker);
  516. private:
  517. sigset_t m_pending_set { 0 };
  518. siginfo_t& m_result;
  519. bool m_did_unblock { false };
  520. };
  521. class SignalBlockerSet final : public BlockerSet {
  522. public:
  523. void unblock_all_blockers_whose_conditions_are_met()
  524. {
  525. BlockerSet::unblock_all_blockers_whose_conditions_are_met([&](auto& b, void*, bool&) {
  526. VERIFY(b.blocker_type() == Blocker::Type::Signal);
  527. auto& blocker = static_cast<Thread::SignalBlocker&>(b);
  528. return blocker.check_pending_signals(false);
  529. });
  530. }
  531. private:
  532. bool should_add_blocker(Blocker& b, void*) override
  533. {
  534. VERIFY(b.blocker_type() == Blocker::Type::Signal);
  535. auto& blocker = static_cast<Thread::SignalBlocker&>(b);
  536. return !blocker.check_pending_signals(true);
  537. }
  538. };
  539. class WaitBlocker final : public Blocker {
  540. public:
  541. enum class UnblockFlags {
  542. Terminated,
  543. Stopped,
  544. Continued,
  545. Disowned
  546. };
  547. WaitBlocker(int wait_options, Variant<Empty, NonnullRefPtr<Process>, NonnullRefPtr<ProcessGroup>> waitee, ErrorOr<siginfo_t>& result);
  548. virtual StringView state_string() const override { return "Waiting"sv; }
  549. virtual Type blocker_type() const override { return Type::Wait; }
  550. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  551. virtual void was_unblocked(bool) override;
  552. virtual bool setup_blocker() override;
  553. bool unblock(Process& process, UnblockFlags flags, u8 signal, bool from_add_blocker);
  554. bool is_wait() const { return (m_wait_options & WNOWAIT) != WNOWAIT; }
  555. private:
  556. void do_was_disowned();
  557. void do_set_result(siginfo_t const&);
  558. int const m_wait_options;
  559. ErrorOr<siginfo_t>& m_result;
  560. Variant<Empty, NonnullRefPtr<Process>, NonnullRefPtr<ProcessGroup>> const m_waitee;
  561. bool m_did_unblock { false };
  562. bool m_got_sigchild { false };
  563. };
  564. class WaitBlockerSet final : public BlockerSet {
  565. friend class WaitBlocker;
  566. public:
  567. explicit WaitBlockerSet(Process& process)
  568. : m_process(process)
  569. {
  570. }
  571. void disowned_by_waiter(Process&);
  572. bool unblock(Process&, WaitBlocker::UnblockFlags, u8);
  573. void try_unblock(WaitBlocker&);
  574. void finalize();
  575. protected:
  576. virtual bool should_add_blocker(Blocker&, void*) override;
  577. private:
  578. struct ProcessBlockInfo {
  579. NonnullRefPtr<Process> const process;
  580. WaitBlocker::UnblockFlags flags;
  581. u8 signal;
  582. bool was_waited { false };
  583. explicit ProcessBlockInfo(NonnullRefPtr<Process>&&, WaitBlocker::UnblockFlags, u8);
  584. ~ProcessBlockInfo();
  585. };
  586. Process& m_process;
  587. Vector<ProcessBlockInfo, 2> m_processes;
  588. bool m_finalized { false };
  589. };
  590. class FlockBlocker final : public Blocker {
  591. public:
  592. FlockBlocker(NonnullRefPtr<Inode>, flock const&);
  593. virtual StringView state_string() const override { return "Locking File"sv; }
  594. virtual Type blocker_type() const override { return Type::Flock; }
  595. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  596. virtual bool setup_blocker() override;
  597. bool try_unblock(bool from_add_blocker);
  598. private:
  599. NonnullRefPtr<Inode> m_inode;
  600. flock const& m_flock;
  601. bool m_did_unblock { false };
  602. };
  603. class FlockBlockerSet final : public BlockerSet {
  604. public:
  605. void unblock_all_blockers_whose_conditions_are_met()
  606. {
  607. BlockerSet::unblock_all_blockers_whose_conditions_are_met([&](auto& b, void*, bool&) {
  608. VERIFY(b.blocker_type() == Blocker::Type::Flock);
  609. auto& blocker = static_cast<Thread::FlockBlocker&>(b);
  610. return blocker.try_unblock(false);
  611. });
  612. }
  613. private:
  614. bool should_add_blocker(Blocker& b, void*) override
  615. {
  616. VERIFY(b.blocker_type() == Blocker::Type::Flock);
  617. auto& blocker = static_cast<Thread::FlockBlocker&>(b);
  618. return !blocker.try_unblock(true);
  619. }
  620. };
  621. template<typename AddBlockerHandler>
  622. ErrorOr<void> try_join(AddBlockerHandler add_blocker)
  623. {
  624. if (Thread::current() == this)
  625. return EDEADLK;
  626. SpinlockLocker lock(m_lock);
  627. // Joining dead threads is allowed for two main reasons:
  628. // - Thread join behavior should not be racy when a thread is joined and exiting at roughly the same time.
  629. // This is common behavior when threads are given a signal to end (meaning they are going to exit ASAP) and then joined.
  630. // - POSIX requires that exited threads are joinable (at least, there is no language in the specification forbidding it).
  631. if (!m_is_joinable || state() == Thread::State::Invalid)
  632. return EINVAL;
  633. add_blocker();
  634. // From this point on the thread is no longer joinable by anyone
  635. // else. It also means that if the join is timed, it becomes
  636. // detached when a timeout happens.
  637. m_is_joinable = false;
  638. return {};
  639. }
  640. void did_schedule() { ++m_times_scheduled; }
  641. u32 times_scheduled() const { return m_times_scheduled; }
  642. void resume_from_stopped();
  643. [[nodiscard]] bool should_be_stopped() const;
  644. [[nodiscard]] bool is_stopped() const { return m_state == Thread::State::Stopped; }
  645. [[nodiscard]] bool is_blocked() const { return m_state == Thread::State::Blocked; }
  646. u32 cpu() const { return m_cpu.load(AK::MemoryOrder::memory_order_consume); }
  647. void set_cpu(u32 cpu) { m_cpu.store(cpu, AK::MemoryOrder::memory_order_release); }
  648. u32 affinity() const { return m_cpu_affinity; }
  649. void set_affinity(u32 affinity) { m_cpu_affinity = affinity; }
  650. RegisterState& get_register_dump_from_stack();
  651. RegisterState const& get_register_dump_from_stack() const { return const_cast<Thread*>(this)->get_register_dump_from_stack(); }
  652. DebugRegisterState& debug_register_state() { return m_debug_register_state; }
  653. DebugRegisterState const& debug_register_state() const { return m_debug_register_state; }
  654. ThreadRegisters& regs() { return m_regs; }
  655. ThreadRegisters const& regs() const { return m_regs; }
  656. State state() const { return m_state; }
  657. StringView state_string() const;
  658. VirtualAddress thread_specific_data() const { return m_thread_specific_data; }
  659. ALWAYS_INLINE void yield_if_should_be_stopped()
  660. {
  661. // A thread may continue to execute in user land until the next timer
  662. // tick or until entering the next system call/exiting the current one.
  663. if (!is_stopped() && should_be_stopped()) {
  664. SpinlockLocker scheduler_lock(g_scheduler_lock);
  665. set_state(State::Stopped);
  666. }
  667. // If we're stopped, we need to yield to someone else.
  668. SpinlockLocker lock(m_lock);
  669. while (is_stopped()) {
  670. lock.unlock();
  671. // We shouldn't be holding the big lock here
  672. yield_without_releasing_big_lock();
  673. lock.lock();
  674. }
  675. }
  676. void block(Kernel::Mutex&, SpinlockLocker<Spinlock<LockRank::None>>&, u32);
  677. template<typename BlockerType, class... Args>
  678. BlockResult block(BlockTimeout const& timeout, Args&&... args)
  679. {
  680. BlockerType blocker(forward<Args>(args)...);
  681. return block_impl(timeout, blocker);
  682. }
  683. u32 unblock_from_mutex(Kernel::Mutex&);
  684. void unblock_from_blocker(Blocker&);
  685. void unblock(u8 signal = 0);
  686. template<class... Args>
  687. Thread::BlockResult wait_on(WaitQueue& wait_queue, Thread::BlockTimeout const& timeout, Args&&... args)
  688. {
  689. VERIFY(this == Thread::current());
  690. return block<Thread::WaitQueueBlocker>(timeout, wait_queue, forward<Args>(args)...);
  691. }
  692. BlockResult sleep(clockid_t, Duration const&, Duration* = nullptr);
  693. BlockResult sleep(Duration const& duration, Duration* remaining_time = nullptr)
  694. {
  695. return sleep(CLOCK_MONOTONIC_COARSE, duration, remaining_time);
  696. }
  697. BlockResult sleep_until(clockid_t, Duration const&);
  698. BlockResult sleep_until(Duration const& duration)
  699. {
  700. return sleep_until(CLOCK_MONOTONIC_COARSE, duration);
  701. }
  702. // Tell this thread to unblock if needed,
  703. // gracefully unwind the stack and die.
  704. void set_should_die();
  705. [[nodiscard]] bool should_die() const { return m_should_die; }
  706. void die_if_needed();
  707. void exit(void* = nullptr);
  708. void update_time_scheduled(u64, bool, bool);
  709. bool tick();
  710. void set_ticks_left(u32 t) { m_ticks_left = t; }
  711. u32 ticks_left() const { return m_ticks_left; }
  712. FlatPtr kernel_stack_base() const { return m_kernel_stack_base; }
  713. FlatPtr kernel_stack_top() const { return m_kernel_stack_top; }
  714. void set_state(State, u8 = 0);
  715. [[nodiscard]] bool is_initialized() const { return m_initialized; }
  716. void set_initialized(bool initialized) { m_initialized = initialized; }
  717. void send_urgent_signal_to_self(u8 signal);
  718. void send_signal(u8 signal, Process* sender);
  719. u32 update_signal_mask(u32 signal_mask);
  720. u32 signal_mask_block(sigset_t signal_set, bool block);
  721. u32 signal_mask() const;
  722. void reset_signals_for_exec();
  723. ErrorOr<FlatPtr> peek_debug_register(u32 register_index);
  724. ErrorOr<void> poke_debug_register(u32 register_index, FlatPtr data);
  725. void set_dump_backtrace_on_finalization() { m_dump_backtrace_on_finalization = true; }
  726. DispatchSignalResult dispatch_one_pending_signal();
  727. DispatchSignalResult try_dispatch_one_pending_signal(u8 signal);
  728. DispatchSignalResult dispatch_signal(u8 signal);
  729. void check_dispatch_pending_signal();
  730. [[nodiscard]] bool has_unmasked_pending_signals() const { return m_have_any_unmasked_pending_signals.load(AK::memory_order_consume); }
  731. [[nodiscard]] bool should_ignore_signal(u8 signal) const;
  732. [[nodiscard]] bool has_signal_handler(u8 signal) const;
  733. [[nodiscard]] bool is_signal_masked(u8 signal) const;
  734. u32 pending_signals() const;
  735. u32 pending_signals_for_state() 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. void print_backtrace();
  887. Blocker const* blocker() const { return m_blocker; }
  888. Kernel::Mutex const* blocking_mutex() const { return m_blocking_mutex; }
  889. #if LOCK_DEBUG
  890. struct HoldingLockInfo {
  891. Mutex* lock;
  892. LockLocation lock_location;
  893. unsigned count;
  894. };
  895. template<IteratorFunction<HoldingLockInfo const&> Callback>
  896. void for_each_held_lock(Callback);
  897. template<VoidFunction<HoldingLockInfo const&> Callback>
  898. void for_each_held_lock(Callback);
  899. #endif
  900. private:
  901. Thread(NonnullRefPtr<Process>, NonnullOwnPtr<Memory::Region>, NonnullRefPtr<Timer>);
  902. BlockResult block_impl(BlockTimeout const&, Blocker&);
  903. IntrusiveListNode<Thread> m_process_thread_list_node;
  904. int m_runnable_priority { -1 };
  905. friend class WaitQueue;
  906. class JoinBlockerSet final : public BlockerSet {
  907. public:
  908. void thread_did_exit(void* exit_value)
  909. {
  910. SpinlockLocker lock(m_lock);
  911. VERIFY(!m_thread_did_exit);
  912. m_thread_did_exit = true;
  913. m_exit_value.store(exit_value, AK::MemoryOrder::memory_order_release);
  914. do_unblock_joiner();
  915. }
  916. void thread_finalizing()
  917. {
  918. SpinlockLocker lock(m_lock);
  919. do_unblock_joiner();
  920. }
  921. void* exit_value() const
  922. {
  923. VERIFY(m_thread_did_exit);
  924. return m_exit_value.load(AK::MemoryOrder::memory_order_acquire);
  925. }
  926. void try_unblock(JoinBlocker& blocker)
  927. {
  928. SpinlockLocker lock(m_lock);
  929. if (m_thread_did_exit)
  930. blocker.unblock(exit_value(), false);
  931. }
  932. protected:
  933. virtual bool should_add_blocker(Blocker& b, void*) override
  934. {
  935. VERIFY(b.blocker_type() == Blocker::Type::Join);
  936. auto& blocker = static_cast<JoinBlocker&>(b);
  937. // NOTE: m_lock is held already!
  938. if (m_thread_did_exit) {
  939. blocker.unblock(exit_value(), true);
  940. return false;
  941. }
  942. return true;
  943. }
  944. private:
  945. void do_unblock_joiner()
  946. {
  947. unblock_all_blockers_whose_conditions_are_met_locked([&](Blocker& b, void*, bool&) {
  948. VERIFY(b.blocker_type() == Blocker::Type::Join);
  949. auto& blocker = static_cast<JoinBlocker&>(b);
  950. return blocker.unblock(exit_value(), false);
  951. });
  952. }
  953. Atomic<void*> m_exit_value { nullptr };
  954. bool m_thread_did_exit { false };
  955. };
  956. LockMode unlock_process_if_locked(u32&);
  957. void relock_process(LockMode, u32);
  958. void reset_fpu_state();
  959. mutable RecursiveSpinlock<LockRank::Thread> m_lock {};
  960. mutable RecursiveSpinlock<LockRank::None> m_block_lock {};
  961. NonnullRefPtr<Process> const m_process;
  962. ThreadID m_tid { -1 };
  963. ThreadRegisters m_regs {};
  964. DebugRegisterState m_debug_register_state {};
  965. TrapFrame* m_current_trap { nullptr };
  966. u32 m_saved_critical { 1 };
  967. IntrusiveListNode<Thread> m_ready_queue_node;
  968. Atomic<u32> m_cpu { 0 };
  969. u32 m_cpu_affinity { THREAD_AFFINITY_DEFAULT };
  970. Optional<u64> m_last_time_scheduled;
  971. Atomic<u64> m_total_time_scheduled_user { 0 };
  972. Atomic<u64> m_total_time_scheduled_kernel { 0 };
  973. u32 m_ticks_left { 0 };
  974. u32 m_times_scheduled { 0 };
  975. u32 m_ticks_in_user { 0 };
  976. u32 m_ticks_in_kernel { 0 };
  977. u32 m_pending_signals { 0 };
  978. u8 m_currently_handled_signal { 0 };
  979. u32 m_signal_mask { 0 };
  980. Optional<Memory::VirtualRange> m_alternative_signal_stack;
  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. #ifdef ENABLE_KERNEL_COVERAGE_COLLECTION
  1045. // Used by __sanitizer_cov_trace_pc to identify traced threads.
  1046. bool m_kcov_enabled { false };
  1047. # ifdef ENABLE_KERNEL_COVERAGE_COLLECTION_DEBUG
  1048. // Used by __sanitizer_cov_trace_pc to detect an infinite recursion.
  1049. bool m_kcov_recursion_hint { false };
  1050. # endif
  1051. #endif
  1052. };
  1053. AK_ENUM_BITWISE_OPERATORS(Thread::FileBlocker::BlockFlags);
  1054. template<IteratorFunction<Thread&> Callback>
  1055. inline IterationDecision Thread::for_each_ignoring_jails(Callback callback)
  1056. {
  1057. return Thread::all_instances().with([&](auto& list) -> IterationDecision {
  1058. for (auto& thread : list) {
  1059. IterationDecision decision = callback(thread);
  1060. if (decision != IterationDecision::Continue)
  1061. return decision;
  1062. }
  1063. return IterationDecision::Continue;
  1064. });
  1065. }
  1066. template<IteratorFunction<Thread&> Callback>
  1067. inline IterationDecision Thread::for_each_in_state_ignoring_jails(State state, Callback callback)
  1068. {
  1069. return Thread::all_instances().with([&](auto& list) -> IterationDecision {
  1070. for (auto& thread : list) {
  1071. if (thread.state() != state)
  1072. continue;
  1073. IterationDecision decision = callback(thread);
  1074. if (decision != IterationDecision::Continue)
  1075. return decision;
  1076. }
  1077. return IterationDecision::Continue;
  1078. });
  1079. }
  1080. template<VoidFunction<Thread&> Callback>
  1081. inline IterationDecision Thread::for_each_ignoring_jails(Callback callback)
  1082. {
  1083. return Thread::all_instances().with([&](auto& list) {
  1084. for (auto& thread : list) {
  1085. if (callback(thread) == IterationDecision::Break)
  1086. return IterationDecision::Break;
  1087. }
  1088. return IterationDecision::Continue;
  1089. });
  1090. }
  1091. template<VoidFunction<Thread&> Callback>
  1092. inline IterationDecision Thread::for_each_in_state_ignoring_jails(State state, Callback callback)
  1093. {
  1094. return for_each_in_state_ignoring_jails(state, [&](auto& thread) {
  1095. callback(thread);
  1096. return IterationDecision::Continue;
  1097. });
  1098. }
  1099. #if LOCK_DEBUG
  1100. template<IteratorFunction<Thread::HoldingLockInfo const&> Callback>
  1101. inline void Thread::for_each_held_lock(Callback callback)
  1102. {
  1103. SpinlockLocker list_lock(m_holding_locks_lock);
  1104. for (auto const& lock_info : m_holding_locks_list) {
  1105. if (callback(lock_info) == IterationDecision::Break)
  1106. break;
  1107. }
  1108. }
  1109. template<VoidFunction<Thread::HoldingLockInfo const&> Callback>
  1110. inline void Thread::for_each_held_lock(Callback callback)
  1111. {
  1112. for_each_held_lock([&](auto const& lock_info) {
  1113. callback(lock_info);
  1114. return IterationDecision::Continue;
  1115. });
  1116. }
  1117. #endif
  1118. }
  1119. template<>
  1120. struct AK::Formatter<Kernel::Thread> : AK::Formatter<FormatString> {
  1121. ErrorOr<void> format(FormatBuilder&, Kernel::Thread const&);
  1122. };