Processor.cpp 45 KB

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