Processor.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Array.h>
  8. #include <AK/Concepts.h>
  9. #include <AK/Function.h>
  10. #include <AK/Types.h>
  11. #include <Kernel/Arch/x86/ASM_wrapper.h>
  12. #include <Kernel/Arch/x86/CPUID.h>
  13. #include <Kernel/Arch/x86/DescriptorTable.h>
  14. #include <Kernel/Arch/x86/PageDirectory.h>
  15. #include <Kernel/Arch/x86/TSS.h>
  16. namespace Kernel {
  17. class Thread;
  18. class SchedulerPerProcessorData;
  19. struct MemoryManagerData;
  20. struct ProcessorMessageEntry;
  21. class TrapFrame;
  22. class ProcessorInfo;
  23. struct [[gnu::aligned(16)]] FPUState
  24. {
  25. u8 buffer[512];
  26. };
  27. struct ProcessorMessage {
  28. using CallbackFunction = Function<void()>;
  29. enum Type {
  30. FlushTlb,
  31. Callback,
  32. };
  33. Type type;
  34. volatile u32 refs; // atomic
  35. union {
  36. ProcessorMessage* next; // only valid while in the pool
  37. alignas(CallbackFunction) u8 callback_storage[sizeof(CallbackFunction)];
  38. struct {
  39. const PageDirectory* page_directory;
  40. u8* ptr;
  41. size_t page_count;
  42. } flush_tlb;
  43. };
  44. volatile bool async;
  45. ProcessorMessageEntry* per_proc_entries;
  46. CallbackFunction& callback_value()
  47. {
  48. return *bit_cast<CallbackFunction*>(&callback_storage);
  49. }
  50. void invoke_callback()
  51. {
  52. VERIFY(type == Type::Callback);
  53. callback_value()();
  54. }
  55. };
  56. struct ProcessorMessageEntry {
  57. ProcessorMessageEntry* next;
  58. ProcessorMessage* msg;
  59. };
  60. struct DeferredCallEntry {
  61. using HandlerFunction = Function<void()>;
  62. DeferredCallEntry* next;
  63. alignas(HandlerFunction) u8 handler_storage[sizeof(HandlerFunction)];
  64. bool was_allocated;
  65. HandlerFunction& handler_value()
  66. {
  67. return *bit_cast<HandlerFunction*>(&handler_storage);
  68. }
  69. void invoke_handler()
  70. {
  71. handler_value()();
  72. }
  73. };
  74. class Processor;
  75. // Note: We only support processors at most at the moment,
  76. // so allocate 8 slots of inline capacity in the container.
  77. using ProcessorContainer = Array<Processor*, 8>;
  78. class Processor {
  79. friend class ProcessorInfo;
  80. AK_MAKE_NONCOPYABLE(Processor);
  81. AK_MAKE_NONMOVABLE(Processor);
  82. Processor* m_self;
  83. DescriptorTablePointer m_gdtr;
  84. Descriptor m_gdt[256];
  85. u32 m_gdt_length;
  86. u32 m_cpu;
  87. u32 m_in_irq;
  88. Atomic<u32, AK::MemoryOrder::memory_order_relaxed> m_in_critical;
  89. static Atomic<u32> s_idle_cpu_mask;
  90. TSS m_tss;
  91. static FPUState s_clean_fpu_state;
  92. CPUFeature m_features;
  93. static volatile u32 g_total_processors; // atomic
  94. u8 m_physical_address_bit_width;
  95. ProcessorInfo* m_info;
  96. MemoryManagerData* m_mm_data;
  97. SchedulerPerProcessorData* m_scheduler_data;
  98. Thread* m_current_thread;
  99. Thread* m_idle_thread;
  100. volatile ProcessorMessageEntry* m_message_queue; // atomic, LIFO
  101. bool m_invoke_scheduler_async;
  102. bool m_scheduler_initialized;
  103. Atomic<bool> m_halt_requested;
  104. DeferredCallEntry* m_pending_deferred_calls; // in reverse order
  105. DeferredCallEntry* m_free_deferred_call_pool_entry;
  106. DeferredCallEntry m_deferred_call_pool[5];
  107. void gdt_init();
  108. void write_raw_gdt_entry(u16 selector, u32 low, u32 high);
  109. void write_gdt_entry(u16 selector, Descriptor& descriptor);
  110. static ProcessorContainer& processors();
  111. static void smp_return_to_pool(ProcessorMessage& msg);
  112. static ProcessorMessage& smp_get_from_pool();
  113. static void smp_cleanup_message(ProcessorMessage& msg);
  114. bool smp_queue_message(ProcessorMessage& msg);
  115. static void smp_unicast_message(u32 cpu, ProcessorMessage& msg, bool async);
  116. static void smp_broadcast_message(ProcessorMessage& msg);
  117. static void smp_broadcast_wait_sync(ProcessorMessage& msg);
  118. static void smp_broadcast_halt();
  119. void deferred_call_pool_init();
  120. void deferred_call_execute_pending();
  121. DeferredCallEntry* deferred_call_get_free();
  122. void deferred_call_return_to_pool(DeferredCallEntry*);
  123. void deferred_call_queue_entry(DeferredCallEntry*);
  124. void cpu_detect();
  125. void cpu_setup();
  126. String features_string() const;
  127. public:
  128. Processor() = default;
  129. void early_initialize(u32 cpu);
  130. void initialize(u32 cpu);
  131. void idle_begin()
  132. {
  133. s_idle_cpu_mask.fetch_or(1u << m_cpu, AK::MemoryOrder::memory_order_relaxed);
  134. }
  135. void idle_end()
  136. {
  137. s_idle_cpu_mask.fetch_and(~(1u << m_cpu), AK::MemoryOrder::memory_order_relaxed);
  138. }
  139. static u32 count()
  140. {
  141. // NOTE: because this value never changes once all APs are booted,
  142. // we don't really need to do an atomic_load() on this variable
  143. return g_total_processors;
  144. }
  145. ALWAYS_INLINE static void wait_check()
  146. {
  147. Processor::current().smp_process_pending_messages();
  148. // TODO: pause
  149. }
  150. [[noreturn]] static void halt();
  151. static void flush_entire_tlb_local()
  152. {
  153. write_cr3(read_cr3());
  154. }
  155. static void flush_tlb_local(VirtualAddress vaddr, size_t page_count);
  156. static void flush_tlb(const PageDirectory*, VirtualAddress, size_t);
  157. Descriptor& get_gdt_entry(u16 selector);
  158. void flush_gdt();
  159. const DescriptorTablePointer& get_gdtr();
  160. static Processor& by_id(u32 cpu);
  161. static size_t processor_count() { return processors().size(); }
  162. template<IteratorFunction<Processor&> Callback>
  163. static inline IterationDecision for_each(Callback callback)
  164. {
  165. auto& procs = processors();
  166. size_t count = procs.size();
  167. for (size_t i = 0; i < count; i++) {
  168. if (callback(*procs[i]) == IterationDecision::Break)
  169. return IterationDecision::Break;
  170. }
  171. return IterationDecision::Continue;
  172. }
  173. template<VoidFunction<Processor&> Callback>
  174. static inline IterationDecision for_each(Callback callback)
  175. {
  176. auto& procs = processors();
  177. size_t count = procs.size();
  178. for (size_t i = 0; i < count; i++) {
  179. if (procs[i] != nullptr)
  180. callback(*procs[i]);
  181. }
  182. return IterationDecision::Continue;
  183. }
  184. ALWAYS_INLINE u8 physical_address_bit_width() const { return m_physical_address_bit_width; }
  185. ALWAYS_INLINE ProcessorInfo& info() { return *m_info; }
  186. ALWAYS_INLINE static Processor& current()
  187. {
  188. return *(Processor*)read_fs_ptr(__builtin_offsetof(Processor, m_self));
  189. }
  190. ALWAYS_INLINE static bool is_initialized()
  191. {
  192. return get_fs() == GDT_SELECTOR_PROC && read_fs_u32(__builtin_offsetof(Processor, m_self)) != 0;
  193. }
  194. ALWAYS_INLINE void set_scheduler_data(SchedulerPerProcessorData& scheduler_data)
  195. {
  196. m_scheduler_data = &scheduler_data;
  197. }
  198. ALWAYS_INLINE SchedulerPerProcessorData& get_scheduler_data() const
  199. {
  200. return *m_scheduler_data;
  201. }
  202. ALWAYS_INLINE void set_mm_data(MemoryManagerData& mm_data)
  203. {
  204. m_mm_data = &mm_data;
  205. }
  206. ALWAYS_INLINE MemoryManagerData& get_mm_data() const
  207. {
  208. return *m_mm_data;
  209. }
  210. ALWAYS_INLINE void set_idle_thread(Thread& idle_thread)
  211. {
  212. m_idle_thread = &idle_thread;
  213. }
  214. ALWAYS_INLINE static Thread* current_thread()
  215. {
  216. // If we were to use Processor::current here, we'd have to
  217. // disable interrupts to prevent a race where we may get pre-empted
  218. // right after getting the Processor structure and then get moved
  219. // to another processor, which would lead us to get the wrong thread.
  220. // To avoid having to disable interrupts, we can just read the field
  221. // directly in an atomic fashion, similar to Processor::current.
  222. return (Thread*)read_fs_ptr(__builtin_offsetof(Processor, m_current_thread));
  223. }
  224. ALWAYS_INLINE static void set_current_thread(Thread& current_thread)
  225. {
  226. // See comment in Processor::current_thread
  227. write_fs_u32(__builtin_offsetof(Processor, m_current_thread), FlatPtr(&current_thread));
  228. }
  229. ALWAYS_INLINE static Thread* idle_thread()
  230. {
  231. // See comment in Processor::current_thread
  232. return (Thread*)read_fs_ptr(__builtin_offsetof(Processor, m_idle_thread));
  233. }
  234. ALWAYS_INLINE u32 get_id() const
  235. {
  236. // NOTE: This variant should only be used when iterating over all
  237. // Processor instances, or when it's guaranteed that the thread
  238. // cannot move to another processor in between calling Processor::current
  239. // and Processor::get_id, or if this fact is not important.
  240. // All other cases should use Processor::id instead!
  241. return m_cpu;
  242. }
  243. ALWAYS_INLINE static u32 id()
  244. {
  245. // See comment in Processor::current_thread
  246. return read_fs_ptr(__builtin_offsetof(Processor, m_cpu));
  247. }
  248. ALWAYS_INLINE static bool is_bootstrap_processor()
  249. {
  250. return Processor::id() == 0;
  251. }
  252. ALWAYS_INLINE u32 raise_irq()
  253. {
  254. return m_in_irq++;
  255. }
  256. ALWAYS_INLINE void restore_irq(u32 prev_irq)
  257. {
  258. VERIFY(prev_irq <= m_in_irq);
  259. if (!prev_irq) {
  260. u32 prev_critical = 0;
  261. if (m_in_critical.compare_exchange_strong(prev_critical, 1)) {
  262. m_in_irq = prev_irq;
  263. deferred_call_execute_pending();
  264. auto prev_raised = m_in_critical.exchange(prev_critical);
  265. VERIFY(prev_raised == prev_critical + 1);
  266. check_invoke_scheduler();
  267. } else if (prev_critical == 0) {
  268. check_invoke_scheduler();
  269. }
  270. } else {
  271. m_in_irq = prev_irq;
  272. }
  273. }
  274. ALWAYS_INLINE u32& in_irq()
  275. {
  276. return m_in_irq;
  277. }
  278. ALWAYS_INLINE void restore_in_critical(u32 critical)
  279. {
  280. m_in_critical = critical;
  281. }
  282. ALWAYS_INLINE void enter_critical(u32& prev_flags)
  283. {
  284. prev_flags = cpu_flags();
  285. cli();
  286. m_in_critical++;
  287. }
  288. ALWAYS_INLINE void leave_critical(u32 prev_flags)
  289. {
  290. cli(); // Need to prevent IRQs from interrupting us here!
  291. VERIFY(m_in_critical > 0);
  292. if (m_in_critical == 1) {
  293. if (!m_in_irq) {
  294. deferred_call_execute_pending();
  295. VERIFY(m_in_critical == 1);
  296. }
  297. m_in_critical--;
  298. if (!m_in_irq)
  299. check_invoke_scheduler();
  300. } else {
  301. m_in_critical--;
  302. }
  303. if (prev_flags & 0x200)
  304. sti();
  305. else
  306. cli();
  307. }
  308. ALWAYS_INLINE u32 clear_critical(u32& prev_flags, bool enable_interrupts)
  309. {
  310. prev_flags = cpu_flags();
  311. u32 prev_crit = m_in_critical.exchange(0, AK::MemoryOrder::memory_order_acquire);
  312. if (!m_in_irq)
  313. check_invoke_scheduler();
  314. if (enable_interrupts)
  315. sti();
  316. return prev_crit;
  317. }
  318. ALWAYS_INLINE void restore_critical(u32 prev_crit, u32 prev_flags)
  319. {
  320. m_in_critical.store(prev_crit, AK::MemoryOrder::memory_order_release);
  321. VERIFY(!prev_crit || !(prev_flags & 0x200));
  322. if (prev_flags & 0x200)
  323. sti();
  324. else
  325. cli();
  326. }
  327. ALWAYS_INLINE u32 in_critical() { return m_in_critical.load(); }
  328. ALWAYS_INLINE const FPUState& clean_fpu_state() const
  329. {
  330. return s_clean_fpu_state;
  331. }
  332. static void smp_enable();
  333. bool smp_process_pending_messages();
  334. static void smp_broadcast(Function<void()>, bool async);
  335. static void smp_unicast(u32 cpu, Function<void()>, bool async);
  336. static void smp_broadcast_flush_tlb(const PageDirectory*, VirtualAddress, size_t);
  337. static u32 smp_wake_n_idle_processors(u32 wake_count);
  338. static void deferred_call_queue(Function<void()> callback);
  339. ALWAYS_INLINE bool has_feature(CPUFeature f) const
  340. {
  341. return (static_cast<u32>(m_features) & static_cast<u32>(f)) != 0;
  342. }
  343. void check_invoke_scheduler();
  344. void invoke_scheduler_async() { m_invoke_scheduler_async = true; }
  345. void enter_trap(TrapFrame& trap, bool raise_irq);
  346. void exit_trap(TrapFrame& trap);
  347. [[noreturn]] void initialize_context_switching(Thread& initial_thread);
  348. NEVER_INLINE void switch_context(Thread*& from_thread, Thread*& to_thread);
  349. [[noreturn]] static void assume_context(Thread& thread, FlatPtr flags);
  350. u32 init_context(Thread& thread, bool leave_crit);
  351. static Vector<FlatPtr> capture_stack_trace(Thread& thread, size_t max_frames = 0);
  352. String platform_string() const;
  353. };
  354. }