Thread.h 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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/HashMap.h>
  10. #include <AK/IntrusiveList.h>
  11. #include <AK/Optional.h>
  12. #include <AK/OwnPtr.h>
  13. #include <AK/String.h>
  14. #include <AK/Time.h>
  15. #include <AK/Vector.h>
  16. #include <AK/WeakPtr.h>
  17. #include <AK/Weakable.h>
  18. #include <Kernel/Arch/x86/RegisterState.h>
  19. #include <Kernel/Arch/x86/SafeMem.h>
  20. #include <Kernel/Debug.h>
  21. #include <Kernel/FileSystem/InodeIdentifier.h>
  22. #include <Kernel/Forward.h>
  23. #include <Kernel/KResult.h>
  24. #include <Kernel/KString.h>
  25. #include <Kernel/Library/ListedRefCounted.h>
  26. #include <Kernel/Locking/LockLocation.h>
  27. #include <Kernel/Locking/LockMode.h>
  28. #include <Kernel/Locking/SpinlockProtected.h>
  29. #include <Kernel/Memory/VirtualRange.h>
  30. #include <Kernel/Scheduler.h>
  31. #include <Kernel/TimerQueue.h>
  32. #include <Kernel/UnixTypes.h>
  33. #include <LibC/fd_set.h>
  34. #include <LibC/signal_numbers.h>
  35. namespace Kernel {
  36. namespace Memory {
  37. extern RecursiveSpinlock s_mm_lock;
  38. }
  39. enum class DispatchSignalResult {
  40. Deferred = 0,
  41. Yield,
  42. Terminate,
  43. Continue
  44. };
  45. struct SignalActionData {
  46. VirtualAddress handler_or_sigaction;
  47. u32 mask { 0 };
  48. int flags { 0 };
  49. };
  50. struct ThreadSpecificData {
  51. ThreadSpecificData* self;
  52. };
  53. #define THREAD_PRIORITY_MIN 1
  54. #define THREAD_PRIORITY_LOW 10
  55. #define THREAD_PRIORITY_NORMAL 30
  56. #define THREAD_PRIORITY_HIGH 50
  57. #define THREAD_PRIORITY_MAX 99
  58. #define THREAD_AFFINITY_DEFAULT 0xffffffff
  59. struct ThreadRegisters {
  60. #if ARCH(I386)
  61. FlatPtr ss;
  62. FlatPtr gs;
  63. FlatPtr fs;
  64. FlatPtr es;
  65. FlatPtr ds;
  66. FlatPtr edi;
  67. FlatPtr esi;
  68. FlatPtr ebp;
  69. FlatPtr esp;
  70. FlatPtr ebx;
  71. FlatPtr edx;
  72. FlatPtr ecx;
  73. FlatPtr eax;
  74. FlatPtr eip;
  75. FlatPtr esp0;
  76. FlatPtr ss0;
  77. #else
  78. FlatPtr rdi;
  79. FlatPtr rsi;
  80. FlatPtr rbp;
  81. FlatPtr rsp;
  82. FlatPtr rbx;
  83. FlatPtr rdx;
  84. FlatPtr rcx;
  85. FlatPtr rax;
  86. FlatPtr r8;
  87. FlatPtr r9;
  88. FlatPtr r10;
  89. FlatPtr r11;
  90. FlatPtr r12;
  91. FlatPtr r13;
  92. FlatPtr r14;
  93. FlatPtr r15;
  94. FlatPtr rip;
  95. FlatPtr rsp0;
  96. #endif
  97. FlatPtr cs;
  98. #if ARCH(I386)
  99. FlatPtr eflags;
  100. FlatPtr flags() const { return eflags; }
  101. void set_flags(FlatPtr value) { eflags = value; }
  102. void set_sp(FlatPtr value) { esp = value; }
  103. void set_sp0(FlatPtr value) { esp0 = value; }
  104. void set_ip(FlatPtr value) { eip = value; }
  105. #else
  106. FlatPtr rflags;
  107. FlatPtr flags() const { return rflags; }
  108. void set_flags(FlatPtr value) { rflags = value; }
  109. void set_sp(FlatPtr value) { rsp = value; }
  110. void set_sp0(FlatPtr value) { rsp0 = value; }
  111. void set_ip(FlatPtr value) { rip = value; }
  112. #endif
  113. FlatPtr cr3;
  114. FlatPtr ip() const
  115. {
  116. #if ARCH(I386)
  117. return eip;
  118. #else
  119. return rip;
  120. #endif
  121. }
  122. FlatPtr sp() const
  123. {
  124. #if ARCH(I386)
  125. return esp;
  126. #else
  127. return rsp;
  128. #endif
  129. }
  130. };
  131. class Thread
  132. : public ListedRefCounted<Thread>
  133. , public Weakable<Thread> {
  134. AK_MAKE_NONCOPYABLE(Thread);
  135. AK_MAKE_NONMOVABLE(Thread);
  136. friend class Mutex;
  137. friend class Process;
  138. friend class ProtectedProcessBase;
  139. friend class Scheduler;
  140. friend struct ThreadReadyQueue;
  141. public:
  142. inline static Thread* current()
  143. {
  144. return Processor::current_thread();
  145. }
  146. static void initialize();
  147. static KResultOr<NonnullRefPtr<Thread>> try_create(NonnullRefPtr<Process>);
  148. ~Thread();
  149. static RefPtr<Thread> from_tid(ThreadID);
  150. static void finalize_dying_threads();
  151. ThreadID tid() const { return m_tid; }
  152. ProcessID pid() const;
  153. void set_priority(u32 p) { m_priority = p; }
  154. u32 priority() const { return m_priority; }
  155. void detach()
  156. {
  157. SpinlockLocker lock(m_lock);
  158. m_is_joinable = false;
  159. }
  160. [[nodiscard]] bool is_joinable() const
  161. {
  162. SpinlockLocker lock(m_lock);
  163. return m_is_joinable;
  164. }
  165. Process& process() { return m_process; }
  166. const Process& process() const { return m_process; }
  167. // NOTE: This returns a null-terminated string.
  168. StringView name() const
  169. {
  170. // NOTE: Whoever is calling this needs to be holding our lock while reading the name.
  171. VERIFY(m_lock.own_lock());
  172. return m_name ? m_name->view() : StringView {};
  173. }
  174. void set_name(OwnPtr<KString> name)
  175. {
  176. SpinlockLocker lock(m_lock);
  177. m_name = move(name);
  178. }
  179. void finalize();
  180. enum State : u8 {
  181. Invalid = 0,
  182. Runnable,
  183. Running,
  184. Dying,
  185. Dead,
  186. Stopped,
  187. Blocked
  188. };
  189. class [[nodiscard]] BlockResult {
  190. public:
  191. enum Type {
  192. WokeNormally,
  193. NotBlocked,
  194. InterruptedBySignal,
  195. InterruptedByDeath,
  196. InterruptedByTimeout,
  197. };
  198. BlockResult() = delete;
  199. BlockResult(Type type)
  200. : m_type(type)
  201. {
  202. }
  203. bool operator==(Type type) const
  204. {
  205. return m_type == type;
  206. }
  207. bool operator!=(Type type) const
  208. {
  209. return m_type != type;
  210. }
  211. [[nodiscard]] bool was_interrupted() const
  212. {
  213. switch (m_type) {
  214. case InterruptedBySignal:
  215. case InterruptedByDeath:
  216. return true;
  217. default:
  218. return false;
  219. }
  220. }
  221. [[nodiscard]] bool timed_out() const
  222. {
  223. return m_type == InterruptedByTimeout;
  224. }
  225. private:
  226. Type m_type;
  227. };
  228. class BlockTimeout {
  229. public:
  230. BlockTimeout()
  231. : m_infinite(true)
  232. {
  233. }
  234. explicit BlockTimeout(bool is_absolute, const Time* time, const Time* start_time = nullptr, clockid_t clock_id = CLOCK_MONOTONIC_COARSE);
  235. const Time& absolute_time() const { return m_time; }
  236. const Time* start_time() const { return !m_infinite ? &m_start_time : nullptr; }
  237. clockid_t clock_id() const { return m_clock_id; }
  238. bool is_infinite() const { return m_infinite; }
  239. bool should_block() const { return m_infinite || m_should_block; };
  240. private:
  241. Time m_time {};
  242. Time m_start_time {};
  243. clockid_t m_clock_id { CLOCK_MONOTONIC_COARSE };
  244. bool m_infinite { false };
  245. bool m_should_block { false };
  246. };
  247. class BlockCondition;
  248. class Blocker {
  249. public:
  250. enum class Type {
  251. Unknown = 0,
  252. File,
  253. Futex,
  254. Plan9FS,
  255. Join,
  256. Queue,
  257. Routing,
  258. Sleep,
  259. Wait
  260. };
  261. virtual ~Blocker();
  262. virtual StringView state_string() const = 0;
  263. virtual bool should_block() { return true; }
  264. virtual Type blocker_type() const = 0;
  265. virtual const BlockTimeout& override_timeout(const BlockTimeout& timeout) { return timeout; }
  266. virtual bool can_be_interrupted() const { return true; }
  267. virtual void not_blocking(bool) = 0;
  268. virtual void was_unblocked(bool did_timeout)
  269. {
  270. if (did_timeout) {
  271. SpinlockLocker lock(m_lock);
  272. m_did_timeout = true;
  273. }
  274. }
  275. void set_interrupted_by_death()
  276. {
  277. SpinlockLocker lock(m_lock);
  278. do_set_interrupted_by_death();
  279. }
  280. void set_interrupted_by_signal(u8 signal)
  281. {
  282. SpinlockLocker lock(m_lock);
  283. do_set_interrupted_by_signal(signal);
  284. }
  285. u8 was_interrupted_by_signal() const
  286. {
  287. SpinlockLocker lock(m_lock);
  288. return do_get_interrupted_by_signal();
  289. }
  290. virtual Thread::BlockResult block_result()
  291. {
  292. SpinlockLocker lock(m_lock);
  293. if (m_was_interrupted_by_death)
  294. return Thread::BlockResult::InterruptedByDeath;
  295. if (m_was_interrupted_by_signal != 0)
  296. return Thread::BlockResult::InterruptedBySignal;
  297. if (m_did_timeout)
  298. return Thread::BlockResult::InterruptedByTimeout;
  299. return Thread::BlockResult::WokeNormally;
  300. }
  301. void begin_blocking(Badge<Thread>);
  302. BlockResult end_blocking(Badge<Thread>, bool);
  303. protected:
  304. void do_set_interrupted_by_death()
  305. {
  306. m_was_interrupted_by_death = true;
  307. }
  308. void do_set_interrupted_by_signal(u8 signal)
  309. {
  310. VERIFY(signal != 0);
  311. m_was_interrupted_by_signal = signal;
  312. }
  313. void do_clear_interrupted_by_signal()
  314. {
  315. m_was_interrupted_by_signal = 0;
  316. }
  317. u8 do_get_interrupted_by_signal() const
  318. {
  319. return m_was_interrupted_by_signal;
  320. }
  321. [[nodiscard]] bool was_interrupted() const
  322. {
  323. return m_was_interrupted_by_death || m_was_interrupted_by_signal != 0;
  324. }
  325. void unblock_from_blocker()
  326. {
  327. RefPtr<Thread> thread;
  328. {
  329. SpinlockLocker lock(m_lock);
  330. if (m_is_blocking) {
  331. m_is_blocking = false;
  332. VERIFY(m_blocked_thread);
  333. thread = m_blocked_thread;
  334. }
  335. }
  336. if (thread)
  337. thread->unblock_from_blocker(*this);
  338. }
  339. bool set_block_condition(BlockCondition&, void* = nullptr);
  340. void set_block_condition_raw_locked(BlockCondition* block_condition)
  341. {
  342. m_block_condition = block_condition;
  343. }
  344. mutable RecursiveSpinlock m_lock;
  345. private:
  346. BlockCondition* m_block_condition { nullptr };
  347. void* m_block_data { nullptr };
  348. Thread* m_blocked_thread { nullptr };
  349. u8 m_was_interrupted_by_signal { 0 };
  350. bool m_is_blocking { false };
  351. bool m_was_interrupted_by_death { false };
  352. bool m_did_timeout { false };
  353. };
  354. class BlockCondition {
  355. AK_MAKE_NONCOPYABLE(BlockCondition);
  356. AK_MAKE_NONMOVABLE(BlockCondition);
  357. public:
  358. BlockCondition() = default;
  359. virtual ~BlockCondition()
  360. {
  361. SpinlockLocker lock(m_lock);
  362. VERIFY(m_blockers.is_empty());
  363. }
  364. bool add_blocker(Blocker& blocker, void* data)
  365. {
  366. SpinlockLocker lock(m_lock);
  367. if (!should_add_blocker(blocker, data))
  368. return false;
  369. m_blockers.append({ &blocker, data });
  370. return true;
  371. }
  372. void remove_blocker(Blocker& blocker, void* data)
  373. {
  374. SpinlockLocker lock(m_lock);
  375. // NOTE: it's possible that the blocker is no longer present
  376. m_blockers.remove_first_matching([&](auto& info) {
  377. return info.blocker == &blocker && info.data == data;
  378. });
  379. }
  380. bool is_empty() const
  381. {
  382. SpinlockLocker lock(m_lock);
  383. return is_empty_locked();
  384. }
  385. protected:
  386. template<typename UnblockOne>
  387. bool unblock(UnblockOne unblock_one)
  388. {
  389. SpinlockLocker lock(m_lock);
  390. return do_unblock(unblock_one);
  391. }
  392. template<typename UnblockOne>
  393. bool do_unblock(UnblockOne unblock_one)
  394. {
  395. VERIFY(m_lock.is_locked());
  396. bool stop_iterating = false;
  397. bool did_unblock = false;
  398. for (size_t i = 0; i < m_blockers.size() && !stop_iterating;) {
  399. auto& info = m_blockers[i];
  400. if (unblock_one(*info.blocker, info.data, stop_iterating)) {
  401. m_blockers.remove(i);
  402. did_unblock = true;
  403. continue;
  404. }
  405. i++;
  406. }
  407. return did_unblock;
  408. }
  409. bool is_empty_locked() const
  410. {
  411. VERIFY(m_lock.is_locked());
  412. return m_blockers.is_empty();
  413. }
  414. virtual bool should_add_blocker(Blocker&, void*) { return true; }
  415. struct BlockerInfo {
  416. Blocker* blocker;
  417. void* data;
  418. };
  419. Vector<BlockerInfo, 4> do_take_blockers(size_t count)
  420. {
  421. if (m_blockers.size() <= count)
  422. return move(m_blockers);
  423. size_t move_count = (count <= m_blockers.size()) ? count : m_blockers.size();
  424. VERIFY(move_count > 0);
  425. Vector<BlockerInfo, 4> taken_blockers;
  426. taken_blockers.ensure_capacity(move_count);
  427. for (size_t i = 0; i < move_count; i++)
  428. taken_blockers.append(m_blockers.take(i));
  429. m_blockers.remove(0, move_count);
  430. return taken_blockers;
  431. }
  432. void do_append_blockers(Vector<BlockerInfo, 4>&& blockers_to_append)
  433. {
  434. if (blockers_to_append.is_empty())
  435. return;
  436. if (m_blockers.is_empty()) {
  437. m_blockers = move(blockers_to_append);
  438. return;
  439. }
  440. m_blockers.ensure_capacity(m_blockers.size() + blockers_to_append.size());
  441. for (size_t i = 0; i < blockers_to_append.size(); i++)
  442. m_blockers.append(blockers_to_append.take(i));
  443. blockers_to_append.clear();
  444. }
  445. mutable Spinlock<u8> m_lock;
  446. private:
  447. Vector<BlockerInfo, 4> m_blockers;
  448. };
  449. friend class JoinBlocker;
  450. class JoinBlocker final : public Blocker {
  451. public:
  452. explicit JoinBlocker(Thread& joinee, KResult& try_join_result, void*& joinee_exit_value);
  453. virtual Type blocker_type() const override { return Type::Join; }
  454. virtual StringView state_string() const override { return "Joining"sv; }
  455. virtual bool can_be_interrupted() const override { return false; }
  456. virtual bool should_block() override { return !m_join_error && m_should_block; }
  457. virtual void not_blocking(bool) override;
  458. bool unblock(void*, bool);
  459. private:
  460. NonnullRefPtr<Thread> m_joinee;
  461. void*& m_joinee_exit_value;
  462. bool m_join_error { false };
  463. bool m_did_unblock { false };
  464. bool m_should_block { true };
  465. };
  466. class QueueBlocker : public Blocker {
  467. public:
  468. explicit QueueBlocker(WaitQueue&, StringView block_reason = {});
  469. virtual ~QueueBlocker();
  470. virtual Type blocker_type() const override { return Type::Queue; }
  471. virtual StringView state_string() const override { return m_block_reason.is_null() ? m_block_reason : "Queue"sv; }
  472. virtual void not_blocking(bool) override { }
  473. virtual bool should_block() override
  474. {
  475. return m_should_block;
  476. }
  477. bool unblock();
  478. protected:
  479. StringView m_block_reason;
  480. bool m_should_block { true };
  481. bool m_did_unblock { false };
  482. };
  483. class FutexBlocker : public Blocker {
  484. public:
  485. explicit FutexBlocker(FutexQueue&, u32);
  486. virtual ~FutexBlocker();
  487. virtual Type blocker_type() const override { return Type::Futex; }
  488. virtual StringView state_string() const override { return "Futex"sv; }
  489. virtual void not_blocking(bool) override { }
  490. virtual bool should_block() override
  491. {
  492. return m_should_block;
  493. }
  494. u32 bitset() const { return m_bitset; }
  495. void begin_requeue()
  496. {
  497. // We need to hold the lock until we moved it over
  498. m_relock_flags = m_lock.lock();
  499. }
  500. void finish_requeue(FutexQueue&);
  501. bool unblock_bitset(u32 bitset);
  502. bool unblock(bool force = false);
  503. protected:
  504. u32 m_bitset;
  505. u32 m_relock_flags { 0 };
  506. bool m_should_block { true };
  507. bool m_did_unblock { false };
  508. };
  509. class FileBlocker : public Blocker {
  510. public:
  511. enum class BlockFlags : u16 {
  512. None = 0,
  513. Read = 1 << 0,
  514. Write = 1 << 1,
  515. ReadPriority = 1 << 2,
  516. Accept = 1 << 3,
  517. Connect = 1 << 4,
  518. SocketFlags = Accept | Connect,
  519. WriteNotOpen = 1 << 5,
  520. WriteError = 1 << 6,
  521. WriteHangUp = 1 << 7,
  522. ReadHangUp = 1 << 8,
  523. Exception = WriteNotOpen | WriteError | WriteHangUp | ReadHangUp,
  524. };
  525. virtual Type blocker_type() const override { return Type::File; }
  526. virtual bool should_block() override
  527. {
  528. return m_should_block;
  529. }
  530. virtual bool unblock(bool, void*) = 0;
  531. protected:
  532. bool m_should_block { true };
  533. };
  534. class FileDescriptionBlocker : public FileBlocker {
  535. public:
  536. const FileDescription& blocked_description() const;
  537. virtual bool unblock(bool, void*) override;
  538. virtual void not_blocking(bool) override;
  539. protected:
  540. explicit FileDescriptionBlocker(FileDescription&, BlockFlags, BlockFlags&);
  541. private:
  542. NonnullRefPtr<FileDescription> m_blocked_description;
  543. const BlockFlags m_flags;
  544. BlockFlags& m_unblocked_flags;
  545. bool m_did_unblock { false };
  546. };
  547. class AcceptBlocker final : public FileDescriptionBlocker {
  548. public:
  549. explicit AcceptBlocker(FileDescription&, BlockFlags&);
  550. virtual StringView state_string() const override { return "Accepting"sv; }
  551. };
  552. class ConnectBlocker final : public FileDescriptionBlocker {
  553. public:
  554. explicit ConnectBlocker(FileDescription&, BlockFlags&);
  555. virtual StringView state_string() const override { return "Connecting"sv; }
  556. };
  557. class WriteBlocker final : public FileDescriptionBlocker {
  558. public:
  559. explicit WriteBlocker(FileDescription&, BlockFlags&);
  560. virtual StringView state_string() const override { return "Writing"sv; }
  561. virtual const BlockTimeout& override_timeout(const BlockTimeout&) override;
  562. private:
  563. BlockTimeout m_timeout;
  564. };
  565. class ReadBlocker final : public FileDescriptionBlocker {
  566. public:
  567. explicit ReadBlocker(FileDescription&, BlockFlags&);
  568. virtual StringView state_string() const override { return "Reading"sv; }
  569. virtual const BlockTimeout& override_timeout(const BlockTimeout&) override;
  570. private:
  571. BlockTimeout m_timeout;
  572. };
  573. class SleepBlocker final : public Blocker {
  574. public:
  575. explicit SleepBlocker(const BlockTimeout&, Time* = nullptr);
  576. virtual StringView state_string() const override { return "Sleeping"sv; }
  577. virtual Type blocker_type() const override { return Type::Sleep; }
  578. virtual const BlockTimeout& override_timeout(const BlockTimeout&) override;
  579. virtual void not_blocking(bool) override;
  580. virtual void was_unblocked(bool) override;
  581. virtual Thread::BlockResult block_result() override;
  582. private:
  583. void calculate_remaining();
  584. BlockTimeout m_deadline;
  585. Time* m_remaining;
  586. };
  587. class SelectBlocker final : public FileBlocker {
  588. public:
  589. struct FDInfo {
  590. NonnullRefPtr<FileDescription> description;
  591. BlockFlags block_flags { BlockFlags::None };
  592. BlockFlags unblocked_flags { BlockFlags::None };
  593. };
  594. typedef Vector<FDInfo, FD_SETSIZE> FDVector;
  595. SelectBlocker(FDVector& fds);
  596. virtual ~SelectBlocker();
  597. virtual bool unblock(bool, void*) override;
  598. virtual void not_blocking(bool) override;
  599. virtual void was_unblocked(bool) override;
  600. virtual StringView state_string() const override { return "Selecting"sv; }
  601. private:
  602. size_t collect_unblocked_flags();
  603. FDVector& m_fds;
  604. bool m_did_unblock { false };
  605. };
  606. class WaitBlocker final : public Blocker {
  607. public:
  608. enum class UnblockFlags {
  609. Terminated,
  610. Stopped,
  611. Continued,
  612. Disowned
  613. };
  614. WaitBlocker(int wait_options, idtype_t id_type, pid_t id, KResultOr<siginfo_t>& result);
  615. virtual StringView state_string() const override { return "Waiting"sv; }
  616. virtual Type blocker_type() const override { return Type::Wait; }
  617. virtual bool should_block() override { return m_should_block; }
  618. virtual void not_blocking(bool) override;
  619. virtual void was_unblocked(bool) override;
  620. bool unblock(Process& process, UnblockFlags flags, u8 signal, bool from_add_blocker);
  621. bool is_wait() const { return !(m_wait_options & WNOWAIT); }
  622. private:
  623. void do_was_disowned();
  624. void do_set_result(const siginfo_t&);
  625. const int m_wait_options;
  626. const idtype_t m_id_type;
  627. const pid_t m_waitee_id;
  628. KResultOr<siginfo_t>& m_result;
  629. RefPtr<Process> m_waitee;
  630. RefPtr<ProcessGroup> m_waitee_group;
  631. bool m_did_unblock { false };
  632. bool m_error { false };
  633. bool m_got_sigchild { false };
  634. bool m_should_block;
  635. };
  636. class WaitBlockCondition final : public BlockCondition {
  637. friend class WaitBlocker;
  638. public:
  639. WaitBlockCondition(Process& process)
  640. : m_process(process)
  641. {
  642. }
  643. void disowned_by_waiter(Process&);
  644. bool unblock(Process&, WaitBlocker::UnblockFlags, u8);
  645. void try_unblock(WaitBlocker&);
  646. void finalize();
  647. protected:
  648. virtual bool should_add_blocker(Blocker&, void*) override;
  649. private:
  650. struct ProcessBlockInfo {
  651. NonnullRefPtr<Process> process;
  652. WaitBlocker::UnblockFlags flags;
  653. u8 signal;
  654. bool was_waited { false };
  655. explicit ProcessBlockInfo(NonnullRefPtr<Process>&&, WaitBlocker::UnblockFlags, u8);
  656. ~ProcessBlockInfo();
  657. };
  658. Process& m_process;
  659. Vector<ProcessBlockInfo, 2> m_processes;
  660. bool m_finalized { false };
  661. };
  662. template<typename AddBlockerHandler>
  663. KResult try_join(AddBlockerHandler add_blocker)
  664. {
  665. if (Thread::current() == this)
  666. return EDEADLK;
  667. SpinlockLocker lock(m_lock);
  668. if (!m_is_joinable || state() == Dead)
  669. return EINVAL;
  670. add_blocker();
  671. // From this point on the thread is no longer joinable by anyone
  672. // else. It also means that if the join is timed, it becomes
  673. // detached when a timeout happens.
  674. m_is_joinable = false;
  675. return KSuccess;
  676. }
  677. void did_schedule() { ++m_times_scheduled; }
  678. u32 times_scheduled() const { return m_times_scheduled; }
  679. void resume_from_stopped();
  680. [[nodiscard]] bool should_be_stopped() const;
  681. [[nodiscard]] bool is_stopped() const { return m_state == Stopped; }
  682. [[nodiscard]] bool is_blocked() const { return m_state == Blocked; }
  683. [[nodiscard]] bool is_in_block() const
  684. {
  685. SpinlockLocker lock(m_block_lock);
  686. return m_in_block;
  687. }
  688. u32 cpu() const { return m_cpu.load(AK::MemoryOrder::memory_order_consume); }
  689. void set_cpu(u32 cpu) { m_cpu.store(cpu, AK::MemoryOrder::memory_order_release); }
  690. u32 affinity() const { return m_cpu_affinity; }
  691. void set_affinity(u32 affinity) { m_cpu_affinity = affinity; }
  692. RegisterState& get_register_dump_from_stack();
  693. const RegisterState& get_register_dump_from_stack() const { return const_cast<Thread*>(this)->get_register_dump_from_stack(); }
  694. DebugRegisterState& debug_register_state() { return m_debug_register_state; }
  695. const DebugRegisterState& debug_register_state() const { return m_debug_register_state; }
  696. ThreadRegisters& regs() { return m_regs; }
  697. ThreadRegisters const& regs() const { return m_regs; }
  698. State state() const { return m_state; }
  699. StringView state_string() const;
  700. VirtualAddress thread_specific_data() const { return m_thread_specific_data; }
  701. size_t thread_specific_region_size() const;
  702. size_t thread_specific_region_alignment() const;
  703. ALWAYS_INLINE void yield_if_stopped()
  704. {
  705. // If some thread stopped us, we need to yield to someone else
  706. // We check this when entering/exiting a system call. A thread
  707. // may continue to execute in user land until the next timer
  708. // tick or entering the next system call, or if it's in kernel
  709. // mode then we will intercept prior to returning back to user
  710. // mode.
  711. SpinlockLocker lock(m_lock);
  712. while (state() == Thread::Stopped) {
  713. lock.unlock();
  714. // We shouldn't be holding the big lock here
  715. yield_without_releasing_big_lock();
  716. lock.lock();
  717. }
  718. }
  719. void block(Kernel::Mutex&, SpinlockLocker<Spinlock<u8>>&, u32);
  720. template<typename BlockerType, class... Args>
  721. [[nodiscard]] BlockResult block(const BlockTimeout& timeout, Args&&... args)
  722. {
  723. VERIFY(!Processor::current().in_irq());
  724. VERIFY(this == Thread::current());
  725. ScopedCritical critical;
  726. VERIFY(!Memory::s_mm_lock.own_lock());
  727. SpinlockLocker block_lock(m_block_lock);
  728. // We need to hold m_block_lock so that nobody can unblock a blocker as soon
  729. // as it is constructed and registered elsewhere
  730. m_in_block = true;
  731. BlockerType blocker(forward<Args>(args)...);
  732. SpinlockLocker scheduler_lock(g_scheduler_lock);
  733. // Relaxed semantics are fine for timeout_unblocked because we
  734. // synchronize on the spin locks already.
  735. Atomic<bool, AK::MemoryOrder::memory_order_relaxed> timeout_unblocked(false);
  736. bool timer_was_added = false;
  737. {
  738. switch (state()) {
  739. case Thread::Stopped:
  740. // It's possible that we were requested to be stopped!
  741. break;
  742. case Thread::Running:
  743. VERIFY(m_blocker == nullptr);
  744. break;
  745. default:
  746. VERIFY_NOT_REACHED();
  747. }
  748. m_blocker = &blocker;
  749. if (!blocker.should_block()) {
  750. // Don't block if the wake condition is already met
  751. blocker.not_blocking(false);
  752. m_blocker = nullptr;
  753. m_in_block = false;
  754. return BlockResult::NotBlocked;
  755. }
  756. auto& block_timeout = blocker.override_timeout(timeout);
  757. if (!block_timeout.is_infinite()) {
  758. // Process::kill_all_threads may be called at any time, which will mark all
  759. // threads to die. In that case
  760. timer_was_added = TimerQueue::the().add_timer_without_id(*m_block_timer, block_timeout.clock_id(), block_timeout.absolute_time(), [&]() {
  761. VERIFY(!Processor::current().in_irq());
  762. VERIFY(!g_scheduler_lock.own_lock());
  763. VERIFY(!m_block_lock.own_lock());
  764. // NOTE: this may execute on the same or any other processor!
  765. SpinlockLocker scheduler_lock(g_scheduler_lock);
  766. SpinlockLocker block_lock(m_block_lock);
  767. if (m_blocker && timeout_unblocked.exchange(true) == false)
  768. unblock();
  769. });
  770. if (!timer_was_added) {
  771. // Timeout is already in the past
  772. blocker.not_blocking(true);
  773. m_blocker = nullptr;
  774. m_in_block = false;
  775. return BlockResult::InterruptedByTimeout;
  776. }
  777. }
  778. blocker.begin_blocking({});
  779. set_state(Thread::Blocked);
  780. }
  781. scheduler_lock.unlock();
  782. block_lock.unlock();
  783. dbgln_if(THREAD_DEBUG, "Thread {} blocking on {} ({}) -->", *this, &blocker, blocker.state_string());
  784. bool did_timeout = false;
  785. u32 lock_count_to_restore = 0;
  786. auto previous_locked = unlock_process_if_locked(lock_count_to_restore);
  787. for (;;) {
  788. // Yield to the scheduler, and wait for us to resume unblocked.
  789. VERIFY(!g_scheduler_lock.own_lock());
  790. VERIFY(Processor::in_critical());
  791. yield_without_releasing_big_lock();
  792. VERIFY(Processor::in_critical());
  793. SpinlockLocker block_lock2(m_block_lock);
  794. if (should_be_stopped() || state() == Stopped) {
  795. dbgln("Thread should be stopped, current state: {}", state_string());
  796. set_state(Thread::Blocked);
  797. continue;
  798. }
  799. if (m_blocker && !m_blocker->can_be_interrupted() && !m_should_die) {
  800. block_lock2.unlock();
  801. dbgln("Thread should not be unblocking, current state: {}", state_string());
  802. set_state(Thread::Blocked);
  803. continue;
  804. }
  805. // Prevent the timeout from unblocking this thread if it happens to
  806. // be in the process of firing already
  807. did_timeout |= timeout_unblocked.exchange(true);
  808. if (m_blocker) {
  809. // Remove ourselves...
  810. VERIFY(m_blocker == &blocker);
  811. m_blocker = nullptr;
  812. }
  813. dbgln_if(THREAD_DEBUG, "<-- Thread {} unblocked from {} ({})", *this, &blocker, blocker.state_string());
  814. m_in_block = false;
  815. break;
  816. }
  817. if (blocker.was_interrupted_by_signal()) {
  818. SpinlockLocker scheduler_lock(g_scheduler_lock);
  819. SpinlockLocker lock(m_lock);
  820. dispatch_one_pending_signal();
  821. }
  822. // Notify the blocker that we are no longer blocking. It may need
  823. // to clean up now while we're still holding m_lock
  824. auto result = blocker.end_blocking({}, did_timeout); // calls was_unblocked internally
  825. if (timer_was_added && !did_timeout) {
  826. // Cancel the timer while not holding any locks. This allows
  827. // the timer function to complete before we remove it
  828. // (e.g. if it's on another processor)
  829. TimerQueue::the().cancel_timer(*m_block_timer);
  830. }
  831. if (previous_locked != LockMode::Unlocked) {
  832. // NOTE: this may trigger another call to Thread::block(), so
  833. // we need to do this after we're all done and restored m_in_block!
  834. relock_process(previous_locked, lock_count_to_restore);
  835. }
  836. return result;
  837. }
  838. u32 unblock_from_lock(Kernel::Mutex&);
  839. void unblock_from_blocker(Blocker&);
  840. void unblock(u8 signal = 0);
  841. template<class... Args>
  842. Thread::BlockResult wait_on(WaitQueue& wait_queue, const Thread::BlockTimeout& timeout, Args&&... args)
  843. {
  844. VERIFY(this == Thread::current());
  845. return block<Thread::QueueBlocker>(timeout, wait_queue, forward<Args>(args)...);
  846. }
  847. BlockResult sleep(clockid_t, const Time&, Time* = nullptr);
  848. BlockResult sleep(const Time& duration, Time* remaining_time = nullptr)
  849. {
  850. return sleep(CLOCK_MONOTONIC_COARSE, duration, remaining_time);
  851. }
  852. BlockResult sleep_until(clockid_t, const Time&);
  853. BlockResult sleep_until(const Time& duration)
  854. {
  855. return sleep_until(CLOCK_MONOTONIC_COARSE, duration);
  856. }
  857. // Tell this thread to unblock if needed,
  858. // gracefully unwind the stack and die.
  859. void set_should_die();
  860. [[nodiscard]] bool should_die() const { return m_should_die; }
  861. void die_if_needed();
  862. void exit(void* = nullptr);
  863. void update_time_scheduled(u64, bool, bool);
  864. bool tick();
  865. void set_ticks_left(u32 t) { m_ticks_left = t; }
  866. u32 ticks_left() const { return m_ticks_left; }
  867. FlatPtr kernel_stack_base() const { return m_kernel_stack_base; }
  868. FlatPtr kernel_stack_top() const { return m_kernel_stack_top; }
  869. void set_state(State, u8 = 0);
  870. [[nodiscard]] bool is_initialized() const { return m_initialized; }
  871. void set_initialized(bool initialized) { m_initialized = initialized; }
  872. void send_urgent_signal_to_self(u8 signal);
  873. void send_signal(u8 signal, Process* sender);
  874. u32 update_signal_mask(u32 signal_mask);
  875. u32 signal_mask_block(sigset_t signal_set, bool block);
  876. u32 signal_mask() const;
  877. void clear_signals();
  878. KResultOr<u32> peek_debug_register(u32 register_index);
  879. KResult poke_debug_register(u32 register_index, u32 data);
  880. void set_dump_backtrace_on_finalization() { m_dump_backtrace_on_finalization = true; }
  881. DispatchSignalResult dispatch_one_pending_signal();
  882. DispatchSignalResult try_dispatch_one_pending_signal(u8 signal);
  883. DispatchSignalResult dispatch_signal(u8 signal);
  884. void check_dispatch_pending_signal();
  885. [[nodiscard]] bool has_unmasked_pending_signals() const { return m_have_any_unmasked_pending_signals.load(AK::memory_order_consume); }
  886. [[nodiscard]] bool should_ignore_signal(u8 signal) const;
  887. [[nodiscard]] bool has_signal_handler(u8 signal) const;
  888. u32 pending_signals() const;
  889. u32 pending_signals_for_state() const;
  890. FPUState& fpu_state() { return m_fpu_state; }
  891. KResult make_thread_specific_region(Badge<Process>);
  892. unsigned syscall_count() const { return m_syscall_count; }
  893. void did_syscall() { ++m_syscall_count; }
  894. unsigned inode_faults() const { return m_inode_faults; }
  895. void did_inode_fault() { ++m_inode_faults; }
  896. unsigned zero_faults() const { return m_zero_faults; }
  897. void did_zero_fault() { ++m_zero_faults; }
  898. unsigned cow_faults() const { return m_cow_faults; }
  899. void did_cow_fault() { ++m_cow_faults; }
  900. unsigned file_read_bytes() const { return m_file_read_bytes; }
  901. unsigned file_write_bytes() const { return m_file_write_bytes; }
  902. void did_file_read(unsigned bytes)
  903. {
  904. m_file_read_bytes += bytes;
  905. }
  906. void did_file_write(unsigned bytes)
  907. {
  908. m_file_write_bytes += bytes;
  909. }
  910. unsigned unix_socket_read_bytes() const { return m_unix_socket_read_bytes; }
  911. unsigned unix_socket_write_bytes() const { return m_unix_socket_write_bytes; }
  912. void did_unix_socket_read(unsigned bytes)
  913. {
  914. m_unix_socket_read_bytes += bytes;
  915. }
  916. void did_unix_socket_write(unsigned bytes)
  917. {
  918. m_unix_socket_write_bytes += bytes;
  919. }
  920. unsigned ipv4_socket_read_bytes() const { return m_ipv4_socket_read_bytes; }
  921. unsigned ipv4_socket_write_bytes() const { return m_ipv4_socket_write_bytes; }
  922. void did_ipv4_socket_read(unsigned bytes)
  923. {
  924. m_ipv4_socket_read_bytes += bytes;
  925. }
  926. void did_ipv4_socket_write(unsigned bytes)
  927. {
  928. m_ipv4_socket_write_bytes += bytes;
  929. }
  930. void set_active(bool active) { m_is_active = active; }
  931. u32 saved_critical() const { return m_saved_critical; }
  932. void save_critical(u32 critical) { m_saved_critical = critical; }
  933. [[nodiscard]] bool is_active() const { return m_is_active; }
  934. [[nodiscard]] bool is_finalizable() const
  935. {
  936. // We can't finalize as long as this thread is still running
  937. // Note that checking for Running state here isn't sufficient
  938. // as the thread may not be in Running state but switching out.
  939. // m_is_active is set to false once the context switch is
  940. // complete and the thread is not executing on any processor.
  941. if (m_is_active.load(AK::memory_order_acquire))
  942. return false;
  943. // We can't finalize until the thread is either detached or
  944. // a join has started. We can't make m_is_joinable atomic
  945. // because that would introduce a race in try_join.
  946. SpinlockLocker lock(m_lock);
  947. return !m_is_joinable;
  948. }
  949. RefPtr<Thread> clone(Process&);
  950. template<IteratorFunction<Thread&> Callback>
  951. static IterationDecision for_each_in_state(State, Callback);
  952. template<IteratorFunction<Thread&> Callback>
  953. static IterationDecision for_each(Callback);
  954. template<VoidFunction<Thread&> Callback>
  955. static IterationDecision for_each_in_state(State, Callback);
  956. template<VoidFunction<Thread&> Callback>
  957. static IterationDecision for_each(Callback);
  958. static constexpr u32 default_kernel_stack_size = 65536;
  959. static constexpr u32 default_userspace_stack_size = 1 * MiB;
  960. u64 time_in_user() const { return m_total_time_scheduled_user; }
  961. u64 time_in_kernel() const { return m_total_time_scheduled_kernel; }
  962. enum class PreviousMode : u8 {
  963. KernelMode = 0,
  964. UserMode
  965. };
  966. PreviousMode previous_mode() const { return m_previous_mode; }
  967. bool set_previous_mode(PreviousMode mode)
  968. {
  969. if (m_previous_mode == mode)
  970. return false;
  971. m_previous_mode = mode;
  972. return true;
  973. }
  974. TrapFrame*& current_trap() { return m_current_trap; }
  975. TrapFrame const* const& current_trap() const { return m_current_trap; }
  976. RecursiveSpinlock& get_lock() const { return m_lock; }
  977. #if LOCK_DEBUG
  978. void holding_lock(Mutex& lock, int refs_delta, LockLocation const& location)
  979. {
  980. VERIFY(refs_delta != 0);
  981. m_holding_locks.fetch_add(refs_delta, AK::MemoryOrder::memory_order_relaxed);
  982. SpinlockLocker list_lock(m_holding_locks_lock);
  983. if (refs_delta > 0) {
  984. bool have_existing = false;
  985. for (size_t i = 0; i < m_holding_locks_list.size(); i++) {
  986. auto& info = m_holding_locks_list[i];
  987. if (info.lock == &lock) {
  988. have_existing = true;
  989. info.count += refs_delta;
  990. break;
  991. }
  992. }
  993. if (!have_existing)
  994. m_holding_locks_list.append({ &lock, location, 1 });
  995. } else {
  996. VERIFY(refs_delta < 0);
  997. bool found = false;
  998. for (size_t i = 0; i < m_holding_locks_list.size(); i++) {
  999. auto& info = m_holding_locks_list[i];
  1000. if (info.lock == &lock) {
  1001. VERIFY(info.count >= (unsigned)-refs_delta);
  1002. info.count -= (unsigned)-refs_delta;
  1003. if (info.count == 0)
  1004. m_holding_locks_list.remove(i);
  1005. found = true;
  1006. break;
  1007. }
  1008. }
  1009. VERIFY(found);
  1010. }
  1011. }
  1012. u32 lock_count() const
  1013. {
  1014. return m_holding_locks.load(AK::MemoryOrder::memory_order_relaxed);
  1015. }
  1016. #endif
  1017. bool is_handling_page_fault() const
  1018. {
  1019. return m_handling_page_fault;
  1020. }
  1021. void set_handling_page_fault(bool b) { m_handling_page_fault = b; }
  1022. void set_idle_thread() { m_is_idle_thread = true; }
  1023. bool is_idle_thread() const { return m_is_idle_thread; }
  1024. ALWAYS_INLINE u32 enter_profiler()
  1025. {
  1026. return m_nested_profiler_calls.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  1027. }
  1028. ALWAYS_INLINE u32 leave_profiler()
  1029. {
  1030. return m_nested_profiler_calls.fetch_sub(1, AK::MemoryOrder::memory_order_acquire);
  1031. }
  1032. bool is_profiling_suppressed() const { return m_is_profiling_suppressed; }
  1033. void set_profiling_suppressed() { m_is_profiling_suppressed = true; }
  1034. String backtrace();
  1035. private:
  1036. Thread(NonnullRefPtr<Process>, NonnullOwnPtr<Memory::Region>, NonnullRefPtr<Timer>, OwnPtr<KString>);
  1037. IntrusiveListNode<Thread> m_process_thread_list_node;
  1038. int m_runnable_priority { -1 };
  1039. friend class WaitQueue;
  1040. class JoinBlockCondition : public BlockCondition {
  1041. public:
  1042. void thread_did_exit(void* exit_value)
  1043. {
  1044. SpinlockLocker lock(m_lock);
  1045. VERIFY(!m_thread_did_exit);
  1046. m_thread_did_exit = true;
  1047. m_exit_value.store(exit_value, AK::MemoryOrder::memory_order_release);
  1048. do_unblock_joiner();
  1049. }
  1050. void thread_finalizing()
  1051. {
  1052. SpinlockLocker lock(m_lock);
  1053. do_unblock_joiner();
  1054. }
  1055. void* exit_value() const
  1056. {
  1057. VERIFY(m_thread_did_exit);
  1058. return m_exit_value.load(AK::MemoryOrder::memory_order_acquire);
  1059. }
  1060. void try_unblock(JoinBlocker& blocker)
  1061. {
  1062. SpinlockLocker lock(m_lock);
  1063. if (m_thread_did_exit)
  1064. blocker.unblock(exit_value(), false);
  1065. }
  1066. protected:
  1067. virtual bool should_add_blocker(Blocker& b, void*) override
  1068. {
  1069. VERIFY(b.blocker_type() == Blocker::Type::Join);
  1070. auto& blocker = static_cast<JoinBlocker&>(b);
  1071. // NOTE: m_lock is held already!
  1072. if (m_thread_did_exit) {
  1073. blocker.unblock(exit_value(), true);
  1074. return false;
  1075. }
  1076. return true;
  1077. }
  1078. private:
  1079. void do_unblock_joiner()
  1080. {
  1081. do_unblock([&](Blocker& b, void*, bool&) {
  1082. VERIFY(b.blocker_type() == Blocker::Type::Join);
  1083. auto& blocker = static_cast<JoinBlocker&>(b);
  1084. return blocker.unblock(exit_value(), false);
  1085. });
  1086. }
  1087. Atomic<void*> m_exit_value { nullptr };
  1088. bool m_thread_did_exit { false };
  1089. };
  1090. LockMode unlock_process_if_locked(u32&);
  1091. void relock_process(LockMode, u32);
  1092. void reset_fpu_state();
  1093. mutable RecursiveSpinlock m_lock;
  1094. mutable RecursiveSpinlock m_block_lock;
  1095. NonnullRefPtr<Process> m_process;
  1096. ThreadID m_tid { -1 };
  1097. ThreadRegisters m_regs;
  1098. DebugRegisterState m_debug_register_state {};
  1099. TrapFrame* m_current_trap { nullptr };
  1100. u32 m_saved_critical { 1 };
  1101. IntrusiveListNode<Thread> m_ready_queue_node;
  1102. Atomic<u32> m_cpu { 0 };
  1103. u32 m_cpu_affinity { THREAD_AFFINITY_DEFAULT };
  1104. Optional<u64> m_last_time_scheduled;
  1105. u64 m_total_time_scheduled_user { 0 };
  1106. u64 m_total_time_scheduled_kernel { 0 };
  1107. u32 m_ticks_left { 0 };
  1108. u32 m_times_scheduled { 0 };
  1109. u32 m_ticks_in_user { 0 };
  1110. u32 m_ticks_in_kernel { 0 };
  1111. u32 m_pending_signals { 0 };
  1112. u32 m_signal_mask { 0 };
  1113. FlatPtr m_kernel_stack_base { 0 };
  1114. FlatPtr m_kernel_stack_top { 0 };
  1115. OwnPtr<Memory::Region> m_kernel_stack_region;
  1116. VirtualAddress m_thread_specific_data;
  1117. Optional<Memory::VirtualRange> m_thread_specific_range;
  1118. Array<SignalActionData, NSIG> m_signal_action_data;
  1119. Blocker* m_blocker { nullptr };
  1120. Kernel::Mutex* m_blocking_lock { nullptr };
  1121. u32 m_lock_requested_count { 0 };
  1122. IntrusiveListNode<Thread> m_blocked_threads_list_node;
  1123. #if LOCK_DEBUG
  1124. struct HoldingLockInfo {
  1125. Mutex* lock;
  1126. LockLocation lock_location;
  1127. unsigned count;
  1128. };
  1129. Atomic<u32> m_holding_locks { 0 };
  1130. Spinlock<u8> m_holding_locks_lock;
  1131. Vector<HoldingLockInfo> m_holding_locks_list;
  1132. #endif
  1133. JoinBlockCondition m_join_condition;
  1134. Atomic<bool, AK::MemoryOrder::memory_order_relaxed> m_is_active { false };
  1135. bool m_is_joinable { true };
  1136. bool m_handling_page_fault { false };
  1137. PreviousMode m_previous_mode { PreviousMode::KernelMode }; // We always start out in kernel mode
  1138. unsigned m_syscall_count { 0 };
  1139. unsigned m_inode_faults { 0 };
  1140. unsigned m_zero_faults { 0 };
  1141. unsigned m_cow_faults { 0 };
  1142. unsigned m_file_read_bytes { 0 };
  1143. unsigned m_file_write_bytes { 0 };
  1144. unsigned m_unix_socket_read_bytes { 0 };
  1145. unsigned m_unix_socket_write_bytes { 0 };
  1146. unsigned m_ipv4_socket_read_bytes { 0 };
  1147. unsigned m_ipv4_socket_write_bytes { 0 };
  1148. FPUState m_fpu_state {};
  1149. State m_state { Invalid };
  1150. OwnPtr<KString> m_name;
  1151. u32 m_priority { THREAD_PRIORITY_NORMAL };
  1152. State m_stop_state { Invalid };
  1153. bool m_dump_backtrace_on_finalization { false };
  1154. bool m_should_die { false };
  1155. bool m_initialized { false };
  1156. bool m_in_block { false };
  1157. bool m_is_idle_thread { false };
  1158. Atomic<bool> m_have_any_unmasked_pending_signals { false };
  1159. Atomic<u32> m_nested_profiler_calls { 0 };
  1160. RefPtr<Timer> m_block_timer;
  1161. bool m_is_profiling_suppressed { false };
  1162. void yield_and_release_relock_big_lock();
  1163. enum class VerifyLockNotHeld {
  1164. Yes,
  1165. No
  1166. };
  1167. void yield_without_releasing_big_lock(VerifyLockNotHeld verify_lock_not_held = VerifyLockNotHeld::Yes);
  1168. void drop_thread_count(bool);
  1169. mutable IntrusiveListNode<Thread> m_global_thread_list_node;
  1170. public:
  1171. using ListInProcess = IntrusiveList<Thread, RawPtr<Thread>, &Thread::m_process_thread_list_node>;
  1172. using GlobalList = IntrusiveList<Thread, RawPtr<Thread>, &Thread::m_global_thread_list_node>;
  1173. static SpinlockProtected<GlobalList>& all_instances();
  1174. };
  1175. AK_ENUM_BITWISE_OPERATORS(Thread::FileBlocker::BlockFlags);
  1176. template<IteratorFunction<Thread&> Callback>
  1177. inline IterationDecision Thread::for_each(Callback callback)
  1178. {
  1179. return Thread::all_instances().with([&](auto& list) -> IterationDecision {
  1180. for (auto& thread : list) {
  1181. IterationDecision decision = callback(thread);
  1182. if (decision != IterationDecision::Continue)
  1183. return decision;
  1184. }
  1185. return IterationDecision::Continue;
  1186. });
  1187. }
  1188. template<IteratorFunction<Thread&> Callback>
  1189. inline IterationDecision Thread::for_each_in_state(State state, Callback callback)
  1190. {
  1191. return Thread::all_instances().with([&](auto& list) -> IterationDecision {
  1192. for (auto& thread : list) {
  1193. if (thread.state() != state)
  1194. continue;
  1195. IterationDecision decision = callback(thread);
  1196. if (decision != IterationDecision::Continue)
  1197. return decision;
  1198. }
  1199. return IterationDecision::Continue;
  1200. });
  1201. }
  1202. template<VoidFunction<Thread&> Callback>
  1203. inline IterationDecision Thread::for_each(Callback callback)
  1204. {
  1205. return Thread::all_instances().with([&](auto& list) {
  1206. for (auto& thread : list) {
  1207. if (callback(thread) == IterationDecision::Break)
  1208. return IterationDecision::Break;
  1209. }
  1210. return IterationDecision::Continue;
  1211. });
  1212. }
  1213. template<VoidFunction<Thread&> Callback>
  1214. inline IterationDecision Thread::for_each_in_state(State state, Callback callback)
  1215. {
  1216. return for_each_in_state(state, [&](auto& thread) {
  1217. callback(thread);
  1218. return IterationDecision::Continue;
  1219. });
  1220. }
  1221. }
  1222. template<>
  1223. struct AK::Formatter<Kernel::Thread> : AK::Formatter<FormatString> {
  1224. void format(FormatBuilder&, const Kernel::Thread&);
  1225. };