Thread.h 43 KB

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