Processor.cpp 47 KB

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