Processor.cpp 48 KB

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