Thread.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. #pragma once
  2. #include <AK/AKString.h>
  3. #include <AK/Function.h>
  4. #include <AK/IntrusiveList.h>
  5. #include <AK/OwnPtr.h>
  6. #include <AK/RefPtr.h>
  7. #include <AK/Vector.h>
  8. #include <Kernel/Arch/i386/CPU.h>
  9. #include <Kernel/KResult.h>
  10. #include <Kernel/UnixTypes.h>
  11. #include <Kernel/VM/Region.h>
  12. #include <LibC/fd_set.h>
  13. class Alarm;
  14. class FileDescription;
  15. class Process;
  16. class Region;
  17. class Thread;
  18. enum class ShouldUnblockThread {
  19. No = 0,
  20. Yes
  21. };
  22. struct SignalActionData {
  23. VirtualAddress handler_or_sigaction;
  24. u32 mask { 0 };
  25. int flags { 0 };
  26. };
  27. class Thread {
  28. friend class Process;
  29. friend class Scheduler;
  30. public:
  31. explicit Thread(Process&);
  32. ~Thread();
  33. static void initialize();
  34. static void finalize_dying_threads();
  35. static Vector<Thread*> all_threads();
  36. static bool is_thread(void*);
  37. int tid() const { return m_tid; }
  38. int pid() const;
  39. Process& process() { return m_process; }
  40. const Process& process() const { return m_process; }
  41. void finalize();
  42. enum State : u8 {
  43. Invalid = 0,
  44. Runnable,
  45. Running,
  46. Skip1SchedulerPass,
  47. Skip0SchedulerPasses,
  48. Dying,
  49. Dead,
  50. Stopped,
  51. Blocked,
  52. };
  53. class Blocker {
  54. public:
  55. virtual ~Blocker() {}
  56. virtual bool should_unblock(Thread&, time_t now_s, long us) = 0;
  57. virtual const char* state_string() const = 0;
  58. void set_interrupted_by_signal() { m_was_interrupted_while_blocked = true; }
  59. bool was_interrupted_by_signal() const { return m_was_interrupted_while_blocked; }
  60. private:
  61. bool m_was_interrupted_while_blocked { false };
  62. };
  63. class FileDescriptionBlocker : public Blocker {
  64. public:
  65. const FileDescription& blocked_description() const;
  66. protected:
  67. explicit FileDescriptionBlocker(const FileDescription&);
  68. private:
  69. NonnullRefPtr<FileDescription> m_blocked_description;
  70. };
  71. class AcceptBlocker final : public FileDescriptionBlocker {
  72. public:
  73. explicit AcceptBlocker(const FileDescription&);
  74. virtual bool should_unblock(Thread&, time_t, long) override;
  75. virtual const char* state_string() const override { return "Accepting"; }
  76. };
  77. class ReceiveBlocker final : public FileDescriptionBlocker {
  78. public:
  79. explicit ReceiveBlocker(const FileDescription&);
  80. virtual bool should_unblock(Thread&, time_t, long) override;
  81. virtual const char* state_string() const override { return "Receiving"; }
  82. };
  83. class ConnectBlocker final : public FileDescriptionBlocker {
  84. public:
  85. explicit ConnectBlocker(const FileDescription&);
  86. virtual bool should_unblock(Thread&, time_t, long) override;
  87. virtual const char* state_string() const override { return "Connecting"; }
  88. };
  89. class WriteBlocker final : public FileDescriptionBlocker {
  90. public:
  91. explicit WriteBlocker(const FileDescription&);
  92. virtual bool should_unblock(Thread&, time_t, long) override;
  93. virtual const char* state_string() const override { return "Writing"; }
  94. };
  95. class ReadBlocker final : public FileDescriptionBlocker {
  96. public:
  97. explicit ReadBlocker(const FileDescription&);
  98. virtual bool should_unblock(Thread&, time_t, long) override;
  99. virtual const char* state_string() const override { return "Reading"; }
  100. };
  101. class ConditionBlocker final : public Blocker {
  102. public:
  103. ConditionBlocker(const char* state_string, Function<bool()>&& condition);
  104. virtual bool should_unblock(Thread&, time_t, long) override;
  105. virtual const char* state_string() const override { return m_state_string; }
  106. private:
  107. Function<bool()> m_block_until_condition;
  108. const char* m_state_string { nullptr };
  109. };
  110. class SleepBlocker final : public Blocker {
  111. public:
  112. explicit SleepBlocker(u64 wakeup_time);
  113. virtual bool should_unblock(Thread&, time_t, long) override;
  114. virtual const char* state_string() const override { return "Sleeping"; }
  115. private:
  116. u64 m_wakeup_time { 0 };
  117. };
  118. class SelectBlocker final : public Blocker {
  119. public:
  120. typedef Vector<int, FD_SETSIZE> FDVector;
  121. SelectBlocker(const timeval& tv, bool select_has_timeout, const FDVector& read_fds, const FDVector& write_fds, const FDVector& except_fds);
  122. virtual bool should_unblock(Thread&, time_t, long) override;
  123. virtual const char* state_string() const override { return "Selecting"; }
  124. private:
  125. timeval m_select_timeout;
  126. bool m_select_has_timeout { false };
  127. const FDVector& m_select_read_fds;
  128. const FDVector& m_select_write_fds;
  129. const FDVector& m_select_exceptional_fds;
  130. };
  131. class WaitBlocker final : public Blocker {
  132. public:
  133. WaitBlocker(int wait_options, pid_t& waitee_pid);
  134. virtual bool should_unblock(Thread&, time_t, long) override;
  135. virtual const char* state_string() const override { return "Waiting"; }
  136. private:
  137. int m_wait_options { 0 };
  138. pid_t& m_waitee_pid;
  139. };
  140. class SemiPermanentBlocker final : public Blocker {
  141. public:
  142. enum class Reason {
  143. Lurking,
  144. Signal,
  145. };
  146. SemiPermanentBlocker(Reason reason);
  147. virtual bool should_unblock(Thread&, time_t, long) override;
  148. virtual const char* state_string() const override
  149. {
  150. switch (m_reason) {
  151. case Reason::Lurking:
  152. return "Lurking";
  153. case Reason::Signal:
  154. return "Signal";
  155. }
  156. ASSERT_NOT_REACHED();
  157. }
  158. private:
  159. Reason m_reason;
  160. };
  161. void did_schedule() { ++m_times_scheduled; }
  162. u32 times_scheduled() const { return m_times_scheduled; }
  163. bool is_stopped() const { return m_state == Stopped; }
  164. bool is_blocked() const { return m_state == Blocked; }
  165. bool in_kernel() const { return (m_tss.cs & 0x03) == 0; }
  166. u32 frame_ptr() const { return m_tss.ebp; }
  167. u32 stack_ptr() const { return m_tss.esp; }
  168. u16 selector() const { return m_far_ptr.selector; }
  169. TSS32& tss() { return m_tss; }
  170. State state() const { return m_state; }
  171. const char* state_string() const;
  172. u32 ticks() const { return m_ticks; }
  173. u64 sleep(u32 ticks);
  174. enum class BlockResult {
  175. WokeNormally,
  176. InterruptedBySignal,
  177. };
  178. template <typename T, class... Args>
  179. [[nodiscard]] BlockResult block(Args&& ... args)
  180. {
  181. // If this is triggered, state has gotten messed: we should never have a
  182. // blocker already set. That means we're re-entering somehow, which is
  183. // bad.
  184. ASSERT(m_blocker == nullptr);
  185. // We should never be blocking a blocked (or otherwise non-active) thread.
  186. ASSERT(state() == Thread::Running);
  187. T t(AK::forward<Args>(args)...);
  188. m_blocker = &t;
  189. set_state(Thread::Blocked);
  190. block_helper(); // this will unlock, yield, and eventually unblock us to return here.
  191. ASSERT(state() != Thread::Blocked);
  192. m_blocker = nullptr;
  193. if (t.was_interrupted_by_signal())
  194. return BlockResult::InterruptedBySignal;
  195. return BlockResult::WokeNormally;
  196. };
  197. [[nodiscard]] BlockResult block_until(const char* state_string, Function<bool()>&& condition)
  198. {
  199. return block<ConditionBlocker>(state_string, move(condition));
  200. }
  201. void unblock();
  202. const FarPtr& far_ptr() const { return m_far_ptr; }
  203. bool tick();
  204. void set_ticks_left(u32 t) { m_ticks_left = t; }
  205. u32 ticks_left() const { return m_ticks_left; }
  206. u32 kernel_stack_base() const { return m_kernel_stack_base; }
  207. u32 kernel_stack_for_signal_handler_base() const { return m_kernel_stack_for_signal_handler_region ? m_kernel_stack_for_signal_handler_region->vaddr().get() : 0; }
  208. void set_selector(u16 s) { m_far_ptr.selector = s; }
  209. void set_state(State);
  210. void send_signal(u8 signal, Process* sender);
  211. void consider_unblock(time_t now_sec, long now_usec);
  212. ShouldUnblockThread dispatch_one_pending_signal();
  213. ShouldUnblockThread dispatch_signal(u8 signal);
  214. bool has_unmasked_pending_signals() const;
  215. void terminate_due_to_signal(u8 signal);
  216. bool should_ignore_signal(u8 signal) const;
  217. FPUState& fpu_state() { return *m_fpu_state; }
  218. bool has_used_fpu() const { return m_has_used_fpu; }
  219. void set_has_used_fpu(bool b) { m_has_used_fpu = b; }
  220. void set_default_signal_dispositions();
  221. void push_value_on_stack(u32);
  222. void make_userspace_stack_for_main_thread(Vector<String> arguments, Vector<String> environment);
  223. void make_userspace_stack_for_secondary_thread(void* argument);
  224. Thread* clone(Process&);
  225. template<typename Callback>
  226. static IterationDecision for_each_in_state(State, Callback);
  227. template<typename Callback>
  228. static IterationDecision for_each_living(Callback);
  229. template<typename Callback>
  230. static IterationDecision for_each_runnable(Callback);
  231. template<typename Callback>
  232. static IterationDecision for_each_nonrunnable(Callback);
  233. template<typename Callback>
  234. static IterationDecision for_each(Callback);
  235. static bool is_runnable_state(Thread::State state)
  236. {
  237. return state == Thread::State::Running || state == Thread::State::Runnable;
  238. }
  239. private:
  240. IntrusiveListNode m_runnable_list_node;
  241. typedef IntrusiveList<Thread, &Thread::m_runnable_list_node> SchedulerThreadList;
  242. public:
  243. static SchedulerThreadList* g_runnable_threads;
  244. static SchedulerThreadList* g_nonrunnable_threads;
  245. static SchedulerThreadList* thread_list_for_state(Thread::State state)
  246. {
  247. if (is_runnable_state(state))
  248. return g_runnable_threads;
  249. return g_nonrunnable_threads;
  250. }
  251. private:
  252. Process& m_process;
  253. int m_tid { -1 };
  254. TSS32 m_tss;
  255. OwnPtr<TSS32> m_tss_to_resume_kernel;
  256. FarPtr m_far_ptr;
  257. u32 m_ticks { 0 };
  258. u32 m_ticks_left { 0 };
  259. u32 m_times_scheduled { 0 };
  260. u32 m_pending_signals { 0 };
  261. u32 m_signal_mask { 0 };
  262. u32 m_kernel_stack_base { 0 };
  263. RefPtr<Region> m_kernel_stack_region;
  264. RefPtr<Region> m_kernel_stack_for_signal_handler_region;
  265. SignalActionData m_signal_action_data[32];
  266. Region* m_signal_stack_user_region { nullptr };
  267. Blocker* m_blocker { nullptr };
  268. FPUState* m_fpu_state { nullptr };
  269. State m_state { Invalid };
  270. bool m_has_used_fpu { false };
  271. void block_helper();
  272. };
  273. HashTable<Thread*>& thread_table();
  274. template<typename Callback>
  275. inline IterationDecision Thread::for_each_in_state(State state, Callback callback)
  276. {
  277. ASSERT_INTERRUPTS_DISABLED();
  278. auto new_callback = [=](Thread& thread) -> IterationDecision {
  279. if (thread.state() == state)
  280. return callback(thread);
  281. return IterationDecision::Continue;
  282. };
  283. if (is_runnable_state(state))
  284. return for_each_runnable(new_callback);
  285. return for_each_nonrunnable(new_callback);
  286. }
  287. template<typename Callback>
  288. inline IterationDecision Thread::for_each_living(Callback callback)
  289. {
  290. ASSERT_INTERRUPTS_DISABLED();
  291. return Thread::for_each([callback](Thread& thread) -> IterationDecision {
  292. if (thread.state() != Thread::State::Dead && thread.state() != Thread::State::Dying)
  293. return callback(thread);
  294. return IterationDecision::Continue;
  295. });
  296. }
  297. template<typename Callback>
  298. inline IterationDecision Thread::for_each(Callback callback)
  299. {
  300. ASSERT_INTERRUPTS_DISABLED();
  301. auto ret = for_each_runnable(callback);
  302. if (ret == IterationDecision::Break)
  303. return ret;
  304. return for_each_nonrunnable(callback);
  305. }
  306. template<typename Callback>
  307. inline IterationDecision Thread::for_each_runnable(Callback callback)
  308. {
  309. ASSERT_INTERRUPTS_DISABLED();
  310. auto& tl = *g_runnable_threads;
  311. for (auto it = tl.begin(); it != tl.end();) {
  312. auto thread = *it;
  313. it = ++it;
  314. if (callback(*thread) == IterationDecision::Break)
  315. return IterationDecision::Break;
  316. }
  317. return IterationDecision::Continue;
  318. }
  319. template<typename Callback>
  320. inline IterationDecision Thread::for_each_nonrunnable(Callback callback)
  321. {
  322. ASSERT_INTERRUPTS_DISABLED();
  323. auto& tl = *g_nonrunnable_threads;
  324. for (auto it = tl.begin(); it != tl.end();) {
  325. auto thread = *it;
  326. it = ++it;
  327. if (callback(*thread) == IterationDecision::Break)
  328. return IterationDecision::Break;
  329. }
  330. return IterationDecision::Continue;
  331. }