Processor.cpp 44 KB

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