Processor.cpp 38 KB

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