Processor.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/BuiltinWrappers.h>
  8. #include <AK/Format.h>
  9. #include <AK/StdLibExtras.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/Types.h>
  12. #include <Kernel/Interrupts/APIC.h>
  13. #include <Kernel/Process.h>
  14. #include <Kernel/Scheduler.h>
  15. #include <Kernel/Sections.h>
  16. #include <Kernel/StdLib.h>
  17. #include <Kernel/Thread.h>
  18. #include <Kernel/Arch/Processor.h>
  19. #include <Kernel/Arch/ScopedCritical.h>
  20. #include <Kernel/Arch/x86/CPUID.h>
  21. #include <Kernel/Arch/x86/InterruptDisabler.h>
  22. #include <Kernel/Arch/x86/Interrupts.h>
  23. #include <Kernel/Arch/x86/MSR.h>
  24. #include <Kernel/Arch/x86/ProcessorInfo.h>
  25. #include <Kernel/Arch/x86/SafeMem.h>
  26. #include <Kernel/Arch/x86/TrapFrame.h>
  27. #include <Kernel/Memory/PageDirectory.h>
  28. #include <Kernel/Memory/ScopedAddressSpaceSwitcher.h>
  29. namespace Kernel {
  30. READONLY_AFTER_INIT FPUState Processor::s_clean_fpu_state;
  31. READONLY_AFTER_INIT static ProcessorContainer s_processors {};
  32. READONLY_AFTER_INIT Atomic<u32> Processor::g_total_processors;
  33. READONLY_AFTER_INIT static volatile bool s_smp_enabled;
  34. static Atomic<ProcessorMessage*> s_message_pool;
  35. Atomic<u32> Processor::s_idle_cpu_mask { 0 };
  36. // The compiler can't see the calls to these functions inside assembly.
  37. // Declare them, to avoid dead code warnings.
  38. extern "C" void context_first_init(Thread* from_thread, Thread* to_thread, TrapFrame* trap) __attribute__((used));
  39. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread) __attribute__((used));
  40. extern "C" FlatPtr do_init_context(Thread* thread, u32 flags) __attribute__((used));
  41. extern "C" void syscall_entry();
  42. bool Processor::is_smp_enabled()
  43. {
  44. return s_smp_enabled;
  45. }
  46. UNMAP_AFTER_INIT static void sse_init()
  47. {
  48. write_cr0((read_cr0() & 0xfffffffbu) | 0x2);
  49. write_cr4(read_cr4() | 0x600);
  50. }
  51. void exit_kernel_thread(void)
  52. {
  53. Thread::current()->exit();
  54. }
  55. UNMAP_AFTER_INIT void Processor::cpu_detect()
  56. {
  57. // NOTE: This is called during Processor::early_initialize, we cannot
  58. // safely log at this point because we don't have kmalloc
  59. // initialized yet!
  60. auto set_feature =
  61. [&](CPUFeature f) {
  62. m_features = static_cast<CPUFeature>(static_cast<u32>(m_features) | static_cast<u32>(f));
  63. };
  64. m_features = static_cast<CPUFeature>(0);
  65. CPUID processor_info(0x1);
  66. if (processor_info.edx() & (1 << 4))
  67. set_feature(CPUFeature::TSC);
  68. if (processor_info.edx() & (1 << 6))
  69. set_feature(CPUFeature::PAE);
  70. if (processor_info.edx() & (1 << 13))
  71. set_feature(CPUFeature::PGE);
  72. if (processor_info.edx() & (1 << 23))
  73. set_feature(CPUFeature::MMX);
  74. if (processor_info.edx() & (1 << 24))
  75. set_feature(CPUFeature::FXSR);
  76. if (processor_info.edx() & (1 << 25))
  77. set_feature(CPUFeature::SSE);
  78. if (processor_info.edx() & (1 << 26))
  79. set_feature(CPUFeature::SSE2);
  80. if (processor_info.ecx() & (1 << 0))
  81. set_feature(CPUFeature::SSE3);
  82. if (processor_info.ecx() & (1 << 9))
  83. set_feature(CPUFeature::SSSE3);
  84. if (processor_info.ecx() & (1 << 19))
  85. set_feature(CPUFeature::SSE4_1);
  86. if (processor_info.ecx() & (1 << 20))
  87. set_feature(CPUFeature::SSE4_2);
  88. if (processor_info.ecx() & (1 << 26))
  89. set_feature(CPUFeature::XSAVE);
  90. if (processor_info.ecx() & (1 << 28))
  91. set_feature(CPUFeature::AVX);
  92. if (processor_info.ecx() & (1 << 30))
  93. set_feature(CPUFeature::RDRAND);
  94. if (processor_info.ecx() & (1u << 31))
  95. set_feature(CPUFeature::HYPERVISOR);
  96. if (processor_info.edx() & (1 << 11)) {
  97. u32 stepping = processor_info.eax() & 0xf;
  98. u32 model = (processor_info.eax() >> 4) & 0xf;
  99. u32 family = (processor_info.eax() >> 8) & 0xf;
  100. if (!(family == 6 && model < 3 && stepping < 3))
  101. set_feature(CPUFeature::SEP);
  102. if ((family == 6 && model >= 3) || (family == 0xf && model >= 0xe))
  103. set_feature(CPUFeature::CONSTANT_TSC);
  104. }
  105. if (processor_info.edx() & (1 << 16))
  106. set_feature(CPUFeature::PAT);
  107. u32 max_extended_leaf = CPUID(0x80000000).eax();
  108. if (max_extended_leaf >= 0x80000001) {
  109. CPUID extended_processor_info(0x80000001);
  110. if (extended_processor_info.edx() & (1 << 20))
  111. set_feature(CPUFeature::NX);
  112. if (extended_processor_info.edx() & (1 << 27))
  113. set_feature(CPUFeature::RDTSCP);
  114. if (extended_processor_info.edx() & (1 << 29))
  115. set_feature(CPUFeature::LM);
  116. if (extended_processor_info.edx() & (1 << 11)) {
  117. // Only available in 64 bit mode
  118. set_feature(CPUFeature::SYSCALL);
  119. }
  120. }
  121. if (max_extended_leaf >= 0x80000007) {
  122. CPUID cpuid(0x80000007);
  123. if (cpuid.edx() & (1 << 8)) {
  124. set_feature(CPUFeature::CONSTANT_TSC);
  125. set_feature(CPUFeature::NONSTOP_TSC);
  126. }
  127. }
  128. if (max_extended_leaf >= 0x80000008) {
  129. // CPUID.80000008H:EAX[7:0] reports the physical-address width supported by the processor.
  130. CPUID cpuid(0x80000008);
  131. m_physical_address_bit_width = cpuid.eax() & 0xff;
  132. // CPUID.80000008H:EAX[15:8] reports the linear-address width supported by the processor.
  133. m_virtual_address_bit_width = (cpuid.eax() >> 8) & 0xff;
  134. } else {
  135. // For processors that do not support CPUID function 80000008H, the width is generally 36 if CPUID.01H:EDX.PAE [bit 6] = 1 and 32 otherwise.
  136. m_physical_address_bit_width = has_feature(CPUFeature::PAE) ? 36 : 32;
  137. // Processors that do not support CPUID function 80000008H, support a linear-address width of 32.
  138. m_virtual_address_bit_width = 32;
  139. }
  140. CPUID extended_features(0x7);
  141. if (extended_features.ebx() & (1 << 20))
  142. set_feature(CPUFeature::SMAP);
  143. if (extended_features.ebx() & (1 << 7))
  144. set_feature(CPUFeature::SMEP);
  145. if (extended_features.ecx() & (1 << 2))
  146. set_feature(CPUFeature::UMIP);
  147. if (extended_features.ebx() & (1 << 18))
  148. set_feature(CPUFeature::RDSEED);
  149. }
  150. UNMAP_AFTER_INIT void Processor::cpu_setup()
  151. {
  152. // NOTE: This is called during Processor::early_initialize, we cannot
  153. // safely log at this point because we don't have kmalloc
  154. // initialized yet!
  155. cpu_detect();
  156. if (has_feature(CPUFeature::SSE)) {
  157. // enter_thread_context() assumes that if a x86 CPU supports SSE then it also supports FXSR.
  158. // SSE support without FXSR is an extremely unlikely scenario, so let's be pragmatic about it.
  159. VERIFY(has_feature(CPUFeature::FXSR));
  160. sse_init();
  161. }
  162. write_cr0(read_cr0() | 0x00010000);
  163. if (has_feature(CPUFeature::PGE)) {
  164. // Turn on CR4.PGE so the CPU will respect the G bit in page tables.
  165. write_cr4(read_cr4() | 0x80);
  166. }
  167. if (has_feature(CPUFeature::NX)) {
  168. // Turn on IA32_EFER.NXE
  169. MSR ia32_efer(MSR_IA32_EFER);
  170. ia32_efer.set(ia32_efer.get() | 0x800);
  171. }
  172. if (has_feature(CPUFeature::PAT)) {
  173. MSR ia32_pat(MSR_IA32_PAT);
  174. // Set PA4 to Write Comine. This allows us to
  175. // use this mode by only setting the bit in the PTE
  176. // and leaving all other bits in the upper levels unset,
  177. // which maps to setting bit 3 of the index, resulting
  178. // in the index value 0 or 4.
  179. u64 pat = ia32_pat.get() & ~(0x7ull << 32);
  180. pat |= 0x1ull << 32; // set WC mode for PA4
  181. ia32_pat.set(pat);
  182. }
  183. if (has_feature(CPUFeature::SMEP)) {
  184. // Turn on CR4.SMEP
  185. write_cr4(read_cr4() | 0x100000);
  186. }
  187. if (has_feature(CPUFeature::SMAP)) {
  188. // Turn on CR4.SMAP
  189. write_cr4(read_cr4() | 0x200000);
  190. }
  191. if (has_feature(CPUFeature::UMIP)) {
  192. write_cr4(read_cr4() | 0x800);
  193. }
  194. if (has_feature(CPUFeature::TSC)) {
  195. write_cr4(read_cr4() | 0x4);
  196. }
  197. if (has_feature(CPUFeature::XSAVE)) {
  198. // Turn on CR4.OSXSAVE
  199. write_cr4(read_cr4() | 0x40000);
  200. // According to the Intel manual: "After reset, all bits (except bit 0) in XCR0 are cleared to zero; XCR0[0] is set to 1."
  201. // Sadly we can't trust this, for example VirtualBox starts with bits 0-4 set, so let's do it ourselves.
  202. write_xcr0(0x1);
  203. if (has_feature(CPUFeature::AVX)) {
  204. // Turn on SSE, AVX and x87 flags
  205. write_xcr0(read_xcr0() | 0x7);
  206. }
  207. }
  208. #if ARCH(X86_64)
  209. // x86_64 processors must support the syscall feature.
  210. VERIFY(has_feature(CPUFeature::SYSCALL));
  211. MSR efer_msr(MSR_EFER);
  212. efer_msr.set(efer_msr.get() | 1u);
  213. // Write code and stack selectors to the STAR MSR. The first value stored in bits 63:48 controls the sysret CS (value + 0x10) and SS (value + 0x8),
  214. // and the value stored in bits 47:32 controls the syscall CS (value) and SS (value + 0x8).
  215. u64 star = 0;
  216. star |= 0x13ul << 48u;
  217. star |= 0x08ul << 32u;
  218. MSR star_msr(MSR_STAR);
  219. star_msr.set(star);
  220. // Write the syscall entry point to the LSTAR MSR.
  221. MSR lstar_msr(MSR_LSTAR);
  222. lstar_msr.set(reinterpret_cast<u64>(&syscall_entry));
  223. // Write the SFMASK MSR. This MSR controls which bits of rflags are masked when a syscall instruction is executed -
  224. // if a bit is set in sfmask, the corresponding bit in rflags is cleared. The value set here clears most of rflags,
  225. // but keeps the reserved and virtualization bits intact. The userspace rflags value is saved in r11 by syscall.
  226. constexpr u64 rflags_mask = 0x257fd5u;
  227. MSR sfmask_msr(MSR_SFMASK);
  228. sfmask_msr.set(rflags_mask);
  229. #endif
  230. }
  231. NonnullOwnPtr<KString> Processor::features_string() const
  232. {
  233. StringBuilder builder;
  234. auto feature_to_str =
  235. [](CPUFeature f) -> StringView {
  236. switch (f) {
  237. case CPUFeature::NX:
  238. return "nx"sv;
  239. case CPUFeature::PAE:
  240. return "pae"sv;
  241. case CPUFeature::PGE:
  242. return "pge"sv;
  243. case CPUFeature::RDRAND:
  244. return "rdrand"sv;
  245. case CPUFeature::RDSEED:
  246. return "rdseed"sv;
  247. case CPUFeature::SMAP:
  248. return "smap"sv;
  249. case CPUFeature::SMEP:
  250. return "smep"sv;
  251. case CPUFeature::SSE:
  252. return "sse"sv;
  253. case CPUFeature::TSC:
  254. return "tsc"sv;
  255. case CPUFeature::RDTSCP:
  256. return "rdtscp"sv;
  257. case CPUFeature::CONSTANT_TSC:
  258. return "constant_tsc"sv;
  259. case CPUFeature::NONSTOP_TSC:
  260. return "nonstop_tsc"sv;
  261. case CPUFeature::UMIP:
  262. return "umip"sv;
  263. case CPUFeature::SEP:
  264. return "sep"sv;
  265. case CPUFeature::SYSCALL:
  266. return "syscall"sv;
  267. case CPUFeature::MMX:
  268. return "mmx"sv;
  269. case CPUFeature::FXSR:
  270. return "fxsr"sv;
  271. case CPUFeature::SSE2:
  272. return "sse2"sv;
  273. case CPUFeature::SSE3:
  274. return "sse3"sv;
  275. case CPUFeature::SSSE3:
  276. return "ssse3"sv;
  277. case CPUFeature::SSE4_1:
  278. return "sse4.1"sv;
  279. case CPUFeature::SSE4_2:
  280. return "sse4.2"sv;
  281. case CPUFeature::XSAVE:
  282. return "xsave"sv;
  283. case CPUFeature::AVX:
  284. return "avx"sv;
  285. case CPUFeature::LM:
  286. return "lm"sv;
  287. case CPUFeature::HYPERVISOR:
  288. return "hypervisor"sv;
  289. // no default statement here intentionally so that we get
  290. // a warning if a new feature is forgotten to be added here
  291. case CPUFeature::PAT:
  292. return "pat"sv;
  293. }
  294. // Shouldn't ever happen
  295. return "???"sv;
  296. };
  297. bool first = true;
  298. for (u32 flag = 1; flag != 0; flag <<= 1) {
  299. if ((static_cast<u32>(m_features) & flag) != 0) {
  300. if (first)
  301. first = false;
  302. else
  303. MUST(builder.try_append(' '));
  304. auto str = feature_to_str(static_cast<CPUFeature>(flag));
  305. MUST(builder.try_append(str));
  306. }
  307. }
  308. return KString::must_create(builder.string_view());
  309. }
  310. UNMAP_AFTER_INIT void Processor::early_initialize(u32 cpu)
  311. {
  312. m_self = this;
  313. m_cpu = cpu;
  314. m_in_irq = 0;
  315. m_in_critical = 0;
  316. m_invoke_scheduler_async = false;
  317. m_scheduler_initialized = false;
  318. m_in_scheduler = true;
  319. m_message_queue = nullptr;
  320. m_idle_thread = nullptr;
  321. m_current_thread = nullptr;
  322. m_info = nullptr;
  323. m_halt_requested = false;
  324. if (cpu == 0) {
  325. s_smp_enabled = false;
  326. g_total_processors.store(1u, AK::MemoryOrder::memory_order_release);
  327. } else {
  328. g_total_processors.fetch_add(1u, AK::MemoryOrder::memory_order_acq_rel);
  329. }
  330. deferred_call_pool_init();
  331. cpu_setup();
  332. gdt_init();
  333. VERIFY(is_initialized()); // sanity check
  334. VERIFY(&current() == this); // sanity check
  335. }
  336. UNMAP_AFTER_INIT void Processor::initialize(u32 cpu)
  337. {
  338. VERIFY(m_self == this);
  339. VERIFY(&current() == this); // sanity check
  340. dmesgln("CPU[{}]: Supported features: {}", current_id(), features_string());
  341. if (!has_feature(CPUFeature::RDRAND))
  342. dmesgln("CPU[{}]: No RDRAND support detected, randomness will be poor", current_id());
  343. dmesgln("CPU[{}]: Physical address bit width: {}", current_id(), m_physical_address_bit_width);
  344. dmesgln("CPU[{}]: Virtual address bit width: {}", current_id(), m_virtual_address_bit_width);
  345. if (cpu == 0)
  346. idt_init();
  347. else
  348. flush_idt();
  349. if (cpu == 0) {
  350. VERIFY((FlatPtr(&s_clean_fpu_state) & 0xF) == 0);
  351. asm volatile("fninit");
  352. if (has_feature(CPUFeature::FXSR))
  353. asm volatile("fxsave %0"
  354. : "=m"(s_clean_fpu_state));
  355. else
  356. asm volatile("fnsave %0"
  357. : "=m"(s_clean_fpu_state));
  358. if (has_feature(CPUFeature::HYPERVISOR))
  359. detect_hypervisor();
  360. }
  361. m_info = new ProcessorInfo(*this);
  362. {
  363. // We need to prevent races between APs starting up at the same time
  364. VERIFY(cpu < s_processors.size());
  365. s_processors[cpu] = this;
  366. }
  367. }
  368. UNMAP_AFTER_INIT void Processor::detect_hypervisor()
  369. {
  370. CPUID hypervisor_leaf_range(0x40000000);
  371. // Get signature of hypervisor.
  372. alignas(sizeof(u32)) char hypervisor_signature_buffer[13];
  373. *reinterpret_cast<u32*>(hypervisor_signature_buffer) = hypervisor_leaf_range.ebx();
  374. *reinterpret_cast<u32*>(hypervisor_signature_buffer + 4) = hypervisor_leaf_range.ecx();
  375. *reinterpret_cast<u32*>(hypervisor_signature_buffer + 8) = hypervisor_leaf_range.edx();
  376. hypervisor_signature_buffer[12] = '\0';
  377. StringView hypervisor_signature(hypervisor_signature_buffer);
  378. dmesgln("CPU[{}]: CPUID hypervisor signature '{}' ({:#x} {:#x} {:#x}), max leaf {:#x}", current_id(), hypervisor_signature, hypervisor_leaf_range.ebx(), hypervisor_leaf_range.ecx(), hypervisor_leaf_range.edx(), hypervisor_leaf_range.eax());
  379. if (hypervisor_signature == "Microsoft Hv"sv)
  380. detect_hypervisor_hyperv(hypervisor_leaf_range);
  381. }
  382. UNMAP_AFTER_INIT void Processor::detect_hypervisor_hyperv(CPUID const& hypervisor_leaf_range)
  383. {
  384. if (hypervisor_leaf_range.eax() < 0x40000001)
  385. return;
  386. CPUID hypervisor_interface(0x40000001);
  387. // Get signature of hypervisor interface.
  388. alignas(sizeof(u32)) char interface_signature_buffer[5];
  389. *reinterpret_cast<u32*>(interface_signature_buffer) = hypervisor_interface.eax();
  390. interface_signature_buffer[4] = '\0';
  391. StringView hyperv_interface_signature(interface_signature_buffer);
  392. dmesgln("CPU[{}]: Hyper-V interface signature '{}' ({:#x})", current_id(), hyperv_interface_signature, hypervisor_interface.eax());
  393. if (hypervisor_leaf_range.eax() < 0x40000001)
  394. return;
  395. CPUID hypervisor_sysid(0x40000002);
  396. dmesgln("CPU[{}]: Hyper-V system identity {}.{}, build number {}", current_id(), hypervisor_sysid.ebx() >> 16, hypervisor_sysid.ebx() & 0xFFFF, hypervisor_sysid.eax());
  397. if (hypervisor_leaf_range.eax() < 0x40000005 || hyperv_interface_signature != "Hv#1"sv)
  398. return;
  399. dmesgln("CPU[{}]: Hyper-V hypervisor detected", current_id());
  400. // TODO: Actually do something with Hyper-V.
  401. }
  402. void Processor::write_raw_gdt_entry(u16 selector, u32 low, u32 high)
  403. {
  404. u16 i = (selector & 0xfffc) >> 3;
  405. u32 prev_gdt_length = m_gdt_length;
  406. if (i >= m_gdt_length) {
  407. m_gdt_length = i + 1;
  408. VERIFY(m_gdt_length <= sizeof(m_gdt) / sizeof(m_gdt[0]));
  409. m_gdtr.limit = (m_gdt_length + 1) * 8 - 1;
  410. }
  411. m_gdt[i].low = low;
  412. m_gdt[i].high = high;
  413. // clear selectors we may have skipped
  414. for (auto j = prev_gdt_length; j < i; ++j) {
  415. m_gdt[j].low = 0;
  416. m_gdt[j].high = 0;
  417. }
  418. }
  419. void Processor::write_gdt_entry(u16 selector, Descriptor& descriptor)
  420. {
  421. write_raw_gdt_entry(selector, descriptor.low, descriptor.high);
  422. }
  423. Descriptor& Processor::get_gdt_entry(u16 selector)
  424. {
  425. u16 i = (selector & 0xfffc) >> 3;
  426. return *(Descriptor*)(&m_gdt[i]);
  427. }
  428. void Processor::flush_gdt()
  429. {
  430. m_gdtr.address = m_gdt;
  431. m_gdtr.limit = (m_gdt_length * 8) - 1;
  432. asm volatile("lgdt %0" ::"m"(m_gdtr)
  433. : "memory");
  434. }
  435. const DescriptorTablePointer& Processor::get_gdtr()
  436. {
  437. return m_gdtr;
  438. }
  439. ErrorOr<Vector<FlatPtr, 32>> Processor::capture_stack_trace(Thread& thread, size_t max_frames)
  440. {
  441. FlatPtr frame_ptr = 0, ip = 0;
  442. Vector<FlatPtr, 32> stack_trace;
  443. auto walk_stack = [&](FlatPtr stack_ptr) -> ErrorOr<void> {
  444. constexpr size_t max_stack_frames = 4096;
  445. bool is_walking_userspace_stack = false;
  446. TRY(stack_trace.try_append(ip));
  447. size_t count = 1;
  448. while (stack_ptr && stack_trace.size() < max_stack_frames) {
  449. FlatPtr retaddr;
  450. count++;
  451. if (max_frames != 0 && count > max_frames)
  452. break;
  453. if (!Memory::is_user_address(VirtualAddress { stack_ptr })) {
  454. if (is_walking_userspace_stack) {
  455. dbgln("SHENANIGANS! Userspace stack points back into kernel memory");
  456. break;
  457. }
  458. } else {
  459. is_walking_userspace_stack = true;
  460. }
  461. if (Memory::is_user_range(VirtualAddress(stack_ptr), sizeof(FlatPtr) * 2)) {
  462. if (copy_from_user(&retaddr, &((FlatPtr*)stack_ptr)[1]).is_error() || !retaddr)
  463. break;
  464. TRY(stack_trace.try_append(retaddr));
  465. if (copy_from_user(&stack_ptr, (FlatPtr*)stack_ptr).is_error())
  466. break;
  467. } else {
  468. void* fault_at;
  469. if (!safe_memcpy(&retaddr, &((FlatPtr*)stack_ptr)[1], sizeof(FlatPtr), fault_at) || !retaddr)
  470. break;
  471. TRY(stack_trace.try_append(retaddr));
  472. if (!safe_memcpy(&stack_ptr, (FlatPtr*)stack_ptr, sizeof(FlatPtr), fault_at))
  473. break;
  474. }
  475. }
  476. return {};
  477. };
  478. auto capture_current_thread = [&]() {
  479. frame_ptr = (FlatPtr)__builtin_frame_address(0);
  480. ip = (FlatPtr)__builtin_return_address(0);
  481. return walk_stack(frame_ptr);
  482. };
  483. // Since the thread may be running on another processor, there
  484. // is a chance a context switch may happen while we're trying
  485. // to get it. It also won't be entirely accurate and merely
  486. // reflect the status at the last context switch.
  487. SpinlockLocker lock(g_scheduler_lock);
  488. if (&thread == Processor::current_thread()) {
  489. VERIFY(thread.state() == Thread::State::Running);
  490. // Leave the scheduler lock. If we trigger page faults we may
  491. // need to be preempted. Since this is our own thread it won't
  492. // cause any problems as the stack won't change below this frame.
  493. lock.unlock();
  494. TRY(capture_current_thread());
  495. } else if (thread.is_active()) {
  496. VERIFY(thread.cpu() != Processor::current_id());
  497. // If this is the case, the thread is currently running
  498. // on another processor. We can't trust the kernel stack as
  499. // it may be changing at any time. We need to probably send
  500. // an IPI to that processor, have it walk the stack and wait
  501. // until it returns the data back to us
  502. auto& proc = Processor::current();
  503. ErrorOr<void> result;
  504. smp_unicast(
  505. thread.cpu(),
  506. [&]() {
  507. dbgln("CPU[{}] getting stack for cpu #{}", Processor::current_id(), proc.id());
  508. ScopedAddressSpaceSwitcher switcher(thread.process());
  509. VERIFY(&Processor::current() != &proc);
  510. VERIFY(&thread == Processor::current_thread());
  511. // NOTE: Because the other processor is still holding the
  512. // scheduler lock while waiting for this callback to finish,
  513. // the current thread on the target processor cannot change
  514. // TODO: What to do about page faults here? We might deadlock
  515. // because the other processor is still holding the
  516. // scheduler lock...
  517. result = capture_current_thread();
  518. },
  519. false);
  520. TRY(result);
  521. } else {
  522. switch (thread.state()) {
  523. case Thread::State::Running:
  524. VERIFY_NOT_REACHED(); // should have been handled above
  525. case Thread::State::Runnable:
  526. case Thread::State::Stopped:
  527. case Thread::State::Blocked:
  528. case Thread::State::Dying:
  529. case Thread::State::Dead: {
  530. // We need to retrieve ebp from what was last pushed to the kernel
  531. // stack. Before switching out of that thread, it switch_context
  532. // pushed the callee-saved registers, and the last of them happens
  533. // to be ebp.
  534. ScopedAddressSpaceSwitcher switcher(thread.process());
  535. auto& regs = thread.regs();
  536. auto* stack_top = reinterpret_cast<FlatPtr*>(regs.sp());
  537. if (Memory::is_user_range(VirtualAddress(stack_top), sizeof(FlatPtr))) {
  538. if (copy_from_user(&frame_ptr, &((FlatPtr*)stack_top)[0]).is_error())
  539. frame_ptr = 0;
  540. } else {
  541. void* fault_at;
  542. if (!safe_memcpy(&frame_ptr, &((FlatPtr*)stack_top)[0], sizeof(FlatPtr), fault_at))
  543. frame_ptr = 0;
  544. }
  545. ip = regs.ip();
  546. // TODO: We need to leave the scheduler lock here, but we also
  547. // need to prevent the target thread from being run while
  548. // we walk the stack
  549. lock.unlock();
  550. TRY(walk_stack(frame_ptr));
  551. break;
  552. }
  553. default:
  554. dbgln("Cannot capture stack trace for thread {} in state {}", thread, thread.state_string());
  555. break;
  556. }
  557. }
  558. return stack_trace;
  559. }
  560. ProcessorContainer& Processor::processors()
  561. {
  562. return s_processors;
  563. }
  564. Processor& Processor::by_id(u32 id)
  565. {
  566. return *s_processors[id];
  567. }
  568. void Processor::enter_trap(TrapFrame& trap, bool raise_irq)
  569. {
  570. VERIFY_INTERRUPTS_DISABLED();
  571. VERIFY(&Processor::current() == this);
  572. trap.prev_irq_level = m_in_irq;
  573. if (raise_irq)
  574. m_in_irq++;
  575. auto* current_thread = Processor::current_thread();
  576. if (current_thread) {
  577. auto& current_trap = current_thread->current_trap();
  578. trap.next_trap = current_trap;
  579. current_trap = &trap;
  580. // The cs register of this trap tells us where we will return back to
  581. auto new_previous_mode = ((trap.regs->cs & 3) != 0) ? Thread::PreviousMode::UserMode : Thread::PreviousMode::KernelMode;
  582. if (current_thread->set_previous_mode(new_previous_mode) && trap.prev_irq_level == 0) {
  583. current_thread->update_time_scheduled(Scheduler::current_time(), new_previous_mode == Thread::PreviousMode::KernelMode, false);
  584. }
  585. } else {
  586. trap.next_trap = nullptr;
  587. }
  588. }
  589. void Processor::exit_trap(TrapFrame& trap)
  590. {
  591. VERIFY_INTERRUPTS_DISABLED();
  592. VERIFY(&Processor::current() == this);
  593. // Temporarily enter a critical section. This is to prevent critical
  594. // sections entered and left within e.g. smp_process_pending_messages
  595. // to trigger a context switch while we're executing this function
  596. // See the comment at the end of the function why we don't use
  597. // ScopedCritical here.
  598. m_in_critical = m_in_critical + 1;
  599. VERIFY(m_in_irq >= trap.prev_irq_level);
  600. m_in_irq = trap.prev_irq_level;
  601. if (s_smp_enabled)
  602. smp_process_pending_messages();
  603. // Process the deferred call queue. Among other things, this ensures
  604. // that any pending thread unblocks happen before we enter the scheduler.
  605. deferred_call_execute_pending();
  606. auto* current_thread = Processor::current_thread();
  607. if (current_thread) {
  608. auto& current_trap = current_thread->current_trap();
  609. current_trap = trap.next_trap;
  610. Thread::PreviousMode new_previous_mode;
  611. if (current_trap) {
  612. VERIFY(current_trap->regs);
  613. // If we have another higher level trap then we probably returned
  614. // from an interrupt or irq handler. The cs register of the
  615. // new/higher level trap tells us what the mode prior to it was
  616. new_previous_mode = ((current_trap->regs->cs & 3) != 0) ? Thread::PreviousMode::UserMode : Thread::PreviousMode::KernelMode;
  617. } else {
  618. // If we don't have a higher level trap then we're back in user mode.
  619. // Which means that the previous mode prior to being back in user mode was kernel mode
  620. new_previous_mode = Thread::PreviousMode::KernelMode;
  621. }
  622. if (current_thread->set_previous_mode(new_previous_mode))
  623. current_thread->update_time_scheduled(Scheduler::current_time(), true, false);
  624. }
  625. VERIFY_INTERRUPTS_DISABLED();
  626. // Leave the critical section without actually enabling interrupts.
  627. // We don't want context switches to happen until we're explicitly
  628. // triggering a switch in check_invoke_scheduler.
  629. m_in_critical = m_in_critical - 1;
  630. if (!m_in_irq && !m_in_critical)
  631. check_invoke_scheduler();
  632. }
  633. void Processor::check_invoke_scheduler()
  634. {
  635. InterruptDisabler disabler;
  636. VERIFY(!m_in_irq);
  637. VERIFY(!m_in_critical);
  638. VERIFY(&Processor::current() == this);
  639. if (m_invoke_scheduler_async && m_scheduler_initialized) {
  640. m_invoke_scheduler_async = false;
  641. Scheduler::invoke_async();
  642. }
  643. }
  644. void Processor::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  645. {
  646. auto ptr = vaddr.as_ptr();
  647. while (page_count > 0) {
  648. // clang-format off
  649. asm volatile("invlpg %0"
  650. :
  651. : "m"(*ptr)
  652. : "memory");
  653. // clang-format on
  654. ptr += PAGE_SIZE;
  655. page_count--;
  656. }
  657. }
  658. void Processor::flush_tlb(Memory::PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
  659. {
  660. if (s_smp_enabled && (!Memory::is_user_address(vaddr) || Process::current().thread_count() > 1))
  661. smp_broadcast_flush_tlb(page_directory, vaddr, page_count);
  662. else
  663. flush_tlb_local(vaddr, page_count);
  664. }
  665. void Processor::smp_return_to_pool(ProcessorMessage& msg)
  666. {
  667. ProcessorMessage* next = nullptr;
  668. for (;;) {
  669. msg.next = next;
  670. if (s_message_pool.compare_exchange_strong(next, &msg, AK::MemoryOrder::memory_order_acq_rel))
  671. break;
  672. Processor::pause();
  673. }
  674. }
  675. ProcessorMessage& Processor::smp_get_from_pool()
  676. {
  677. ProcessorMessage* msg;
  678. // The assumption is that messages are never removed from the pool!
  679. for (;;) {
  680. msg = s_message_pool.load(AK::MemoryOrder::memory_order_consume);
  681. if (!msg) {
  682. if (!Processor::current().smp_process_pending_messages()) {
  683. Processor::pause();
  684. }
  685. continue;
  686. }
  687. // If another processor were to use this message in the meanwhile,
  688. // "msg" is still valid (because it never gets freed). We'd detect
  689. // this because the expected value "msg" and pool would
  690. // no longer match, and the compare_exchange will fail. But accessing
  691. // "msg->next" is always safe here.
  692. if (s_message_pool.compare_exchange_strong(msg, msg->next, AK::MemoryOrder::memory_order_acq_rel)) {
  693. // We successfully "popped" this available message
  694. break;
  695. }
  696. }
  697. VERIFY(msg != nullptr);
  698. return *msg;
  699. }
  700. u32 Processor::smp_wake_n_idle_processors(u32 wake_count)
  701. {
  702. VERIFY_INTERRUPTS_DISABLED();
  703. VERIFY(wake_count > 0);
  704. if (!s_smp_enabled)
  705. return 0;
  706. // Wake at most N - 1 processors
  707. if (wake_count >= Processor::count()) {
  708. wake_count = Processor::count() - 1;
  709. VERIFY(wake_count > 0);
  710. }
  711. u32 current_id = Processor::current_id();
  712. u32 did_wake_count = 0;
  713. auto& apic = APIC::the();
  714. while (did_wake_count < wake_count) {
  715. // Try to get a set of idle CPUs and flip them to busy
  716. u32 idle_mask = s_idle_cpu_mask.load(AK::MemoryOrder::memory_order_relaxed) & ~(1u << current_id);
  717. u32 idle_count = popcount(idle_mask);
  718. if (idle_count == 0)
  719. break; // No (more) idle processor available
  720. u32 found_mask = 0;
  721. for (u32 i = 0; i < idle_count; i++) {
  722. u32 cpu = bit_scan_forward(idle_mask) - 1;
  723. idle_mask &= ~(1u << cpu);
  724. found_mask |= 1u << cpu;
  725. }
  726. idle_mask = s_idle_cpu_mask.fetch_and(~found_mask, AK::MemoryOrder::memory_order_acq_rel) & found_mask;
  727. if (idle_mask == 0)
  728. continue; // All of them were flipped to busy, try again
  729. idle_count = popcount(idle_mask);
  730. for (u32 i = 0; i < idle_count; i++) {
  731. u32 cpu = bit_scan_forward(idle_mask) - 1;
  732. idle_mask &= ~(1u << cpu);
  733. // Send an IPI to that CPU to wake it up. There is a possibility
  734. // someone else woke it up as well, or that it woke up due to
  735. // a timer interrupt. But we tried hard to avoid this...
  736. apic.send_ipi(cpu);
  737. did_wake_count++;
  738. }
  739. }
  740. return did_wake_count;
  741. }
  742. UNMAP_AFTER_INIT void Processor::smp_enable()
  743. {
  744. size_t msg_pool_size = Processor::count() * 100u;
  745. size_t msg_entries_cnt = Processor::count();
  746. auto msgs = new ProcessorMessage[msg_pool_size];
  747. auto msg_entries = new ProcessorMessageEntry[msg_pool_size * msg_entries_cnt];
  748. size_t msg_entry_i = 0;
  749. for (size_t i = 0; i < msg_pool_size; i++, msg_entry_i += msg_entries_cnt) {
  750. auto& msg = msgs[i];
  751. msg.next = i < msg_pool_size - 1 ? &msgs[i + 1] : nullptr;
  752. msg.per_proc_entries = &msg_entries[msg_entry_i];
  753. for (size_t k = 0; k < msg_entries_cnt; k++)
  754. msg_entries[msg_entry_i + k].msg = &msg;
  755. }
  756. s_message_pool.store(&msgs[0], AK::MemoryOrder::memory_order_release);
  757. // Start sending IPI messages
  758. s_smp_enabled = true;
  759. }
  760. void Processor::smp_cleanup_message(ProcessorMessage& msg)
  761. {
  762. switch (msg.type) {
  763. case ProcessorMessage::Callback:
  764. msg.callback_value().~Function();
  765. break;
  766. default:
  767. break;
  768. }
  769. }
  770. bool Processor::smp_process_pending_messages()
  771. {
  772. VERIFY(s_smp_enabled);
  773. bool did_process = false;
  774. enter_critical();
  775. if (auto pending_msgs = m_message_queue.exchange(nullptr, AK::MemoryOrder::memory_order_acq_rel)) {
  776. // We pulled the stack of pending messages in LIFO order, so we need to reverse the list first
  777. auto reverse_list =
  778. [](ProcessorMessageEntry* list) -> ProcessorMessageEntry* {
  779. ProcessorMessageEntry* rev_list = nullptr;
  780. while (list) {
  781. auto next = list->next;
  782. list->next = rev_list;
  783. rev_list = list;
  784. list = next;
  785. }
  786. return rev_list;
  787. };
  788. pending_msgs = reverse_list(pending_msgs);
  789. // now process in the right order
  790. ProcessorMessageEntry* next_msg;
  791. for (auto cur_msg = pending_msgs; cur_msg; cur_msg = next_msg) {
  792. next_msg = cur_msg->next;
  793. auto msg = cur_msg->msg;
  794. dbgln_if(SMP_DEBUG, "SMP[{}]: Processing message {}", current_id(), VirtualAddress(msg));
  795. switch (msg->type) {
  796. case ProcessorMessage::Callback:
  797. msg->invoke_callback();
  798. break;
  799. case ProcessorMessage::FlushTlb:
  800. if (Memory::is_user_address(VirtualAddress(msg->flush_tlb.ptr))) {
  801. // We assume that we don't cross into kernel land!
  802. VERIFY(Memory::is_user_range(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count * PAGE_SIZE));
  803. if (read_cr3() != msg->flush_tlb.page_directory->cr3()) {
  804. // This processor isn't using this page directory right now, we can ignore this request
  805. dbgln_if(SMP_DEBUG, "SMP[{}]: No need to flush {} pages at {}", current_id(), msg->flush_tlb.page_count, VirtualAddress(msg->flush_tlb.ptr));
  806. break;
  807. }
  808. }
  809. flush_tlb_local(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count);
  810. break;
  811. }
  812. bool is_async = msg->async; // Need to cache this value *before* dropping the ref count!
  813. auto prev_refs = msg->refs.fetch_sub(1u, AK::MemoryOrder::memory_order_acq_rel);
  814. VERIFY(prev_refs != 0);
  815. if (prev_refs == 1) {
  816. // All processors handled this. If this is an async message,
  817. // we need to clean it up and return it to the pool
  818. if (is_async) {
  819. smp_cleanup_message(*msg);
  820. smp_return_to_pool(*msg);
  821. }
  822. }
  823. if (m_halt_requested.load(AK::MemoryOrder::memory_order_relaxed))
  824. halt_this();
  825. }
  826. did_process = true;
  827. } else if (m_halt_requested.load(AK::MemoryOrder::memory_order_relaxed)) {
  828. halt_this();
  829. }
  830. leave_critical();
  831. return did_process;
  832. }
  833. bool Processor::smp_enqueue_message(ProcessorMessage& msg)
  834. {
  835. // Note that it's quite possible that the other processor may pop
  836. // the queue at any given time. We rely on the fact that the messages
  837. // are pooled and never get freed!
  838. auto& msg_entry = msg.per_proc_entries[id()];
  839. VERIFY(msg_entry.msg == &msg);
  840. ProcessorMessageEntry* next = nullptr;
  841. for (;;) {
  842. msg_entry.next = next;
  843. if (m_message_queue.compare_exchange_strong(next, &msg_entry, AK::MemoryOrder::memory_order_acq_rel))
  844. break;
  845. Processor::pause();
  846. }
  847. // If the enqueued message was the only message in the queue when posted,
  848. // we return true. This is used by callers when deciding whether to generate an IPI.
  849. return next == nullptr;
  850. }
  851. void Processor::smp_broadcast_message(ProcessorMessage& msg)
  852. {
  853. auto& current_processor = Processor::current();
  854. dbgln_if(SMP_DEBUG, "SMP[{}]: Broadcast message {} to cpus: {} processor: {}", current_processor.id(), VirtualAddress(&msg), count(), VirtualAddress(&current_processor));
  855. msg.refs.store(count() - 1, AK::MemoryOrder::memory_order_release);
  856. VERIFY(msg.refs > 0);
  857. bool need_broadcast = false;
  858. for_each(
  859. [&](Processor& proc) {
  860. if (&proc != &current_processor) {
  861. if (proc.smp_enqueue_message(msg))
  862. need_broadcast = true;
  863. }
  864. });
  865. // Now trigger an IPI on all other APs (unless all targets already had messages queued)
  866. if (need_broadcast)
  867. APIC::the().broadcast_ipi();
  868. }
  869. void Processor::smp_broadcast_wait_sync(ProcessorMessage& msg)
  870. {
  871. auto& cur_proc = Processor::current();
  872. VERIFY(!msg.async);
  873. // If synchronous then we must cleanup and return the message back
  874. // to the pool. Otherwise, the last processor to complete it will return it
  875. while (msg.refs.load(AK::MemoryOrder::memory_order_consume) != 0) {
  876. Processor::pause();
  877. // We need to process any messages that may have been sent to
  878. // us while we're waiting. This also checks if another processor
  879. // may have requested us to halt.
  880. cur_proc.smp_process_pending_messages();
  881. }
  882. smp_cleanup_message(msg);
  883. smp_return_to_pool(msg);
  884. }
  885. void Processor::smp_unicast_message(u32 cpu, ProcessorMessage& msg, bool async)
  886. {
  887. auto& current_processor = Processor::current();
  888. VERIFY(cpu != current_processor.id());
  889. auto& target_processor = processors()[cpu];
  890. msg.async = async;
  891. dbgln_if(SMP_DEBUG, "SMP[{}]: Send message {} to cpu #{} processor: {}", current_processor.id(), VirtualAddress(&msg), cpu, VirtualAddress(&target_processor));
  892. msg.refs.store(1u, AK::MemoryOrder::memory_order_release);
  893. if (target_processor->smp_enqueue_message(msg)) {
  894. APIC::the().send_ipi(cpu);
  895. }
  896. if (!async) {
  897. // If synchronous then we must cleanup and return the message back
  898. // to the pool. Otherwise, the last processor to complete it will return it
  899. while (msg.refs.load(AK::MemoryOrder::memory_order_consume) != 0) {
  900. Processor::pause();
  901. // We need to process any messages that may have been sent to
  902. // us while we're waiting. This also checks if another processor
  903. // may have requested us to halt.
  904. current_processor.smp_process_pending_messages();
  905. }
  906. smp_cleanup_message(msg);
  907. smp_return_to_pool(msg);
  908. }
  909. }
  910. void Processor::smp_unicast(u32 cpu, Function<void()> callback, bool async)
  911. {
  912. auto& msg = smp_get_from_pool();
  913. msg.type = ProcessorMessage::Callback;
  914. new (msg.callback_storage) ProcessorMessage::CallbackFunction(move(callback));
  915. smp_unicast_message(cpu, msg, async);
  916. }
  917. void Processor::smp_broadcast_flush_tlb(Memory::PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
  918. {
  919. auto& msg = smp_get_from_pool();
  920. msg.async = false;
  921. msg.type = ProcessorMessage::FlushTlb;
  922. msg.flush_tlb.page_directory = page_directory;
  923. msg.flush_tlb.ptr = vaddr.as_ptr();
  924. msg.flush_tlb.page_count = page_count;
  925. smp_broadcast_message(msg);
  926. // While the other processors handle this request, we'll flush ours
  927. flush_tlb_local(vaddr, page_count);
  928. // Now wait until everybody is done as well
  929. smp_broadcast_wait_sync(msg);
  930. }
  931. void Processor::smp_broadcast_halt()
  932. {
  933. // We don't want to use a message, because this could have been triggered
  934. // by being out of memory and we might not be able to get a message
  935. for_each(
  936. [&](Processor& proc) {
  937. proc.m_halt_requested.store(true, AK::MemoryOrder::memory_order_release);
  938. });
  939. // Now trigger an IPI on all other APs
  940. APIC::the().broadcast_ipi();
  941. }
  942. void Processor::Processor::halt()
  943. {
  944. if (s_smp_enabled)
  945. smp_broadcast_halt();
  946. halt_this();
  947. }
  948. UNMAP_AFTER_INIT void Processor::deferred_call_pool_init()
  949. {
  950. size_t pool_count = sizeof(m_deferred_call_pool) / sizeof(m_deferred_call_pool[0]);
  951. for (size_t i = 0; i < pool_count; i++) {
  952. auto& entry = m_deferred_call_pool[i];
  953. entry.next = i < pool_count - 1 ? &m_deferred_call_pool[i + 1] : nullptr;
  954. new (entry.handler_storage) DeferredCallEntry::HandlerFunction;
  955. entry.was_allocated = false;
  956. }
  957. m_pending_deferred_calls = nullptr;
  958. m_free_deferred_call_pool_entry = &m_deferred_call_pool[0];
  959. }
  960. void Processor::deferred_call_return_to_pool(DeferredCallEntry* entry)
  961. {
  962. VERIFY(m_in_critical);
  963. VERIFY(!entry->was_allocated);
  964. entry->handler_value() = {};
  965. entry->next = m_free_deferred_call_pool_entry;
  966. m_free_deferred_call_pool_entry = entry;
  967. }
  968. DeferredCallEntry* Processor::deferred_call_get_free()
  969. {
  970. VERIFY(m_in_critical);
  971. if (m_free_deferred_call_pool_entry) {
  972. // Fast path, we have an entry in our pool
  973. auto* entry = m_free_deferred_call_pool_entry;
  974. m_free_deferred_call_pool_entry = entry->next;
  975. VERIFY(!entry->was_allocated);
  976. return entry;
  977. }
  978. auto* entry = new DeferredCallEntry;
  979. new (entry->handler_storage) DeferredCallEntry::HandlerFunction;
  980. entry->was_allocated = true;
  981. return entry;
  982. }
  983. void Processor::deferred_call_execute_pending()
  984. {
  985. VERIFY(m_in_critical);
  986. if (!m_pending_deferred_calls)
  987. return;
  988. auto* pending_list = m_pending_deferred_calls;
  989. m_pending_deferred_calls = nullptr;
  990. // We pulled the stack of pending deferred calls in LIFO order, so we need to reverse the list first
  991. auto reverse_list =
  992. [](DeferredCallEntry* list) -> DeferredCallEntry* {
  993. DeferredCallEntry* rev_list = nullptr;
  994. while (list) {
  995. auto next = list->next;
  996. list->next = rev_list;
  997. rev_list = list;
  998. list = next;
  999. }
  1000. return rev_list;
  1001. };
  1002. pending_list = reverse_list(pending_list);
  1003. do {
  1004. pending_list->invoke_handler();
  1005. // Return the entry back to the pool, or free it
  1006. auto* next = pending_list->next;
  1007. if (pending_list->was_allocated) {
  1008. pending_list->handler_value().~Function();
  1009. delete pending_list;
  1010. } else
  1011. deferred_call_return_to_pool(pending_list);
  1012. pending_list = next;
  1013. } while (pending_list);
  1014. }
  1015. void Processor::deferred_call_queue_entry(DeferredCallEntry* entry)
  1016. {
  1017. VERIFY(m_in_critical);
  1018. entry->next = m_pending_deferred_calls;
  1019. m_pending_deferred_calls = entry;
  1020. }
  1021. void Processor::deferred_call_queue(Function<void()> callback)
  1022. {
  1023. // NOTE: If we are called outside of a critical section and outside
  1024. // of an irq handler, the function will be executed before we return!
  1025. ScopedCritical critical;
  1026. auto& cur_proc = Processor::current();
  1027. auto* entry = cur_proc.deferred_call_get_free();
  1028. entry->handler_value() = move(callback);
  1029. cur_proc.deferred_call_queue_entry(entry);
  1030. }
  1031. UNMAP_AFTER_INIT void Processor::gdt_init()
  1032. {
  1033. m_gdt_length = 0;
  1034. m_gdtr.address = nullptr;
  1035. m_gdtr.limit = 0;
  1036. write_raw_gdt_entry(0x0000, 0x00000000, 0x00000000);
  1037. #if ARCH(I386)
  1038. write_raw_gdt_entry(GDT_SELECTOR_CODE0, 0x0000ffff, 0x00cf9a00); // code0
  1039. write_raw_gdt_entry(GDT_SELECTOR_DATA0, 0x0000ffff, 0x00cf9200); // data0
  1040. write_raw_gdt_entry(GDT_SELECTOR_CODE3, 0x0000ffff, 0x00cffa00); // code3
  1041. write_raw_gdt_entry(GDT_SELECTOR_DATA3, 0x0000ffff, 0x00cff200); // data3
  1042. #else
  1043. write_raw_gdt_entry(GDT_SELECTOR_CODE0, 0x0000ffff, 0x00af9a00); // code0
  1044. write_raw_gdt_entry(GDT_SELECTOR_DATA0, 0x0000ffff, 0x00af9200); // data0
  1045. write_raw_gdt_entry(GDT_SELECTOR_DATA3, 0x0000ffff, 0x008ff200); // data3
  1046. write_raw_gdt_entry(GDT_SELECTOR_CODE3, 0x0000ffff, 0x00affa00); // code3
  1047. #endif
  1048. #if ARCH(I386)
  1049. Descriptor tls_descriptor {};
  1050. tls_descriptor.low = tls_descriptor.high = 0;
  1051. tls_descriptor.dpl = 3;
  1052. tls_descriptor.segment_present = 1;
  1053. tls_descriptor.granularity = 0;
  1054. tls_descriptor.operation_size64 = 0;
  1055. tls_descriptor.operation_size32 = 1;
  1056. tls_descriptor.descriptor_type = 1;
  1057. tls_descriptor.type = 2;
  1058. write_gdt_entry(GDT_SELECTOR_TLS, tls_descriptor); // tls3
  1059. Descriptor gs_descriptor {};
  1060. gs_descriptor.set_base(VirtualAddress { this });
  1061. gs_descriptor.set_limit(sizeof(Processor) - 1);
  1062. gs_descriptor.dpl = 0;
  1063. gs_descriptor.segment_present = 1;
  1064. gs_descriptor.granularity = 0;
  1065. gs_descriptor.operation_size64 = 0;
  1066. gs_descriptor.operation_size32 = 1;
  1067. gs_descriptor.descriptor_type = 1;
  1068. gs_descriptor.type = 2;
  1069. write_gdt_entry(GDT_SELECTOR_PROC, gs_descriptor); // gs0
  1070. #endif
  1071. Descriptor tss_descriptor {};
  1072. tss_descriptor.set_base(VirtualAddress { (size_t)&m_tss & 0xffffffff });
  1073. tss_descriptor.set_limit(sizeof(TSS) - 1);
  1074. tss_descriptor.dpl = 0;
  1075. tss_descriptor.segment_present = 1;
  1076. tss_descriptor.granularity = 0;
  1077. tss_descriptor.operation_size64 = 0;
  1078. tss_descriptor.operation_size32 = 1;
  1079. tss_descriptor.descriptor_type = 0;
  1080. tss_descriptor.type = Descriptor::SystemType::AvailableTSS;
  1081. write_gdt_entry(GDT_SELECTOR_TSS, tss_descriptor); // tss
  1082. #if ARCH(X86_64)
  1083. Descriptor tss_descriptor_part2 {};
  1084. tss_descriptor_part2.low = (size_t)&m_tss >> 32;
  1085. write_gdt_entry(GDT_SELECTOR_TSS_PART2, tss_descriptor_part2);
  1086. #endif
  1087. flush_gdt();
  1088. load_task_register(GDT_SELECTOR_TSS);
  1089. #if ARCH(X86_64)
  1090. MSR gs_base(MSR_GS_BASE);
  1091. gs_base.set((u64)this);
  1092. #else
  1093. asm volatile(
  1094. "mov %%ax, %%ds\n"
  1095. "mov %%ax, %%es\n"
  1096. "mov %%ax, %%fs\n"
  1097. "mov %%ax, %%ss\n" ::"a"(GDT_SELECTOR_DATA0)
  1098. : "memory");
  1099. set_gs(GDT_SELECTOR_PROC);
  1100. #endif
  1101. #if ARCH(I386)
  1102. // Make sure CS points to the kernel code descriptor.
  1103. // clang-format off
  1104. asm volatile(
  1105. "ljmpl $" __STRINGIFY(GDT_SELECTOR_CODE0) ", $sanity\n"
  1106. "sanity:\n");
  1107. // clang-format on
  1108. #endif
  1109. }
  1110. extern "C" void context_first_init([[maybe_unused]] Thread* from_thread, [[maybe_unused]] Thread* to_thread, [[maybe_unused]] TrapFrame* trap)
  1111. {
  1112. VERIFY(!are_interrupts_enabled());
  1113. VERIFY(is_kernel_mode());
  1114. dbgln_if(CONTEXT_SWITCH_DEBUG, "switch_context <-- from {} {} to {} {} (context_first_init)", VirtualAddress(from_thread), *from_thread, VirtualAddress(to_thread), *to_thread);
  1115. VERIFY(to_thread == Thread::current());
  1116. Scheduler::enter_current(*from_thread);
  1117. auto in_critical = to_thread->saved_critical();
  1118. VERIFY(in_critical > 0);
  1119. Processor::restore_in_critical(in_critical);
  1120. // Since we got here and don't have Scheduler::context_switch in the
  1121. // call stack (because this is the first time we switched into this
  1122. // context), we need to notify the scheduler so that it can release
  1123. // the scheduler lock. We don't want to enable interrupts at this point
  1124. // as we're still in the middle of a context switch. Doing so could
  1125. // trigger a context switch within a context switch, leading to a crash.
  1126. FlatPtr flags = trap->regs->flags();
  1127. Scheduler::leave_on_first_switch(flags & ~0x200);
  1128. }
  1129. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
  1130. {
  1131. VERIFY(from_thread == to_thread || from_thread->state() != Thread::State::Running);
  1132. VERIFY(to_thread->state() == Thread::State::Running);
  1133. bool has_fxsr = Processor::current().has_feature(CPUFeature::FXSR);
  1134. Processor::set_current_thread(*to_thread);
  1135. auto& from_regs = from_thread->regs();
  1136. auto& to_regs = to_thread->regs();
  1137. // NOTE: IOPL should never be non-zero in any situation, so let's panic immediately
  1138. // instead of carrying on with elevated I/O privileges.
  1139. VERIFY(get_iopl_from_eflags(to_regs.flags()) == 0);
  1140. if (has_fxsr)
  1141. asm volatile("fxsave %0"
  1142. : "=m"(from_thread->fpu_state()));
  1143. else
  1144. asm volatile("fnsave %0"
  1145. : "=m"(from_thread->fpu_state()));
  1146. #if ARCH(I386)
  1147. from_regs.fs = get_fs();
  1148. from_regs.gs = get_gs();
  1149. set_fs(to_regs.fs);
  1150. set_gs(to_regs.gs);
  1151. #endif
  1152. if (from_thread->process().is_traced())
  1153. read_debug_registers_into(from_thread->debug_register_state());
  1154. if (to_thread->process().is_traced()) {
  1155. write_debug_registers_from(to_thread->debug_register_state());
  1156. } else {
  1157. clear_debug_registers();
  1158. }
  1159. auto& processor = Processor::current();
  1160. #if ARCH(I386)
  1161. auto& tls_descriptor = processor.get_gdt_entry(GDT_SELECTOR_TLS);
  1162. tls_descriptor.set_base(to_thread->thread_specific_data());
  1163. tls_descriptor.set_limit(to_thread->thread_specific_region_size());
  1164. #else
  1165. MSR fs_base_msr(MSR_FS_BASE);
  1166. fs_base_msr.set(to_thread->thread_specific_data().get());
  1167. #endif
  1168. if (from_regs.cr3 != to_regs.cr3)
  1169. write_cr3(to_regs.cr3);
  1170. to_thread->set_cpu(processor.id());
  1171. auto in_critical = to_thread->saved_critical();
  1172. VERIFY(in_critical > 0);
  1173. Processor::restore_in_critical(in_critical);
  1174. if (has_fxsr)
  1175. asm volatile("fxrstor %0" ::"m"(to_thread->fpu_state()));
  1176. else
  1177. asm volatile("frstor %0" ::"m"(to_thread->fpu_state()));
  1178. }
  1179. extern "C" FlatPtr do_init_context(Thread* thread, u32 flags)
  1180. {
  1181. VERIFY_INTERRUPTS_DISABLED();
  1182. thread->regs().set_flags(flags);
  1183. return Processor::current().init_context(*thread, true);
  1184. }
  1185. void Processor::assume_context(Thread& thread, FlatPtr flags)
  1186. {
  1187. dbgln_if(CONTEXT_SWITCH_DEBUG, "Assume context for thread {} {}", VirtualAddress(&thread), thread);
  1188. VERIFY_INTERRUPTS_DISABLED();
  1189. Scheduler::prepare_after_exec();
  1190. // in_critical() should be 2 here. The critical section in Process::exec
  1191. // and then the scheduler lock
  1192. VERIFY(Processor::in_critical() == 2);
  1193. do_assume_context(&thread, flags);
  1194. VERIFY_NOT_REACHED();
  1195. }
  1196. u64 Processor::time_spent_idle() const
  1197. {
  1198. return m_idle_thread->time_in_user() + m_idle_thread->time_in_kernel();
  1199. }
  1200. }