Thread.h 45 KB

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