Processor.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  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. String Processor::features_string() const
  217. {
  218. StringBuilder builder;
  219. auto feature_to_str =
  220. [](CPUFeature f) -> const char* {
  221. switch (f) {
  222. case CPUFeature::NX:
  223. return "nx";
  224. case CPUFeature::PAE:
  225. return "pae";
  226. case CPUFeature::PGE:
  227. return "pge";
  228. case CPUFeature::RDRAND:
  229. return "rdrand";
  230. case CPUFeature::RDSEED:
  231. return "rdseed";
  232. case CPUFeature::SMAP:
  233. return "smap";
  234. case CPUFeature::SMEP:
  235. return "smep";
  236. case CPUFeature::SSE:
  237. return "sse";
  238. case CPUFeature::TSC:
  239. return "tsc";
  240. case CPUFeature::RDTSCP:
  241. return "rdtscp";
  242. case CPUFeature::CONSTANT_TSC:
  243. return "constant_tsc";
  244. case CPUFeature::NONSTOP_TSC:
  245. return "nonstop_tsc";
  246. case CPUFeature::UMIP:
  247. return "umip";
  248. case CPUFeature::SEP:
  249. return "sep";
  250. case CPUFeature::SYSCALL:
  251. return "syscall";
  252. case CPUFeature::MMX:
  253. return "mmx";
  254. case CPUFeature::FXSR:
  255. return "fxsr";
  256. case CPUFeature::SSE2:
  257. return "sse2";
  258. case CPUFeature::SSE3:
  259. return "sse3";
  260. case CPUFeature::SSSE3:
  261. return "ssse3";
  262. case CPUFeature::SSE4_1:
  263. return "sse4.1";
  264. case CPUFeature::SSE4_2:
  265. return "sse4.2";
  266. case CPUFeature::XSAVE:
  267. return "xsave";
  268. case CPUFeature::AVX:
  269. return "avx";
  270. case CPUFeature::LM:
  271. return "lm";
  272. case CPUFeature::HYPERVISOR:
  273. return "hypervisor";
  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 "???";
  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. builder.append(' ');
  287. auto str = feature_to_str(static_cast<CPUFeature>(flag));
  288. builder.append(str, strlen(str));
  289. }
  290. }
  291. return builder.build();
  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. while (i < prev_gdt_length) {
  398. m_gdt[i].low = 0;
  399. m_gdt[i].high = 0;
  400. i++;
  401. }
  402. }
  403. void Processor::write_gdt_entry(u16 selector, Descriptor& descriptor)
  404. {
  405. write_raw_gdt_entry(selector, descriptor.low, descriptor.high);
  406. }
  407. Descriptor& Processor::get_gdt_entry(u16 selector)
  408. {
  409. u16 i = (selector & 0xfffc) >> 3;
  410. return *(Descriptor*)(&m_gdt[i]);
  411. }
  412. void Processor::flush_gdt()
  413. {
  414. m_gdtr.address = m_gdt;
  415. m_gdtr.limit = (m_gdt_length * 8) - 1;
  416. asm volatile("lgdt %0" ::"m"(m_gdtr)
  417. : "memory");
  418. }
  419. const DescriptorTablePointer& Processor::get_gdtr()
  420. {
  421. return m_gdtr;
  422. }
  423. Vector<FlatPtr> Processor::capture_stack_trace(Thread& thread, size_t max_frames)
  424. {
  425. FlatPtr frame_ptr = 0, ip = 0;
  426. Vector<FlatPtr, 32> stack_trace;
  427. auto walk_stack = [&](FlatPtr stack_ptr) {
  428. static constexpr size_t max_stack_frames = 4096;
  429. bool is_walking_userspace_stack = false;
  430. stack_trace.append(ip);
  431. size_t count = 1;
  432. while (stack_ptr && stack_trace.size() < max_stack_frames) {
  433. FlatPtr retaddr;
  434. count++;
  435. if (max_frames != 0 && count > max_frames)
  436. break;
  437. if (!Memory::is_user_address(VirtualAddress { stack_ptr })) {
  438. if (is_walking_userspace_stack) {
  439. dbgln("SHENANIGANS! Userspace stack points back into kernel memory");
  440. break;
  441. }
  442. } else {
  443. is_walking_userspace_stack = true;
  444. }
  445. if (Memory::is_user_range(VirtualAddress(stack_ptr), sizeof(FlatPtr) * 2)) {
  446. if (copy_from_user(&retaddr, &((FlatPtr*)stack_ptr)[1]).is_error() || !retaddr)
  447. break;
  448. stack_trace.append(retaddr);
  449. if (copy_from_user(&stack_ptr, (FlatPtr*)stack_ptr).is_error())
  450. break;
  451. } else {
  452. void* fault_at;
  453. if (!safe_memcpy(&retaddr, &((FlatPtr*)stack_ptr)[1], sizeof(FlatPtr), fault_at) || !retaddr)
  454. break;
  455. stack_trace.append(retaddr);
  456. if (!safe_memcpy(&stack_ptr, (FlatPtr*)stack_ptr, sizeof(FlatPtr), fault_at))
  457. break;
  458. }
  459. }
  460. };
  461. auto capture_current_thread = [&]() {
  462. frame_ptr = (FlatPtr)__builtin_frame_address(0);
  463. ip = (FlatPtr)__builtin_return_address(0);
  464. walk_stack(frame_ptr);
  465. };
  466. // Since the thread may be running on another processor, there
  467. // is a chance a context switch may happen while we're trying
  468. // to get it. It also won't be entirely accurate and merely
  469. // reflect the status at the last context switch.
  470. SpinlockLocker lock(g_scheduler_lock);
  471. if (&thread == Processor::current_thread()) {
  472. VERIFY(thread.state() == Thread::Running);
  473. // Leave the scheduler lock. If we trigger page faults we may
  474. // need to be preempted. Since this is our own thread it won't
  475. // cause any problems as the stack won't change below this frame.
  476. lock.unlock();
  477. capture_current_thread();
  478. } else if (thread.is_active()) {
  479. VERIFY(thread.cpu() != Processor::current_id());
  480. // If this is the case, the thread is currently running
  481. // on another processor. We can't trust the kernel stack as
  482. // it may be changing at any time. We need to probably send
  483. // an IPI to that processor, have it walk the stack and wait
  484. // until it returns the data back to us
  485. auto& proc = Processor::current();
  486. smp_unicast(
  487. thread.cpu(),
  488. [&]() {
  489. dbgln("CPU[{}] getting stack for cpu #{}", Processor::current_id(), proc.id());
  490. ScopedAddressSpaceSwitcher switcher(thread.process());
  491. VERIFY(&Processor::current() != &proc);
  492. VERIFY(&thread == Processor::current_thread());
  493. // NOTE: Because the other processor is still holding the
  494. // scheduler lock while waiting for this callback to finish,
  495. // the current thread on the target processor cannot change
  496. // TODO: What to do about page faults here? We might deadlock
  497. // because the other processor is still holding the
  498. // scheduler lock...
  499. capture_current_thread();
  500. },
  501. false);
  502. } else {
  503. switch (thread.state()) {
  504. case Thread::Running:
  505. VERIFY_NOT_REACHED(); // should have been handled above
  506. case Thread::Runnable:
  507. case Thread::Stopped:
  508. case Thread::Blocked:
  509. case Thread::Dying:
  510. case Thread::Dead: {
  511. // We need to retrieve ebp from what was last pushed to the kernel
  512. // stack. Before switching out of that thread, it switch_context
  513. // pushed the callee-saved registers, and the last of them happens
  514. // to be ebp.
  515. ScopedAddressSpaceSwitcher switcher(thread.process());
  516. auto& regs = thread.regs();
  517. auto* stack_top = reinterpret_cast<FlatPtr*>(regs.sp());
  518. if (Memory::is_user_range(VirtualAddress(stack_top), sizeof(FlatPtr))) {
  519. if (copy_from_user(&frame_ptr, &((FlatPtr*)stack_top)[0]).is_error())
  520. frame_ptr = 0;
  521. } else {
  522. void* fault_at;
  523. if (!safe_memcpy(&frame_ptr, &((FlatPtr*)stack_top)[0], sizeof(FlatPtr), fault_at))
  524. frame_ptr = 0;
  525. }
  526. ip = regs.ip();
  527. // TODO: We need to leave the scheduler lock here, but we also
  528. // need to prevent the target thread from being run while
  529. // we walk the stack
  530. lock.unlock();
  531. walk_stack(frame_ptr);
  532. break;
  533. }
  534. default:
  535. dbgln("Cannot capture stack trace for thread {} in state {}", thread, thread.state_string());
  536. break;
  537. }
  538. }
  539. return stack_trace;
  540. }
  541. ProcessorContainer& Processor::processors()
  542. {
  543. return s_processors;
  544. }
  545. Processor& Processor::by_id(u32 id)
  546. {
  547. return *s_processors[id];
  548. }
  549. void Processor::enter_trap(TrapFrame& trap, bool raise_irq)
  550. {
  551. VERIFY_INTERRUPTS_DISABLED();
  552. VERIFY(&Processor::current() == this);
  553. trap.prev_irq_level = m_in_irq;
  554. if (raise_irq)
  555. m_in_irq++;
  556. auto* current_thread = Processor::current_thread();
  557. if (current_thread) {
  558. auto& current_trap = current_thread->current_trap();
  559. trap.next_trap = current_trap;
  560. current_trap = &trap;
  561. // The cs register of this trap tells us where we will return back to
  562. auto new_previous_mode = ((trap.regs->cs & 3) != 0) ? Thread::PreviousMode::UserMode : Thread::PreviousMode::KernelMode;
  563. if (current_thread->set_previous_mode(new_previous_mode) && trap.prev_irq_level == 0) {
  564. current_thread->update_time_scheduled(Scheduler::current_time(), new_previous_mode == Thread::PreviousMode::KernelMode, false);
  565. }
  566. } else {
  567. trap.next_trap = nullptr;
  568. }
  569. }
  570. void Processor::exit_trap(TrapFrame& trap)
  571. {
  572. VERIFY_INTERRUPTS_DISABLED();
  573. VERIFY(&Processor::current() == this);
  574. // Temporarily enter a critical section. This is to prevent critical
  575. // sections entered and left within e.g. smp_process_pending_messages
  576. // to trigger a context switch while we're executing this function
  577. // See the comment at the end of the function why we don't use
  578. // ScopedCritical here.
  579. m_in_critical = m_in_critical + 1;
  580. VERIFY(m_in_irq >= trap.prev_irq_level);
  581. m_in_irq = trap.prev_irq_level;
  582. if (s_smp_enabled)
  583. smp_process_pending_messages();
  584. // Process the deferred call queue. Among other things, this ensures
  585. // that any pending thread unblocks happen before we enter the scheduler.
  586. deferred_call_execute_pending();
  587. auto* current_thread = Processor::current_thread();
  588. if (current_thread) {
  589. auto& current_trap = current_thread->current_trap();
  590. current_trap = trap.next_trap;
  591. Thread::PreviousMode new_previous_mode;
  592. if (current_trap) {
  593. VERIFY(current_trap->regs);
  594. // If we have another higher level trap then we probably returned
  595. // from an interrupt or irq handler. The cs register of the
  596. // new/higher level trap tells us what the mode prior to it was
  597. new_previous_mode = ((current_trap->regs->cs & 3) != 0) ? Thread::PreviousMode::UserMode : Thread::PreviousMode::KernelMode;
  598. } else {
  599. // If we don't have a higher level trap then we're back in user mode.
  600. // Which means that the previous mode prior to being back in user mode was kernel mode
  601. new_previous_mode = Thread::PreviousMode::KernelMode;
  602. }
  603. if (current_thread->set_previous_mode(new_previous_mode))
  604. current_thread->update_time_scheduled(Scheduler::current_time(), true, false);
  605. }
  606. VERIFY_INTERRUPTS_DISABLED();
  607. // Leave the critical section without actually enabling interrupts.
  608. // We don't want context switches to happen until we're explicitly
  609. // triggering a switch in check_invoke_scheduler.
  610. m_in_critical = m_in_critical - 1;
  611. if (!m_in_irq && !m_in_critical)
  612. check_invoke_scheduler();
  613. }
  614. void Processor::check_invoke_scheduler()
  615. {
  616. InterruptDisabler disabler;
  617. VERIFY(!m_in_irq);
  618. VERIFY(!m_in_critical);
  619. VERIFY(&Processor::current() == this);
  620. if (m_invoke_scheduler_async && m_scheduler_initialized) {
  621. m_invoke_scheduler_async = false;
  622. Scheduler::invoke_async();
  623. }
  624. }
  625. void Processor::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  626. {
  627. auto ptr = vaddr.as_ptr();
  628. while (page_count > 0) {
  629. // clang-format off
  630. asm volatile("invlpg %0"
  631. :
  632. : "m"(*ptr)
  633. : "memory");
  634. // clang-format on
  635. ptr += PAGE_SIZE;
  636. page_count--;
  637. }
  638. }
  639. void Processor::flush_tlb(Memory::PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
  640. {
  641. if (s_smp_enabled && (!Memory::is_user_address(vaddr) || Process::current().thread_count() > 1))
  642. smp_broadcast_flush_tlb(page_directory, vaddr, page_count);
  643. else
  644. flush_tlb_local(vaddr, page_count);
  645. }
  646. void Processor::smp_return_to_pool(ProcessorMessage& msg)
  647. {
  648. ProcessorMessage* next = nullptr;
  649. for (;;) {
  650. msg.next = next;
  651. if (s_message_pool.compare_exchange_strong(next, &msg, AK::MemoryOrder::memory_order_acq_rel))
  652. break;
  653. Processor::pause();
  654. }
  655. }
  656. ProcessorMessage& Processor::smp_get_from_pool()
  657. {
  658. ProcessorMessage* msg;
  659. // The assumption is that messages are never removed from the pool!
  660. for (;;) {
  661. msg = s_message_pool.load(AK::MemoryOrder::memory_order_consume);
  662. if (!msg) {
  663. if (!Processor::current().smp_process_pending_messages()) {
  664. Processor::pause();
  665. }
  666. continue;
  667. }
  668. // If another processor were to use this message in the meanwhile,
  669. // "msg" is still valid (because it never gets freed). We'd detect
  670. // this because the expected value "msg" and pool would
  671. // no longer match, and the compare_exchange will fail. But accessing
  672. // "msg->next" is always safe here.
  673. if (s_message_pool.compare_exchange_strong(msg, msg->next, AK::MemoryOrder::memory_order_acq_rel)) {
  674. // We successfully "popped" this available message
  675. break;
  676. }
  677. }
  678. VERIFY(msg != nullptr);
  679. return *msg;
  680. }
  681. u32 Processor::smp_wake_n_idle_processors(u32 wake_count)
  682. {
  683. VERIFY_INTERRUPTS_DISABLED();
  684. VERIFY(wake_count > 0);
  685. if (!s_smp_enabled)
  686. return 0;
  687. // Wake at most N - 1 processors
  688. if (wake_count >= Processor::count()) {
  689. wake_count = Processor::count() - 1;
  690. VERIFY(wake_count > 0);
  691. }
  692. u32 current_id = Processor::current_id();
  693. u32 did_wake_count = 0;
  694. auto& apic = APIC::the();
  695. while (did_wake_count < wake_count) {
  696. // Try to get a set of idle CPUs and flip them to busy
  697. u32 idle_mask = s_idle_cpu_mask.load(AK::MemoryOrder::memory_order_relaxed) & ~(1u << current_id);
  698. u32 idle_count = popcount(idle_mask);
  699. if (idle_count == 0)
  700. break; // No (more) idle processor available
  701. u32 found_mask = 0;
  702. for (u32 i = 0; i < idle_count; i++) {
  703. u32 cpu = bit_scan_forward(idle_mask) - 1;
  704. idle_mask &= ~(1u << cpu);
  705. found_mask |= 1u << cpu;
  706. }
  707. idle_mask = s_idle_cpu_mask.fetch_and(~found_mask, AK::MemoryOrder::memory_order_acq_rel) & found_mask;
  708. if (idle_mask == 0)
  709. continue; // All of them were flipped to busy, try again
  710. idle_count = popcount(idle_mask);
  711. for (u32 i = 0; i < idle_count; i++) {
  712. u32 cpu = bit_scan_forward(idle_mask) - 1;
  713. idle_mask &= ~(1u << cpu);
  714. // Send an IPI to that CPU to wake it up. There is a possibility
  715. // someone else woke it up as well, or that it woke up due to
  716. // a timer interrupt. But we tried hard to avoid this...
  717. apic.send_ipi(cpu);
  718. did_wake_count++;
  719. }
  720. }
  721. return did_wake_count;
  722. }
  723. UNMAP_AFTER_INIT void Processor::smp_enable()
  724. {
  725. size_t msg_pool_size = Processor::count() * 100u;
  726. size_t msg_entries_cnt = Processor::count();
  727. auto msgs = new ProcessorMessage[msg_pool_size];
  728. auto msg_entries = new ProcessorMessageEntry[msg_pool_size * msg_entries_cnt];
  729. size_t msg_entry_i = 0;
  730. for (size_t i = 0; i < msg_pool_size; i++, msg_entry_i += msg_entries_cnt) {
  731. auto& msg = msgs[i];
  732. msg.next = i < msg_pool_size - 1 ? &msgs[i + 1] : nullptr;
  733. msg.per_proc_entries = &msg_entries[msg_entry_i];
  734. for (size_t k = 0; k < msg_entries_cnt; k++)
  735. msg_entries[msg_entry_i + k].msg = &msg;
  736. }
  737. s_message_pool.store(&msgs[0], AK::MemoryOrder::memory_order_release);
  738. // Start sending IPI messages
  739. s_smp_enabled = true;
  740. }
  741. void Processor::smp_cleanup_message(ProcessorMessage& msg)
  742. {
  743. switch (msg.type) {
  744. case ProcessorMessage::Callback:
  745. msg.callback_value().~Function();
  746. break;
  747. default:
  748. break;
  749. }
  750. }
  751. bool Processor::smp_process_pending_messages()
  752. {
  753. VERIFY(s_smp_enabled);
  754. bool did_process = false;
  755. enter_critical();
  756. if (auto pending_msgs = m_message_queue.exchange(nullptr, AK::MemoryOrder::memory_order_acq_rel)) {
  757. // We pulled the stack of pending messages in LIFO order, so we need to reverse the list first
  758. auto reverse_list =
  759. [](ProcessorMessageEntry* list) -> ProcessorMessageEntry* {
  760. ProcessorMessageEntry* rev_list = nullptr;
  761. while (list) {
  762. auto next = list->next;
  763. list->next = rev_list;
  764. rev_list = list;
  765. list = next;
  766. }
  767. return rev_list;
  768. };
  769. pending_msgs = reverse_list(pending_msgs);
  770. // now process in the right order
  771. ProcessorMessageEntry* next_msg;
  772. for (auto cur_msg = pending_msgs; cur_msg; cur_msg = next_msg) {
  773. next_msg = cur_msg->next;
  774. auto msg = cur_msg->msg;
  775. dbgln_if(SMP_DEBUG, "SMP[{}]: Processing message {}", current_id(), VirtualAddress(msg));
  776. switch (msg->type) {
  777. case ProcessorMessage::Callback:
  778. msg->invoke_callback();
  779. break;
  780. case ProcessorMessage::FlushTlb:
  781. if (Memory::is_user_address(VirtualAddress(msg->flush_tlb.ptr))) {
  782. // We assume that we don't cross into kernel land!
  783. VERIFY(Memory::is_user_range(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count * PAGE_SIZE));
  784. if (read_cr3() != msg->flush_tlb.page_directory->cr3()) {
  785. // This processor isn't using this page directory right now, we can ignore this request
  786. dbgln_if(SMP_DEBUG, "SMP[{}]: No need to flush {} pages at {}", current_id(), msg->flush_tlb.page_count, VirtualAddress(msg->flush_tlb.ptr));
  787. break;
  788. }
  789. }
  790. flush_tlb_local(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count);
  791. break;
  792. }
  793. bool is_async = msg->async; // Need to cache this value *before* dropping the ref count!
  794. auto prev_refs = msg->refs.fetch_sub(1u, AK::MemoryOrder::memory_order_acq_rel);
  795. VERIFY(prev_refs != 0);
  796. if (prev_refs == 1) {
  797. // All processors handled this. If this is an async message,
  798. // we need to clean it up and return it to the pool
  799. if (is_async) {
  800. smp_cleanup_message(*msg);
  801. smp_return_to_pool(*msg);
  802. }
  803. }
  804. if (m_halt_requested.load(AK::MemoryOrder::memory_order_relaxed))
  805. halt_this();
  806. }
  807. did_process = true;
  808. } else if (m_halt_requested.load(AK::MemoryOrder::memory_order_relaxed)) {
  809. halt_this();
  810. }
  811. leave_critical();
  812. return did_process;
  813. }
  814. bool Processor::smp_enqueue_message(ProcessorMessage& msg)
  815. {
  816. // Note that it's quite possible that the other processor may pop
  817. // the queue at any given time. We rely on the fact that the messages
  818. // are pooled and never get freed!
  819. auto& msg_entry = msg.per_proc_entries[id()];
  820. VERIFY(msg_entry.msg == &msg);
  821. ProcessorMessageEntry* next = nullptr;
  822. for (;;) {
  823. msg_entry.next = next;
  824. if (m_message_queue.compare_exchange_strong(next, &msg_entry, AK::MemoryOrder::memory_order_acq_rel))
  825. break;
  826. Processor::pause();
  827. }
  828. // If the enqueued message was the only message in the queue when posted,
  829. // we return true. This is used by callers when deciding whether to generate an IPI.
  830. return next == nullptr;
  831. }
  832. void Processor::smp_broadcast_message(ProcessorMessage& msg)
  833. {
  834. auto& current_processor = Processor::current();
  835. dbgln_if(SMP_DEBUG, "SMP[{}]: Broadcast message {} to cpus: {} processor: {}", current_processor.id(), VirtualAddress(&msg), count(), VirtualAddress(&current_processor));
  836. msg.refs.store(count() - 1, AK::MemoryOrder::memory_order_release);
  837. VERIFY(msg.refs > 0);
  838. bool need_broadcast = false;
  839. for_each(
  840. [&](Processor& proc) {
  841. if (&proc != &current_processor) {
  842. if (proc.smp_enqueue_message(msg))
  843. need_broadcast = true;
  844. }
  845. });
  846. // Now trigger an IPI on all other APs (unless all targets already had messages queued)
  847. if (need_broadcast)
  848. APIC::the().broadcast_ipi();
  849. }
  850. void Processor::smp_broadcast_wait_sync(ProcessorMessage& msg)
  851. {
  852. auto& cur_proc = Processor::current();
  853. VERIFY(!msg.async);
  854. // If synchronous then we must cleanup and return the message back
  855. // to the pool. Otherwise, the last processor to complete it will return it
  856. while (msg.refs.load(AK::MemoryOrder::memory_order_consume) != 0) {
  857. Processor::pause();
  858. // We need to process any messages that may have been sent to
  859. // us while we're waiting. This also checks if another processor
  860. // may have requested us to halt.
  861. cur_proc.smp_process_pending_messages();
  862. }
  863. smp_cleanup_message(msg);
  864. smp_return_to_pool(msg);
  865. }
  866. void Processor::smp_unicast_message(u32 cpu, ProcessorMessage& msg, bool async)
  867. {
  868. auto& current_processor = Processor::current();
  869. VERIFY(cpu != current_processor.id());
  870. auto& target_processor = processors()[cpu];
  871. msg.async = async;
  872. dbgln_if(SMP_DEBUG, "SMP[{}]: Send message {} to cpu #{} processor: {}", current_processor.id(), VirtualAddress(&msg), cpu, VirtualAddress(&target_processor));
  873. msg.refs.store(1u, AK::MemoryOrder::memory_order_release);
  874. if (target_processor->smp_enqueue_message(msg)) {
  875. APIC::the().send_ipi(cpu);
  876. }
  877. if (!async) {
  878. // If synchronous then we must cleanup and return the message back
  879. // to the pool. Otherwise, the last processor to complete it will return it
  880. while (msg.refs.load(AK::MemoryOrder::memory_order_consume) != 0) {
  881. Processor::pause();
  882. // We need to process any messages that may have been sent to
  883. // us while we're waiting. This also checks if another processor
  884. // may have requested us to halt.
  885. current_processor.smp_process_pending_messages();
  886. }
  887. smp_cleanup_message(msg);
  888. smp_return_to_pool(msg);
  889. }
  890. }
  891. void Processor::smp_unicast(u32 cpu, Function<void()> callback, bool async)
  892. {
  893. auto& msg = smp_get_from_pool();
  894. msg.type = ProcessorMessage::Callback;
  895. new (msg.callback_storage) ProcessorMessage::CallbackFunction(move(callback));
  896. smp_unicast_message(cpu, msg, async);
  897. }
  898. void Processor::smp_broadcast_flush_tlb(Memory::PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
  899. {
  900. auto& msg = smp_get_from_pool();
  901. msg.async = false;
  902. msg.type = ProcessorMessage::FlushTlb;
  903. msg.flush_tlb.page_directory = page_directory;
  904. msg.flush_tlb.ptr = vaddr.as_ptr();
  905. msg.flush_tlb.page_count = page_count;
  906. smp_broadcast_message(msg);
  907. // While the other processors handle this request, we'll flush ours
  908. flush_tlb_local(vaddr, page_count);
  909. // Now wait until everybody is done as well
  910. smp_broadcast_wait_sync(msg);
  911. }
  912. void Processor::smp_broadcast_halt()
  913. {
  914. // We don't want to use a message, because this could have been triggered
  915. // by being out of memory and we might not be able to get a message
  916. for_each(
  917. [&](Processor& proc) {
  918. proc.m_halt_requested.store(true, AK::MemoryOrder::memory_order_release);
  919. });
  920. // Now trigger an IPI on all other APs
  921. APIC::the().broadcast_ipi();
  922. }
  923. void Processor::Processor::halt()
  924. {
  925. if (s_smp_enabled)
  926. smp_broadcast_halt();
  927. halt_this();
  928. }
  929. UNMAP_AFTER_INIT void Processor::deferred_call_pool_init()
  930. {
  931. size_t pool_count = sizeof(m_deferred_call_pool) / sizeof(m_deferred_call_pool[0]);
  932. for (size_t i = 0; i < pool_count; i++) {
  933. auto& entry = m_deferred_call_pool[i];
  934. entry.next = i < pool_count - 1 ? &m_deferred_call_pool[i + 1] : nullptr;
  935. new (entry.handler_storage) DeferredCallEntry::HandlerFunction;
  936. entry.was_allocated = false;
  937. }
  938. m_pending_deferred_calls = nullptr;
  939. m_free_deferred_call_pool_entry = &m_deferred_call_pool[0];
  940. }
  941. void Processor::deferred_call_return_to_pool(DeferredCallEntry* entry)
  942. {
  943. VERIFY(m_in_critical);
  944. VERIFY(!entry->was_allocated);
  945. entry->handler_value() = {};
  946. entry->next = m_free_deferred_call_pool_entry;
  947. m_free_deferred_call_pool_entry = entry;
  948. }
  949. DeferredCallEntry* Processor::deferred_call_get_free()
  950. {
  951. VERIFY(m_in_critical);
  952. if (m_free_deferred_call_pool_entry) {
  953. // Fast path, we have an entry in our pool
  954. auto* entry = m_free_deferred_call_pool_entry;
  955. m_free_deferred_call_pool_entry = entry->next;
  956. VERIFY(!entry->was_allocated);
  957. return entry;
  958. }
  959. auto* entry = new DeferredCallEntry;
  960. new (entry->handler_storage) DeferredCallEntry::HandlerFunction;
  961. entry->was_allocated = true;
  962. return entry;
  963. }
  964. void Processor::deferred_call_execute_pending()
  965. {
  966. VERIFY(m_in_critical);
  967. if (!m_pending_deferred_calls)
  968. return;
  969. auto* pending_list = m_pending_deferred_calls;
  970. m_pending_deferred_calls = nullptr;
  971. // We pulled the stack of pending deferred calls in LIFO order, so we need to reverse the list first
  972. auto reverse_list =
  973. [](DeferredCallEntry* list) -> DeferredCallEntry* {
  974. DeferredCallEntry* rev_list = nullptr;
  975. while (list) {
  976. auto next = list->next;
  977. list->next = rev_list;
  978. rev_list = list;
  979. list = next;
  980. }
  981. return rev_list;
  982. };
  983. pending_list = reverse_list(pending_list);
  984. do {
  985. pending_list->invoke_handler();
  986. // Return the entry back to the pool, or free it
  987. auto* next = pending_list->next;
  988. if (pending_list->was_allocated) {
  989. pending_list->handler_value().~Function();
  990. delete pending_list;
  991. } else
  992. deferred_call_return_to_pool(pending_list);
  993. pending_list = next;
  994. } while (pending_list);
  995. }
  996. void Processor::deferred_call_queue_entry(DeferredCallEntry* entry)
  997. {
  998. VERIFY(m_in_critical);
  999. entry->next = m_pending_deferred_calls;
  1000. m_pending_deferred_calls = entry;
  1001. }
  1002. void Processor::deferred_call_queue(Function<void()> callback)
  1003. {
  1004. // NOTE: If we are called outside of a critical section and outside
  1005. // of an irq handler, the function will be executed before we return!
  1006. ScopedCritical critical;
  1007. auto& cur_proc = Processor::current();
  1008. auto* entry = cur_proc.deferred_call_get_free();
  1009. entry->handler_value() = move(callback);
  1010. cur_proc.deferred_call_queue_entry(entry);
  1011. }
  1012. UNMAP_AFTER_INIT void Processor::gdt_init()
  1013. {
  1014. m_gdt_length = 0;
  1015. m_gdtr.address = nullptr;
  1016. m_gdtr.limit = 0;
  1017. write_raw_gdt_entry(0x0000, 0x00000000, 0x00000000);
  1018. #if ARCH(I386)
  1019. write_raw_gdt_entry(GDT_SELECTOR_CODE0, 0x0000ffff, 0x00cf9a00); // code0
  1020. write_raw_gdt_entry(GDT_SELECTOR_DATA0, 0x0000ffff, 0x00cf9200); // data0
  1021. write_raw_gdt_entry(GDT_SELECTOR_CODE3, 0x0000ffff, 0x00cffa00); // code3
  1022. write_raw_gdt_entry(GDT_SELECTOR_DATA3, 0x0000ffff, 0x00cff200); // data3
  1023. #else
  1024. write_raw_gdt_entry(GDT_SELECTOR_CODE0, 0x0000ffff, 0x00af9a00); // code0
  1025. write_raw_gdt_entry(GDT_SELECTOR_DATA0, 0x0000ffff, 0x00af9200); // data0
  1026. write_raw_gdt_entry(GDT_SELECTOR_DATA3, 0x0000ffff, 0x008ff200); // data3
  1027. write_raw_gdt_entry(GDT_SELECTOR_CODE3, 0x0000ffff, 0x00affa00); // code3
  1028. #endif
  1029. #if ARCH(I386)
  1030. Descriptor tls_descriptor {};
  1031. tls_descriptor.low = tls_descriptor.high = 0;
  1032. tls_descriptor.dpl = 3;
  1033. tls_descriptor.segment_present = 1;
  1034. tls_descriptor.granularity = 0;
  1035. tls_descriptor.operation_size64 = 0;
  1036. tls_descriptor.operation_size32 = 1;
  1037. tls_descriptor.descriptor_type = 1;
  1038. tls_descriptor.type = 2;
  1039. write_gdt_entry(GDT_SELECTOR_TLS, tls_descriptor); // tls3
  1040. Descriptor gs_descriptor {};
  1041. gs_descriptor.set_base(VirtualAddress { this });
  1042. gs_descriptor.set_limit(sizeof(Processor) - 1);
  1043. gs_descriptor.dpl = 0;
  1044. gs_descriptor.segment_present = 1;
  1045. gs_descriptor.granularity = 0;
  1046. gs_descriptor.operation_size64 = 0;
  1047. gs_descriptor.operation_size32 = 1;
  1048. gs_descriptor.descriptor_type = 1;
  1049. gs_descriptor.type = 2;
  1050. write_gdt_entry(GDT_SELECTOR_PROC, gs_descriptor); // gs0
  1051. #endif
  1052. Descriptor tss_descriptor {};
  1053. tss_descriptor.set_base(VirtualAddress { (size_t)&m_tss & 0xffffffff });
  1054. tss_descriptor.set_limit(sizeof(TSS) - 1);
  1055. tss_descriptor.dpl = 0;
  1056. tss_descriptor.segment_present = 1;
  1057. tss_descriptor.granularity = 0;
  1058. tss_descriptor.operation_size64 = 0;
  1059. tss_descriptor.operation_size32 = 1;
  1060. tss_descriptor.descriptor_type = 0;
  1061. tss_descriptor.type = 9;
  1062. write_gdt_entry(GDT_SELECTOR_TSS, tss_descriptor); // tss
  1063. #if ARCH(X86_64)
  1064. Descriptor tss_descriptor_part2 {};
  1065. tss_descriptor_part2.low = (size_t)&m_tss >> 32;
  1066. write_gdt_entry(GDT_SELECTOR_TSS_PART2, tss_descriptor_part2);
  1067. #endif
  1068. flush_gdt();
  1069. load_task_register(GDT_SELECTOR_TSS);
  1070. #if ARCH(X86_64)
  1071. MSR gs_base(MSR_GS_BASE);
  1072. gs_base.set((u64)this);
  1073. #else
  1074. asm volatile(
  1075. "mov %%ax, %%ds\n"
  1076. "mov %%ax, %%es\n"
  1077. "mov %%ax, %%fs\n"
  1078. "mov %%ax, %%ss\n" ::"a"(GDT_SELECTOR_DATA0)
  1079. : "memory");
  1080. set_gs(GDT_SELECTOR_PROC);
  1081. #endif
  1082. #if ARCH(I386)
  1083. // Make sure CS points to the kernel code descriptor.
  1084. // clang-format off
  1085. asm volatile(
  1086. "ljmpl $" __STRINGIFY(GDT_SELECTOR_CODE0) ", $sanity\n"
  1087. "sanity:\n");
  1088. // clang-format on
  1089. #endif
  1090. }
  1091. extern "C" void context_first_init([[maybe_unused]] Thread* from_thread, [[maybe_unused]] Thread* to_thread, [[maybe_unused]] TrapFrame* trap)
  1092. {
  1093. VERIFY(!are_interrupts_enabled());
  1094. VERIFY(is_kernel_mode());
  1095. dbgln_if(CONTEXT_SWITCH_DEBUG, "switch_context <-- from {} {} to {} {} (context_first_init)", VirtualAddress(from_thread), *from_thread, VirtualAddress(to_thread), *to_thread);
  1096. VERIFY(to_thread == Thread::current());
  1097. Scheduler::enter_current(*from_thread, true);
  1098. auto in_critical = to_thread->saved_critical();
  1099. VERIFY(in_critical > 0);
  1100. Processor::restore_in_critical(in_critical);
  1101. // Since we got here and don't have Scheduler::context_switch in the
  1102. // call stack (because this is the first time we switched into this
  1103. // context), we need to notify the scheduler so that it can release
  1104. // the scheduler lock. We don't want to enable interrupts at this point
  1105. // as we're still in the middle of a context switch. Doing so could
  1106. // trigger a context switch within a context switch, leading to a crash.
  1107. FlatPtr flags = trap->regs->flags();
  1108. Scheduler::leave_on_first_switch(flags & ~0x200);
  1109. }
  1110. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
  1111. {
  1112. VERIFY(from_thread == to_thread || from_thread->state() != Thread::Running);
  1113. VERIFY(to_thread->state() == Thread::Running);
  1114. bool has_fxsr = Processor::current().has_feature(CPUFeature::FXSR);
  1115. Processor::set_current_thread(*to_thread);
  1116. auto& from_regs = from_thread->regs();
  1117. auto& to_regs = to_thread->regs();
  1118. if (has_fxsr)
  1119. asm volatile("fxsave %0"
  1120. : "=m"(from_thread->fpu_state()));
  1121. else
  1122. asm volatile("fnsave %0"
  1123. : "=m"(from_thread->fpu_state()));
  1124. #if ARCH(I386)
  1125. from_regs.fs = get_fs();
  1126. from_regs.gs = get_gs();
  1127. set_fs(to_regs.fs);
  1128. set_gs(to_regs.gs);
  1129. #endif
  1130. if (from_thread->process().is_traced())
  1131. read_debug_registers_into(from_thread->debug_register_state());
  1132. if (to_thread->process().is_traced()) {
  1133. write_debug_registers_from(to_thread->debug_register_state());
  1134. } else {
  1135. clear_debug_registers();
  1136. }
  1137. auto& processor = Processor::current();
  1138. #if ARCH(I386)
  1139. auto& tls_descriptor = processor.get_gdt_entry(GDT_SELECTOR_TLS);
  1140. tls_descriptor.set_base(to_thread->thread_specific_data());
  1141. tls_descriptor.set_limit(to_thread->thread_specific_region_size());
  1142. #else
  1143. MSR fs_base_msr(MSR_FS_BASE);
  1144. fs_base_msr.set(to_thread->thread_specific_data().get());
  1145. #endif
  1146. if (from_regs.cr3 != to_regs.cr3)
  1147. write_cr3(to_regs.cr3);
  1148. to_thread->set_cpu(processor.id());
  1149. auto in_critical = to_thread->saved_critical();
  1150. VERIFY(in_critical > 0);
  1151. Processor::restore_in_critical(in_critical);
  1152. if (has_fxsr)
  1153. asm volatile("fxrstor %0" ::"m"(to_thread->fpu_state()));
  1154. else
  1155. asm volatile("frstor %0" ::"m"(to_thread->fpu_state()));
  1156. // TODO: ioperm?
  1157. }
  1158. extern "C" FlatPtr do_init_context(Thread* thread, u32 flags)
  1159. {
  1160. VERIFY_INTERRUPTS_DISABLED();
  1161. thread->regs().set_flags(flags);
  1162. return Processor::current().init_context(*thread, true);
  1163. }
  1164. void Processor::assume_context(Thread& thread, FlatPtr flags)
  1165. {
  1166. dbgln_if(CONTEXT_SWITCH_DEBUG, "Assume context for thread {} {}", VirtualAddress(&thread), thread);
  1167. VERIFY_INTERRUPTS_DISABLED();
  1168. Scheduler::prepare_after_exec();
  1169. // in_critical() should be 2 here. The critical section in Process::exec
  1170. // and then the scheduler lock
  1171. VERIFY(Processor::in_critical() == 2);
  1172. do_assume_context(&thread, flags);
  1173. VERIFY_NOT_REACHED();
  1174. }
  1175. u64 Processor::time_spent_idle() const
  1176. {
  1177. return m_idle_thread->time_in_user() + m_idle_thread->time_in_kernel();
  1178. }
  1179. }