Thread.h 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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. Atomic<bool> timeout_unblocked(false);
  638. Atomic<bool> did_unblock(false);
  639. RefPtr<Timer> timer;
  640. {
  641. switch (state()) {
  642. case Thread::Stopped:
  643. // It's possible that we were requested to be stopped!
  644. break;
  645. case Thread::Running:
  646. ASSERT(m_blocker == nullptr);
  647. break;
  648. default:
  649. ASSERT_NOT_REACHED();
  650. }
  651. m_blocker = &t;
  652. if (!t.should_block()) {
  653. // Don't block if the wake condition is already met
  654. t.not_blocking(false);
  655. m_blocker = nullptr;
  656. m_in_block = false;
  657. return BlockResult::NotBlocked;
  658. }
  659. auto& block_timeout = t.override_timeout(timeout);
  660. if (!block_timeout.is_infinite()) {
  661. // Process::kill_all_threads may be called at any time, which will mark all
  662. // threads to die. In that case
  663. timer = TimerQueue::the().add_timer_without_id(block_timeout.clock_id(), block_timeout.absolute_time(), [&]() {
  664. ASSERT(!Processor::current().in_irq());
  665. ASSERT(!g_scheduler_lock.own_lock());
  666. ASSERT(!m_block_lock.own_lock());
  667. // NOTE: this may execute on the same or any other processor!
  668. ScopedSpinLock scheduler_lock(g_scheduler_lock);
  669. ScopedSpinLock block_lock(m_block_lock);
  670. if (m_blocker && timeout_unblocked.exchange(true, AK::MemoryOrder::memory_order_relaxed) == false)
  671. unblock();
  672. });
  673. if (!timer) {
  674. // Timeout is already in the past
  675. t.not_blocking(true);
  676. m_blocker = nullptr;
  677. m_in_block = false;
  678. return BlockResult::InterruptedByTimeout;
  679. }
  680. }
  681. t.begin_blocking({});
  682. set_state(Thread::Blocked);
  683. }
  684. block_lock.unlock();
  685. bool did_timeout = false;
  686. auto previous_locked = LockMode::Unlocked;
  687. u32 lock_count_to_restore = 0;
  688. for (;;) {
  689. scheduler_lock.unlock();
  690. // Yield to the scheduler, and wait for us to resume unblocked.
  691. if (previous_locked == LockMode::Unlocked)
  692. previous_locked = unlock_process_if_locked(lock_count_to_restore);
  693. ASSERT(!g_scheduler_lock.own_lock());
  694. ASSERT(Processor::current().in_critical());
  695. yield_while_not_holding_big_lock();
  696. scheduler_lock.lock();
  697. ScopedSpinLock block_lock2(m_block_lock);
  698. if (should_be_stopped() || state() == Stopped) {
  699. dbg() << "Thread should be stopped, current state: " << state_string();
  700. set_state(Thread::Blocked);
  701. continue;
  702. }
  703. if (m_blocker && !m_blocker->can_be_interrupted() && !m_should_die) {
  704. block_lock2.unlock();
  705. dbg() << "Thread should not be unblocking, current state: " << state_string();
  706. set_state(Thread::Blocked);
  707. continue;
  708. }
  709. // Prevent the timeout from unblocking this thread if it happens to
  710. // be in the process of firing already
  711. did_timeout |= timeout_unblocked.exchange(true, AK::MemoryOrder::memory_order_relaxed);
  712. if (m_blocker) {
  713. // Remove ourselves...
  714. ASSERT(m_blocker == &t);
  715. m_blocker = nullptr;
  716. }
  717. m_in_block = false;
  718. break;
  719. }
  720. if (t.was_interrupted_by_signal()) {
  721. ScopedSpinLock lock(m_lock);
  722. dispatch_one_pending_signal();
  723. }
  724. // Notify the blocker that we are no longer blocking. It may need
  725. // to clean up now while we're still holding m_lock
  726. auto result = t.end_blocking({}, did_timeout); // calls was_unblocked internally
  727. scheduler_lock.unlock();
  728. if (timer && !did_timeout) {
  729. // Cancel the timer while not holding any locks. This allows
  730. // the timer function to complete before we remove it
  731. // (e.g. if it's on another processor)
  732. TimerQueue::the().cancel_timer(timer.release_nonnull());
  733. }
  734. if (previous_locked != LockMode::Unlocked) {
  735. // NOTE: this may trigger another call to Thread::block(), so
  736. // we need to do this after we're all done and restored m_in_block!
  737. relock_process(previous_locked, lock_count_to_restore);
  738. }
  739. return result;
  740. }
  741. void unblock_from_blocker(Blocker&);
  742. void unblock(u8 signal = 0);
  743. template<class... Args>
  744. Thread::BlockResult wait_on(WaitQueue& wait_queue, const Thread::BlockTimeout& timeout, Args&&... args)
  745. {
  746. ASSERT(this == Thread::current());
  747. return block<Thread::QueueBlocker>(timeout, wait_queue, forward<Args>(args)...);
  748. }
  749. BlockResult sleep(clockid_t, const timespec&, timespec* = nullptr);
  750. BlockResult sleep(const timespec& duration, timespec* remaining_time = nullptr)
  751. {
  752. return sleep(CLOCK_MONOTONIC_COARSE, duration, remaining_time);
  753. }
  754. BlockResult sleep_until(clockid_t, const timespec&);
  755. BlockResult sleep_until(const timespec& duration)
  756. {
  757. return sleep_until(CLOCK_MONOTONIC_COARSE, duration);
  758. }
  759. // Tell this thread to unblock if needed,
  760. // gracefully unwind the stack and die.
  761. void set_should_die();
  762. [[nodiscard]] bool should_die() const { return m_should_die; }
  763. void die_if_needed();
  764. void exit(void* = nullptr);
  765. bool tick(bool in_kernel);
  766. void set_ticks_left(u32 t) { m_ticks_left = t; }
  767. u32 ticks_left() const { return m_ticks_left; }
  768. u32 kernel_stack_base() const { return m_kernel_stack_base; }
  769. u32 kernel_stack_top() const { return m_kernel_stack_top; }
  770. void set_state(State, u8 = 0);
  771. [[nodiscard]] bool is_initialized() const { return m_initialized; }
  772. void set_initialized(bool initialized) { m_initialized = initialized; }
  773. void send_urgent_signal_to_self(u8 signal);
  774. void send_signal(u8 signal, Process* sender);
  775. u32 update_signal_mask(u32 signal_mask);
  776. u32 signal_mask_block(sigset_t signal_set, bool block);
  777. u32 signal_mask() const;
  778. void clear_signals();
  779. void set_dump_backtrace_on_finalization() { m_dump_backtrace_on_finalization = true; }
  780. DispatchSignalResult dispatch_one_pending_signal();
  781. DispatchSignalResult try_dispatch_one_pending_signal(u8 signal);
  782. DispatchSignalResult dispatch_signal(u8 signal);
  783. void check_dispatch_pending_signal();
  784. [[nodiscard]] bool has_unmasked_pending_signals() const { return m_have_any_unmasked_pending_signals.load(AK::memory_order_consume); }
  785. void terminate_due_to_signal(u8 signal);
  786. [[nodiscard]] bool should_ignore_signal(u8 signal) const;
  787. [[nodiscard]] bool has_signal_handler(u8 signal) const;
  788. [[nodiscard]] bool has_pending_signal(u8 signal) const;
  789. u32 pending_signals() const;
  790. u32 pending_signals_for_state() const;
  791. FPUState& fpu_state() { return *m_fpu_state; }
  792. void set_default_signal_dispositions();
  793. bool push_value_on_stack(FlatPtr);
  794. KResult make_thread_specific_region(Badge<Process>);
  795. unsigned syscall_count() const { return m_syscall_count; }
  796. void did_syscall() { ++m_syscall_count; }
  797. unsigned inode_faults() const { return m_inode_faults; }
  798. void did_inode_fault() { ++m_inode_faults; }
  799. unsigned zero_faults() const { return m_zero_faults; }
  800. void did_zero_fault() { ++m_zero_faults; }
  801. unsigned cow_faults() const { return m_cow_faults; }
  802. void did_cow_fault() { ++m_cow_faults; }
  803. unsigned file_read_bytes() const { return m_file_read_bytes; }
  804. unsigned file_write_bytes() const { return m_file_write_bytes; }
  805. void did_file_read(unsigned bytes)
  806. {
  807. m_file_read_bytes += bytes;
  808. }
  809. void did_file_write(unsigned bytes)
  810. {
  811. m_file_write_bytes += bytes;
  812. }
  813. unsigned unix_socket_read_bytes() const { return m_unix_socket_read_bytes; }
  814. unsigned unix_socket_write_bytes() const { return m_unix_socket_write_bytes; }
  815. void did_unix_socket_read(unsigned bytes)
  816. {
  817. m_unix_socket_read_bytes += bytes;
  818. }
  819. void did_unix_socket_write(unsigned bytes)
  820. {
  821. m_unix_socket_write_bytes += bytes;
  822. }
  823. unsigned ipv4_socket_read_bytes() const { return m_ipv4_socket_read_bytes; }
  824. unsigned ipv4_socket_write_bytes() const { return m_ipv4_socket_write_bytes; }
  825. void did_ipv4_socket_read(unsigned bytes)
  826. {
  827. m_ipv4_socket_read_bytes += bytes;
  828. }
  829. void did_ipv4_socket_write(unsigned bytes)
  830. {
  831. m_ipv4_socket_write_bytes += bytes;
  832. }
  833. void set_active(bool active)
  834. {
  835. m_is_active.store(active, AK::memory_order_release);
  836. }
  837. [[nodiscard]] bool is_active() const
  838. {
  839. return m_is_active.load(AK::MemoryOrder::memory_order_acquire);
  840. }
  841. [[nodiscard]] bool is_finalizable() const
  842. {
  843. // We can't finalize as long as this thread is still running
  844. // Note that checking for Running state here isn't sufficient
  845. // as the thread may not be in Running state but switching out.
  846. // m_is_active is set to false once the context switch is
  847. // complete and the thread is not executing on any processor.
  848. if (m_is_active.load(AK::memory_order_acquire))
  849. return false;
  850. // We can't finalize until the thread is either detached or
  851. // a join has started. We can't make m_is_joinable atomic
  852. // because that would introduce a race in try_join.
  853. ScopedSpinLock lock(m_lock);
  854. return !m_is_joinable;
  855. }
  856. RefPtr<Thread> clone(Process&);
  857. template<typename Callback>
  858. static IterationDecision for_each_in_state(State, Callback);
  859. template<typename Callback>
  860. static IterationDecision for_each_living(Callback);
  861. template<typename Callback>
  862. static IterationDecision for_each(Callback);
  863. [[nodiscard]] static bool is_runnable_state(Thread::State state)
  864. {
  865. return state == Thread::State::Running || state == Thread::State::Runnable;
  866. }
  867. static constexpr u32 default_kernel_stack_size = 65536;
  868. static constexpr u32 default_userspace_stack_size = 4 * MiB;
  869. u32 ticks_in_user() const { return m_ticks_in_user; }
  870. u32 ticks_in_kernel() const { return m_ticks_in_kernel; }
  871. RecursiveSpinLock& get_lock() const { return m_lock; }
  872. #ifdef LOCK_DEBUG
  873. void holding_lock(Lock& lock, int refs_delta, const char* file = nullptr, int line = 0)
  874. {
  875. ASSERT(refs_delta != 0);
  876. m_holding_locks.fetch_add(refs_delta, AK::MemoryOrder::memory_order_relaxed);
  877. ScopedSpinLock list_lock(m_holding_locks_lock);
  878. if (refs_delta > 0) {
  879. bool have_existing = false;
  880. for (size_t i = 0; i < m_holding_locks_list.size(); i++) {
  881. auto& info = m_holding_locks_list[i];
  882. if (info.lock == &lock) {
  883. have_existing = true;
  884. info.count += refs_delta;
  885. break;
  886. }
  887. }
  888. if (!have_existing)
  889. m_holding_locks_list.append({ &lock, file ? file : "unknown", line, 1 });
  890. } else {
  891. ASSERT(refs_delta < 0);
  892. bool found = false;
  893. for (size_t i = 0; i < m_holding_locks_list.size(); i++) {
  894. auto& info = m_holding_locks_list[i];
  895. if (info.lock == &lock) {
  896. ASSERT(info.count >= (unsigned)-refs_delta);
  897. info.count -= (unsigned)-refs_delta;
  898. if (info.count == 0)
  899. m_holding_locks_list.remove(i);
  900. found = true;
  901. break;
  902. }
  903. }
  904. ASSERT(found);
  905. }
  906. }
  907. u32 lock_count() const
  908. {
  909. return m_holding_locks.load(AK::MemoryOrder::memory_order_relaxed);
  910. }
  911. #endif
  912. bool was_created() const
  913. {
  914. return m_kernel_stack_region;
  915. }
  916. private:
  917. IntrusiveListNode m_runnable_list_node;
  918. private:
  919. friend struct SchedulerData;
  920. friend class WaitQueue;
  921. class JoinBlockCondition : public BlockCondition {
  922. public:
  923. void thread_did_exit(void* exit_value)
  924. {
  925. ScopedSpinLock lock(m_lock);
  926. ASSERT(!m_thread_did_exit);
  927. m_thread_did_exit = true;
  928. m_exit_value.store(exit_value, AK::MemoryOrder::memory_order_release);
  929. do_unblock_joiner();
  930. }
  931. void thread_finalizing()
  932. {
  933. ScopedSpinLock lock(m_lock);
  934. do_unblock_joiner();
  935. }
  936. void* exit_value() const
  937. {
  938. ASSERT(m_thread_did_exit);
  939. return m_exit_value.load(AK::MemoryOrder::memory_order_acquire);
  940. }
  941. void try_unblock(JoinBlocker& blocker)
  942. {
  943. ScopedSpinLock lock(m_lock);
  944. if (m_thread_did_exit)
  945. blocker.unblock(exit_value(), false);
  946. }
  947. protected:
  948. virtual bool should_add_blocker(Blocker& b, void*) override
  949. {
  950. ASSERT(b.blocker_type() == Blocker::Type::Join);
  951. auto& blocker = static_cast<JoinBlocker&>(b);
  952. // NOTE: m_lock is held already!
  953. if (m_thread_did_exit) {
  954. blocker.unblock(exit_value(), true);
  955. return false;
  956. }
  957. return true;
  958. }
  959. private:
  960. void do_unblock_joiner()
  961. {
  962. do_unblock([&](Blocker& b, void*, bool&) {
  963. ASSERT(b.blocker_type() == Blocker::Type::Join);
  964. auto& blocker = static_cast<JoinBlocker&>(b);
  965. return blocker.unblock(exit_value(), false);
  966. });
  967. }
  968. Atomic<void*> m_exit_value { nullptr };
  969. bool m_thread_did_exit { false };
  970. };
  971. LockMode unlock_process_if_locked(u32&);
  972. void relock_process(LockMode, u32);
  973. String backtrace_impl();
  974. void reset_fpu_state();
  975. mutable RecursiveSpinLock m_lock;
  976. mutable RecursiveSpinLock m_block_lock;
  977. NonnullRefPtr<Process> m_process;
  978. ThreadID m_tid { -1 };
  979. TSS32 m_tss;
  980. Atomic<u32> m_cpu { 0 };
  981. u32 m_cpu_affinity { THREAD_AFFINITY_DEFAULT };
  982. u32 m_ticks_left { 0 };
  983. u32 m_times_scheduled { 0 };
  984. u32 m_ticks_in_user { 0 };
  985. u32 m_ticks_in_kernel { 0 };
  986. u32 m_pending_signals { 0 };
  987. u32 m_signal_mask { 0 };
  988. u32 m_kernel_stack_base { 0 };
  989. u32 m_kernel_stack_top { 0 };
  990. OwnPtr<Region> m_kernel_stack_region;
  991. VirtualAddress m_thread_specific_data;
  992. SignalActionData m_signal_action_data[32];
  993. Blocker* m_blocker { nullptr };
  994. #ifdef LOCK_DEBUG
  995. struct HoldingLockInfo {
  996. Lock* lock;
  997. const char* file;
  998. int line;
  999. unsigned count;
  1000. };
  1001. Atomic<u32> m_holding_locks { 0 };
  1002. SpinLock<u8> m_holding_locks_lock;
  1003. Vector<HoldingLockInfo> m_holding_locks_list;
  1004. #endif
  1005. JoinBlockCondition m_join_condition;
  1006. Atomic<bool> m_is_active { false };
  1007. bool m_is_joinable { true };
  1008. unsigned m_syscall_count { 0 };
  1009. unsigned m_inode_faults { 0 };
  1010. unsigned m_zero_faults { 0 };
  1011. unsigned m_cow_faults { 0 };
  1012. unsigned m_file_read_bytes { 0 };
  1013. unsigned m_file_write_bytes { 0 };
  1014. unsigned m_unix_socket_read_bytes { 0 };
  1015. unsigned m_unix_socket_write_bytes { 0 };
  1016. unsigned m_ipv4_socket_read_bytes { 0 };
  1017. unsigned m_ipv4_socket_write_bytes { 0 };
  1018. FPUState* m_fpu_state { nullptr };
  1019. State m_state { Invalid };
  1020. String m_name;
  1021. u32 m_priority { THREAD_PRIORITY_NORMAL };
  1022. u32 m_extra_priority { 0 };
  1023. u32 m_priority_boost { 0 };
  1024. State m_stop_state { Invalid };
  1025. bool m_dump_backtrace_on_finalization { false };
  1026. bool m_should_die { false };
  1027. bool m_initialized { false };
  1028. bool m_in_block { false };
  1029. Atomic<bool> m_have_any_unmasked_pending_signals { false };
  1030. void yield_without_holding_big_lock();
  1031. void donate_without_holding_big_lock(RefPtr<Thread>&, const char*);
  1032. void yield_while_not_holding_big_lock();
  1033. void update_state_for_thread(Thread::State previous_state);
  1034. void drop_thread_count(bool);
  1035. };
  1036. template<typename Callback>
  1037. inline IterationDecision Thread::for_each_living(Callback callback)
  1038. {
  1039. ASSERT_INTERRUPTS_DISABLED();
  1040. return Thread::for_each([callback](Thread& thread) -> IterationDecision {
  1041. if (thread.state() != Thread::State::Dead && thread.state() != Thread::State::Dying)
  1042. return callback(thread);
  1043. return IterationDecision::Continue;
  1044. });
  1045. }
  1046. template<typename Callback>
  1047. inline IterationDecision Thread::for_each(Callback callback)
  1048. {
  1049. ASSERT_INTERRUPTS_DISABLED();
  1050. ScopedSpinLock lock(g_scheduler_lock);
  1051. auto ret = Scheduler::for_each_runnable(callback);
  1052. if (ret == IterationDecision::Break)
  1053. return ret;
  1054. return Scheduler::for_each_nonrunnable(callback);
  1055. }
  1056. template<typename Callback>
  1057. inline IterationDecision Thread::for_each_in_state(State state, Callback callback)
  1058. {
  1059. ASSERT_INTERRUPTS_DISABLED();
  1060. ScopedSpinLock lock(g_scheduler_lock);
  1061. auto new_callback = [=](Thread& thread) -> IterationDecision {
  1062. if (thread.state() == state)
  1063. return callback(thread);
  1064. return IterationDecision::Continue;
  1065. };
  1066. if (is_runnable_state(state))
  1067. return Scheduler::for_each_runnable(new_callback);
  1068. return Scheduler::for_each_nonrunnable(new_callback);
  1069. }
  1070. const LogStream& operator<<(const LogStream&, const Thread&);
  1071. struct SchedulerData {
  1072. typedef IntrusiveList<Thread, &Thread::m_runnable_list_node> ThreadList;
  1073. ThreadList m_runnable_threads;
  1074. ThreadList m_nonrunnable_threads;
  1075. bool has_thread(Thread& thread) const
  1076. {
  1077. return m_runnable_threads.contains(thread) || m_nonrunnable_threads.contains(thread);
  1078. }
  1079. ThreadList& thread_list_for_state(Thread::State state)
  1080. {
  1081. if (Thread::is_runnable_state(state))
  1082. return m_runnable_threads;
  1083. return m_nonrunnable_threads;
  1084. }
  1085. };
  1086. template<typename Callback>
  1087. inline IterationDecision Scheduler::for_each_runnable(Callback callback)
  1088. {
  1089. ASSERT_INTERRUPTS_DISABLED();
  1090. ASSERT(g_scheduler_lock.own_lock());
  1091. auto& tl = g_scheduler_data->m_runnable_threads;
  1092. for (auto it = tl.begin(); it != tl.end();) {
  1093. auto& thread = *it;
  1094. it = ++it;
  1095. if (callback(thread) == IterationDecision::Break)
  1096. return IterationDecision::Break;
  1097. }
  1098. return IterationDecision::Continue;
  1099. }
  1100. template<typename Callback>
  1101. inline IterationDecision Scheduler::for_each_nonrunnable(Callback callback)
  1102. {
  1103. ASSERT_INTERRUPTS_DISABLED();
  1104. ASSERT(g_scheduler_lock.own_lock());
  1105. auto& tl = g_scheduler_data->m_nonrunnable_threads;
  1106. for (auto it = tl.begin(); it != tl.end();) {
  1107. auto& thread = *it;
  1108. it = ++it;
  1109. if (callback(thread) == IterationDecision::Break)
  1110. return IterationDecision::Break;
  1111. }
  1112. return IterationDecision::Continue;
  1113. }
  1114. }