Processor.cpp 43 KB

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