Processor.cpp 45 KB

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