Thread.h 42 KB

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