Processor.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/BuiltinWrappers.h>
  9. #include <AK/Format.h>
  10. #include <AK/StdLibExtras.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Types.h>
  13. #include <Kernel/Interrupts/APIC.h>
  14. #include <Kernel/Process.h>
  15. #include <Kernel/Scheduler.h>
  16. #include <Kernel/Sections.h>
  17. #include <Kernel/StdLib.h>
  18. #include <Kernel/Thread.h>
  19. #include <Kernel/Arch/Processor.h>
  20. #include <Kernel/Arch/ScopedCritical.h>
  21. #include <Kernel/Arch/x86/CPUID.h>
  22. #include <Kernel/Arch/x86/InterruptDisabler.h>
  23. #include <Kernel/Arch/x86/Interrupts.h>
  24. #include <Kernel/Arch/x86/MSR.h>
  25. #include <Kernel/Arch/x86/ProcessorInfo.h>
  26. #include <Kernel/Arch/x86/SafeMem.h>
  27. #include <Kernel/Arch/x86/TrapFrame.h>
  28. #include <Kernel/Memory/PageDirectory.h>
  29. #include <Kernel/Memory/ScopedAddressSpaceSwitcher.h>
  30. namespace Kernel {
  31. READONLY_AFTER_INIT FPUState Processor::s_clean_fpu_state;
  32. READONLY_AFTER_INIT static ProcessorContainer s_processors {};
  33. READONLY_AFTER_INIT Atomic<u32> Processor::g_total_processors;
  34. READONLY_AFTER_INIT static volatile bool s_smp_enabled;
  35. static Atomic<ProcessorMessage*> s_message_pool;
  36. Atomic<u32> Processor::s_idle_cpu_mask { 0 };
  37. // The compiler can't see the calls to these functions inside assembly.
  38. // Declare them, to avoid dead code warnings.
  39. extern "C" void context_first_init(Thread* from_thread, Thread* to_thread, TrapFrame* trap) __attribute__((used));
  40. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread) __attribute__((used));
  41. extern "C" FlatPtr do_init_context(Thread* thread, u32 flags) __attribute__((used));
  42. extern "C" void syscall_entry();
  43. bool Processor::is_smp_enabled()
  44. {
  45. return s_smp_enabled;
  46. }
  47. UNMAP_AFTER_INIT static void sse_init()
  48. {
  49. write_cr0((read_cr0() & 0xfffffffbu) | 0x2);
  50. write_cr4(read_cr4() | 0x600);
  51. }
  52. void exit_kernel_thread(void)
  53. {
  54. Thread::current()->exit();
  55. }
  56. UNMAP_AFTER_INIT void Processor::cpu_detect()
  57. {
  58. // NOTE: This is called during Processor::early_initialize, we cannot
  59. // safely log at this point because we don't have kmalloc
  60. // initialized yet!
  61. m_features = CPUFeature::Type(0u);
  62. CPUID processor_info(0x1);
  63. auto handle_edx_bit_11_feature = [&] {
  64. u32 stepping = processor_info.eax() & 0xf;
  65. u32 model = (processor_info.eax() >> 4) & 0xf;
  66. u32 family = (processor_info.eax() >> 8) & 0xf;
  67. // FIXME: I have no clue what these mean or where it's from (the Intel manual I've seen just says EDX[11] is SEP).
  68. // If you do, please convert them to constants or add comments!
  69. if (!(family == 6 && model < 3 && stepping < 3))
  70. m_features |= CPUFeature::SEP;
  71. if ((family == 6 && model >= 3) || (family == 0xf && model >= 0xe))
  72. m_features |= CPUFeature::CONSTANT_TSC;
  73. };
  74. if (processor_info.ecx() & (1 << 0))
  75. m_features |= CPUFeature::SSE3;
  76. if (processor_info.ecx() & (1 << 1))
  77. m_features |= CPUFeature::PCLMULQDQ;
  78. if (processor_info.ecx() & (1 << 2))
  79. m_features |= CPUFeature::DTES64;
  80. if (processor_info.ecx() & (1 << 3))
  81. m_features |= CPUFeature::MONITOR;
  82. if (processor_info.ecx() & (1 << 4))
  83. m_features |= CPUFeature::DS_CPL;
  84. if (processor_info.ecx() & (1 << 5))
  85. m_features |= CPUFeature::VMX;
  86. if (processor_info.ecx() & (1 << 6))
  87. m_features |= CPUFeature::SMX;
  88. if (processor_info.ecx() & (1 << 7))
  89. m_features |= CPUFeature::EST;
  90. if (processor_info.ecx() & (1 << 8))
  91. m_features |= CPUFeature::TM2;
  92. if (processor_info.ecx() & (1 << 9))
  93. m_features |= CPUFeature::SSSE3;
  94. if (processor_info.ecx() & (1 << 10))
  95. m_features |= CPUFeature::CNXT_ID;
  96. if (processor_info.ecx() & (1 << 11))
  97. m_features |= CPUFeature::SDBG;
  98. if (processor_info.ecx() & (1 << 12))
  99. m_features |= CPUFeature::FMA;
  100. if (processor_info.ecx() & (1 << 13))
  101. m_features |= CPUFeature::CX16;
  102. if (processor_info.ecx() & (1 << 14))
  103. m_features |= CPUFeature::XTPR;
  104. if (processor_info.ecx() & (1 << 15))
  105. m_features |= CPUFeature::PDCM;
  106. if (processor_info.ecx() & (1 << 17))
  107. m_features |= CPUFeature::PCID;
  108. if (processor_info.ecx() & (1 << 18))
  109. m_features |= CPUFeature::DCA;
  110. if (processor_info.ecx() & (1 << 19))
  111. m_features |= CPUFeature::SSE4_1;
  112. if (processor_info.ecx() & (1 << 20))
  113. m_features |= CPUFeature::SSE4_2;
  114. if (processor_info.ecx() & (1 << 21))
  115. m_features |= CPUFeature::X2APIC;
  116. if (processor_info.ecx() & (1 << 22))
  117. m_features |= CPUFeature::MOVBE;
  118. if (processor_info.ecx() & (1 << 23))
  119. m_features |= CPUFeature::POPCNT;
  120. if (processor_info.ecx() & (1 << 24))
  121. m_features |= CPUFeature::TSC_DEADLINE;
  122. if (processor_info.ecx() & (1 << 25))
  123. m_features |= CPUFeature::AES;
  124. if (processor_info.ecx() & (1 << 26))
  125. m_features |= CPUFeature::XSAVE;
  126. if (processor_info.ecx() & (1 << 27))
  127. m_features |= CPUFeature::OSXSAVE;
  128. if (processor_info.ecx() & (1 << 28))
  129. m_features |= CPUFeature::AVX;
  130. if (processor_info.ecx() & (1 << 29))
  131. m_features |= CPUFeature::F16C;
  132. if (processor_info.ecx() & (1 << 30))
  133. m_features |= CPUFeature::RDRAND;
  134. if (processor_info.ecx() & (1 << 31))
  135. m_features |= CPUFeature::HYPERVISOR;
  136. if (processor_info.edx() & (1 << 0))
  137. m_features |= CPUFeature::FPU;
  138. if (processor_info.edx() & (1 << 1))
  139. m_features |= CPUFeature::VME;
  140. if (processor_info.edx() & (1 << 2))
  141. m_features |= CPUFeature::DE;
  142. if (processor_info.edx() & (1 << 3))
  143. m_features |= CPUFeature::PSE;
  144. if (processor_info.edx() & (1 << 4))
  145. m_features |= CPUFeature::TSC;
  146. if (processor_info.edx() & (1 << 5))
  147. m_features |= CPUFeature::MSR;
  148. if (processor_info.edx() & (1 << 6))
  149. m_features |= CPUFeature::PAE;
  150. if (processor_info.edx() & (1 << 7))
  151. m_features |= CPUFeature::MCE;
  152. if (processor_info.edx() & (1 << 8))
  153. m_features |= CPUFeature::CX8;
  154. if (processor_info.edx() & (1 << 9))
  155. m_features |= CPUFeature::APIC;
  156. if (processor_info.edx() & (1 << 11))
  157. handle_edx_bit_11_feature();
  158. if (processor_info.edx() & (1 << 12))
  159. m_features |= CPUFeature::MTRR;
  160. if (processor_info.edx() & (1 << 13))
  161. m_features |= CPUFeature::PGE;
  162. if (processor_info.edx() & (1 << 14))
  163. m_features |= CPUFeature::MCA;
  164. if (processor_info.edx() & (1 << 15))
  165. m_features |= CPUFeature::CMOV;
  166. if (processor_info.edx() & (1 << 16))
  167. m_features |= CPUFeature::PAT;
  168. if (processor_info.edx() & (1 << 17))
  169. m_features |= CPUFeature::PSE36;
  170. if (processor_info.edx() & (1 << 18))
  171. m_features |= CPUFeature::PSN;
  172. if (processor_info.edx() & (1 << 19))
  173. m_features |= CPUFeature::CLFLUSH;
  174. if (processor_info.edx() & (1 << 21))
  175. m_features |= CPUFeature::DS;
  176. if (processor_info.edx() & (1 << 22))
  177. m_features |= CPUFeature::ACPI;
  178. if (processor_info.edx() & (1 << 23))
  179. m_features |= CPUFeature::MMX;
  180. if (processor_info.edx() & (1 << 24))
  181. m_features |= CPUFeature::FXSR;
  182. if (processor_info.edx() & (1 << 25))
  183. m_features |= CPUFeature::SSE;
  184. if (processor_info.edx() & (1 << 26))
  185. m_features |= CPUFeature::SSE2;
  186. if (processor_info.edx() & (1 << 27))
  187. m_features |= CPUFeature::SS;
  188. if (processor_info.edx() & (1 << 28))
  189. m_features |= CPUFeature::HTT;
  190. if (processor_info.edx() & (1 << 29))
  191. m_features |= CPUFeature::TM;
  192. if (processor_info.edx() & (1 << 30))
  193. m_features |= CPUFeature::IA64;
  194. if (processor_info.edx() & (1 << 31))
  195. m_features |= CPUFeature::PBE;
  196. CPUID extended_features(0x7);
  197. if (extended_features.ebx() & (1 << 0))
  198. m_features |= CPUFeature::FSGSBASE;
  199. if (extended_features.ebx() & (1 << 1))
  200. m_features |= CPUFeature::TSC_ADJUST;
  201. if (extended_features.ebx() & (1 << 2))
  202. m_features |= CPUFeature::SGX;
  203. if (extended_features.ebx() & (1 << 3))
  204. m_features |= CPUFeature::BMI1;
  205. if (extended_features.ebx() & (1 << 4))
  206. m_features |= CPUFeature::HLE;
  207. if (extended_features.ebx() & (1 << 5))
  208. m_features |= CPUFeature::AVX2;
  209. if (extended_features.ebx() & (1 << 6))
  210. m_features |= CPUFeature::FDP_EXCPTN_ONLY;
  211. if (extended_features.ebx() & (1 << 7))
  212. m_features |= CPUFeature::SMEP;
  213. if (extended_features.ebx() & (1 << 8))
  214. m_features |= CPUFeature::BMI2;
  215. if (extended_features.ebx() & (1 << 9))
  216. m_features |= CPUFeature::ERMS;
  217. if (extended_features.ebx() & (1 << 10))
  218. m_features |= CPUFeature::INVPCID;
  219. if (extended_features.ebx() & (1 << 11))
  220. m_features |= CPUFeature::RTM;
  221. if (extended_features.ebx() & (1 << 12))
  222. m_features |= CPUFeature::PQM;
  223. if (extended_features.ebx() & (1 << 13))
  224. m_features |= CPUFeature::ZERO_FCS_FDS;
  225. if (extended_features.ebx() & (1 << 14))
  226. m_features |= CPUFeature::MPX;
  227. if (extended_features.ebx() & (1 << 15))
  228. m_features |= CPUFeature::PQE;
  229. if (extended_features.ebx() & (1 << 16))
  230. m_features |= CPUFeature::AVX512_F;
  231. if (extended_features.ebx() & (1 << 17))
  232. m_features |= CPUFeature::AVX512_DQ;
  233. if (extended_features.ebx() & (1 << 18))
  234. m_features |= CPUFeature::RDSEED;
  235. if (extended_features.ebx() & (1 << 19))
  236. m_features |= CPUFeature::ADX;
  237. if (extended_features.ebx() & (1 << 20))
  238. m_features |= CPUFeature::SMAP;
  239. if (extended_features.ebx() & (1 << 21))
  240. m_features |= CPUFeature::AVX512_IFMA;
  241. if (extended_features.ebx() & (1 << 22))
  242. m_features |= CPUFeature::PCOMMIT;
  243. if (extended_features.ebx() & (1 << 23))
  244. m_features |= CPUFeature::CLFLUSHOPT;
  245. if (extended_features.ebx() & (1 << 24))
  246. m_features |= CPUFeature::CLWB;
  247. if (extended_features.ebx() & (1 << 25))
  248. m_features |= CPUFeature::INTEL_PT;
  249. if (extended_features.ebx() & (1 << 26))
  250. m_features |= CPUFeature::AVX512_PF;
  251. if (extended_features.ebx() & (1 << 27))
  252. m_features |= CPUFeature::AVX512_ER;
  253. if (extended_features.ebx() & (1 << 28))
  254. m_features |= CPUFeature::AVX512_CD;
  255. if (extended_features.ebx() & (1 << 29))
  256. m_features |= CPUFeature::SHA;
  257. if (extended_features.ebx() & (1 << 30))
  258. m_features |= CPUFeature::AVX512_BW;
  259. if (extended_features.ebx() & (1 << 31))
  260. m_features |= CPUFeature::AVX512_VL;
  261. if (extended_features.ecx() & (1 << 0))
  262. m_features |= CPUFeature::PREFETCHWT1;
  263. if (extended_features.ecx() & (1 << 1))
  264. m_features |= CPUFeature::AVX512_VBMI;
  265. if (extended_features.ecx() & (1 << 2))
  266. m_features |= CPUFeature::UMIP;
  267. if (extended_features.ecx() & (1 << 3))
  268. m_features |= CPUFeature::PKU;
  269. if (extended_features.ecx() & (1 << 4))
  270. m_features |= CPUFeature::OSPKU;
  271. if (extended_features.ecx() & (1 << 5))
  272. m_features |= CPUFeature::WAITPKG;
  273. if (extended_features.ecx() & (1 << 6))
  274. m_features |= CPUFeature::AVX512_VBMI2;
  275. if (extended_features.ecx() & (1 << 7))
  276. m_features |= CPUFeature::CET_SS;
  277. if (extended_features.ecx() & (1 << 8))
  278. m_features |= CPUFeature::GFNI;
  279. if (extended_features.ecx() & (1 << 9))
  280. m_features |= CPUFeature::VAES;
  281. if (extended_features.ecx() & (1 << 10))
  282. m_features |= CPUFeature::VPCLMULQDQ;
  283. if (extended_features.ecx() & (1 << 11))
  284. m_features |= CPUFeature::AVX512_VNNI;
  285. if (extended_features.ecx() & (1 << 12))
  286. m_features |= CPUFeature::AVX512_BITALG;
  287. if (extended_features.ecx() & (1 << 13))
  288. m_features |= CPUFeature::TME_EN;
  289. if (extended_features.ecx() & (1 << 14))
  290. m_features |= CPUFeature::AVX512_VPOPCNTDQ;
  291. if (extended_features.ecx() & (1 << 16))
  292. m_features |= CPUFeature::INTEL_5_LEVEL_PAGING;
  293. if (extended_features.ecx() & (1 << 22))
  294. m_features |= CPUFeature::RDPID;
  295. if (extended_features.ecx() & (1 << 23))
  296. m_features |= CPUFeature::KL;
  297. if (extended_features.ecx() & (1 << 25))
  298. m_features |= CPUFeature::CLDEMOTE;
  299. if (extended_features.ecx() & (1 << 27))
  300. m_features |= CPUFeature::MOVDIRI;
  301. if (extended_features.ecx() & (1 << 28))
  302. m_features |= CPUFeature::MOVDIR64B;
  303. if (extended_features.ecx() & (1 << 29))
  304. m_features |= CPUFeature::ENQCMD;
  305. if (extended_features.ecx() & (1 << 30))
  306. m_features |= CPUFeature::SGX_LC;
  307. if (extended_features.ecx() & (1 << 31))
  308. m_features |= CPUFeature::PKS;
  309. if (extended_features.edx() & (1 << 2))
  310. m_features |= CPUFeature::AVX512_4VNNIW;
  311. if (extended_features.edx() & (1 << 3))
  312. m_features |= CPUFeature::AVX512_4FMAPS;
  313. if (extended_features.edx() & (1 << 4))
  314. m_features |= CPUFeature::FSRM;
  315. if (extended_features.edx() & (1 << 8))
  316. m_features |= CPUFeature::AVX512_VP2INTERSECT;
  317. if (extended_features.edx() & (1 << 9))
  318. m_features |= CPUFeature::SRBDS_CTRL;
  319. if (extended_features.edx() & (1 << 10))
  320. m_features |= CPUFeature::MD_CLEAR;
  321. if (extended_features.edx() & (1 << 11))
  322. m_features |= CPUFeature::RTM_ALWAYS_ABORT;
  323. if (extended_features.edx() & (1 << 13))
  324. m_features |= CPUFeature::TSX_FORCE_ABORT;
  325. if (extended_features.edx() & (1 << 14))
  326. m_features |= CPUFeature::SERIALIZE;
  327. if (extended_features.edx() & (1 << 15))
  328. m_features |= CPUFeature::HYBRID;
  329. if (extended_features.edx() & (1 << 16))
  330. m_features |= CPUFeature::TSXLDTRK;
  331. if (extended_features.edx() & (1 << 18))
  332. m_features |= CPUFeature::PCONFIG;
  333. if (extended_features.edx() & (1 << 19))
  334. m_features |= CPUFeature::LBR;
  335. if (extended_features.edx() & (1 << 20))
  336. m_features |= CPUFeature::CET_IBT;
  337. if (extended_features.edx() & (1 << 22))
  338. m_features |= CPUFeature::AMX_BF16;
  339. if (extended_features.edx() & (1 << 23))
  340. m_features |= CPUFeature::AVX512_FP16;
  341. if (extended_features.edx() & (1 << 24))
  342. m_features |= CPUFeature::AMX_TILE;
  343. if (extended_features.edx() & (1 << 25))
  344. m_features |= CPUFeature::AMX_INT8;
  345. if (extended_features.edx() & (1 << 26))
  346. m_features |= CPUFeature::SPEC_CTRL;
  347. if (extended_features.edx() & (1 << 27))
  348. m_features |= CPUFeature::STIBP;
  349. if (extended_features.edx() & (1 << 28))
  350. m_features |= CPUFeature::L1D_FLUSH;
  351. if (extended_features.edx() & (1 << 29))
  352. m_features |= CPUFeature::IA32_ARCH_CAPABILITIES;
  353. if (extended_features.edx() & (1 << 30))
  354. m_features |= CPUFeature::IA32_CORE_CAPABILITIES;
  355. if (extended_features.edx() & (1 << 31))
  356. m_features |= CPUFeature::SSBD;
  357. u32 max_extended_leaf = CPUID(0x80000000).eax();
  358. if (max_extended_leaf >= 0x80000001) {
  359. CPUID extended_processor_info(0x80000001);
  360. if (extended_processor_info.edx() & (1 << 11))
  361. m_features |= CPUFeature::SYSCALL; // Only available in 64 bit mode
  362. if (extended_processor_info.edx() & (1 << 20))
  363. m_features |= CPUFeature::NX;
  364. if (extended_processor_info.edx() & (1 << 27))
  365. m_features |= CPUFeature::RDTSCP;
  366. if (extended_processor_info.edx() & (1 << 29))
  367. m_features |= CPUFeature::LM;
  368. }
  369. if (max_extended_leaf >= 0x80000007) {
  370. CPUID cpuid(0x80000007);
  371. if (cpuid.edx() & (1 << 8)) {
  372. m_features |= CPUFeature::CONSTANT_TSC;
  373. m_features |= CPUFeature::NONSTOP_TSC;
  374. }
  375. }
  376. #if ARCH(X86_64)
  377. m_has_qemu_hvf_quirk = false;
  378. #endif
  379. if (max_extended_leaf >= 0x80000008) {
  380. // CPUID.80000008H:EAX[7:0] reports the physical-address width supported by the processor.
  381. CPUID cpuid(0x80000008);
  382. m_physical_address_bit_width = cpuid.eax() & 0xff;
  383. // CPUID.80000008H:EAX[15:8] reports the linear-address width supported by the processor.
  384. m_virtual_address_bit_width = (cpuid.eax() >> 8) & 0xff;
  385. } else {
  386. // 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.
  387. m_physical_address_bit_width = has_feature(CPUFeature::PAE) ? 36 : 32;
  388. // Processors that do not support CPUID function 80000008H, support a linear-address width of 32.
  389. m_virtual_address_bit_width = 32;
  390. #if ARCH(X86_64)
  391. // Workaround QEMU hypervisor.framework bug
  392. // https://gitlab.com/qemu-project/qemu/-/issues/664
  393. //
  394. // We detect this as follows:
  395. // * We're in a hypervisor
  396. // * hypervisor_leaf_range is null under Hypervisor.framework
  397. // * m_physical_address_bit_width is 36 bits
  398. if (has_feature(CPUFeature::HYPERVISOR)) {
  399. CPUID hypervisor_leaf_range(0x40000000);
  400. if (!hypervisor_leaf_range.ebx() && m_physical_address_bit_width == 36) {
  401. m_has_qemu_hvf_quirk = true;
  402. m_virtual_address_bit_width = 48;
  403. }
  404. }
  405. #endif
  406. }
  407. }
  408. UNMAP_AFTER_INIT void Processor::cpu_setup()
  409. {
  410. // NOTE: This is called during Processor::early_initialize, we cannot
  411. // safely log at this point because we don't have kmalloc
  412. // initialized yet!
  413. cpu_detect();
  414. if (has_feature(CPUFeature::SSE)) {
  415. // enter_thread_context() assumes that if a x86 CPU supports SSE then it also supports FXSR.
  416. // SSE support without FXSR is an extremely unlikely scenario, so let's be pragmatic about it.
  417. VERIFY(has_feature(CPUFeature::FXSR));
  418. sse_init();
  419. }
  420. write_cr0(read_cr0() | 0x00010000);
  421. if (has_feature(CPUFeature::PGE)) {
  422. // Turn on CR4.PGE so the CPU will respect the G bit in page tables.
  423. write_cr4(read_cr4() | 0x80);
  424. }
  425. if (has_feature(CPUFeature::NX)) {
  426. // Turn on IA32_EFER.NXE
  427. MSR ia32_efer(MSR_IA32_EFER);
  428. ia32_efer.set(ia32_efer.get() | 0x800);
  429. }
  430. if (has_feature(CPUFeature::PAT)) {
  431. MSR ia32_pat(MSR_IA32_PAT);
  432. // Set PA4 to Write Comine. This allows us to
  433. // use this mode by only setting the bit in the PTE
  434. // and leaving all other bits in the upper levels unset,
  435. // which maps to setting bit 3 of the index, resulting
  436. // in the index value 0 or 4.
  437. u64 pat = ia32_pat.get() & ~(0x7ull << 32);
  438. pat |= 0x1ull << 32; // set WC mode for PA4
  439. ia32_pat.set(pat);
  440. }
  441. if (has_feature(CPUFeature::SMEP)) {
  442. // Turn on CR4.SMEP
  443. write_cr4(read_cr4() | 0x100000);
  444. }
  445. if (has_feature(CPUFeature::SMAP)) {
  446. // Turn on CR4.SMAP
  447. write_cr4(read_cr4() | 0x200000);
  448. }
  449. if (has_feature(CPUFeature::UMIP)) {
  450. write_cr4(read_cr4() | 0x800);
  451. }
  452. if (has_feature(CPUFeature::TSC)) {
  453. write_cr4(read_cr4() | 0x4);
  454. }
  455. if (has_feature(CPUFeature::XSAVE)) {
  456. // Turn on CR4.OSXSAVE
  457. write_cr4(read_cr4() | 0x40000);
  458. // According to the Intel manual: "After reset, all bits (except bit 0) in XCR0 are cleared to zero; XCR0[0] is set to 1."
  459. // Sadly we can't trust this, for example VirtualBox starts with bits 0-4 set, so let's do it ourselves.
  460. write_xcr0(0x1);
  461. if (has_feature(CPUFeature::AVX)) {
  462. // Turn on SSE, AVX and x87 flags
  463. write_xcr0(read_xcr0() | 0x7);
  464. }
  465. }
  466. #if ARCH(X86_64)
  467. // x86_64 processors must support the syscall feature.
  468. VERIFY(has_feature(CPUFeature::SYSCALL));
  469. MSR efer_msr(MSR_EFER);
  470. efer_msr.set(efer_msr.get() | 1u);
  471. // Write code and stack selectors to the STAR MSR. The first value stored in bits 63:48 controls the sysret CS (value + 0x10) and SS (value + 0x8),
  472. // and the value stored in bits 47:32 controls the syscall CS (value) and SS (value + 0x8).
  473. u64 star = 0;
  474. star |= 0x13ul << 48u;
  475. star |= 0x08ul << 32u;
  476. MSR star_msr(MSR_STAR);
  477. star_msr.set(star);
  478. // Write the syscall entry point to the LSTAR MSR.
  479. MSR lstar_msr(MSR_LSTAR);
  480. lstar_msr.set(reinterpret_cast<u64>(&syscall_entry));
  481. // Write the SFMASK MSR. This MSR controls which bits of rflags are masked when a syscall instruction is executed -
  482. // if a bit is set in sfmask, the corresponding bit in rflags is cleared. The value set here clears most of rflags,
  483. // but keeps the reserved and virtualization bits intact. The userspace rflags value is saved in r11 by syscall.
  484. constexpr u64 rflags_mask = 0x257fd5u;
  485. MSR sfmask_msr(MSR_SFMASK);
  486. sfmask_msr.set(rflags_mask);
  487. #endif
  488. }
  489. NonnullOwnPtr<KString> Processor::features_string() const
  490. {
  491. StringBuilder builder;
  492. bool first = true;
  493. for (auto feature = CPUFeature::Type(1u); feature != CPUFeature::__End; feature <<= 1u) {
  494. if (has_feature(feature)) {
  495. if (first)
  496. first = false;
  497. else
  498. MUST(builder.try_append(' '));
  499. MUST(builder.try_append(cpu_feature_to_string_view(feature)));
  500. }
  501. }
  502. return KString::must_create(builder.string_view());
  503. }
  504. UNMAP_AFTER_INIT void Processor::early_initialize(u32 cpu)
  505. {
  506. m_self = this;
  507. m_cpu = cpu;
  508. m_in_irq = 0;
  509. m_in_critical = 0;
  510. m_invoke_scheduler_async = false;
  511. m_scheduler_initialized = false;
  512. m_in_scheduler = true;
  513. m_message_queue = nullptr;
  514. m_idle_thread = nullptr;
  515. m_current_thread = nullptr;
  516. m_info = nullptr;
  517. m_halt_requested = false;
  518. if (cpu == 0) {
  519. s_smp_enabled = false;
  520. g_total_processors.store(1u, AK::MemoryOrder::memory_order_release);
  521. } else {
  522. g_total_processors.fetch_add(1u, AK::MemoryOrder::memory_order_acq_rel);
  523. }
  524. deferred_call_pool_init();
  525. cpu_setup();
  526. gdt_init();
  527. VERIFY(is_initialized()); // sanity check
  528. VERIFY(&current() == this); // sanity check
  529. }
  530. UNMAP_AFTER_INIT void Processor::initialize(u32 cpu)
  531. {
  532. VERIFY(m_self == this);
  533. VERIFY(&current() == this); // sanity check
  534. dmesgln("CPU[{}]: Supported features: {}", current_id(), features_string());
  535. if (!has_feature(CPUFeature::RDRAND))
  536. dmesgln("CPU[{}]: No RDRAND support detected, randomness will be poor", current_id());
  537. dmesgln("CPU[{}]: Physical address bit width: {}", current_id(), m_physical_address_bit_width);
  538. dmesgln("CPU[{}]: Virtual address bit width: {}", current_id(), m_virtual_address_bit_width);
  539. #if ARCH(X86_64)
  540. if (m_has_qemu_hvf_quirk)
  541. dmesgln("CPU[{}]: Applied correction for QEMU Hypervisor.framework quirk", current_id());
  542. #endif
  543. if (cpu == 0)
  544. idt_init();
  545. else
  546. flush_idt();
  547. if (cpu == 0) {
  548. VERIFY((FlatPtr(&s_clean_fpu_state) & 0xF) == 0);
  549. asm volatile("fninit");
  550. if (has_feature(CPUFeature::FXSR))
  551. asm volatile("fxsave %0"
  552. : "=m"(s_clean_fpu_state));
  553. else
  554. asm volatile("fnsave %0"
  555. : "=m"(s_clean_fpu_state));
  556. if (has_feature(CPUFeature::HYPERVISOR))
  557. detect_hypervisor();
  558. }
  559. m_info = new ProcessorInfo(*this);
  560. {
  561. // We need to prevent races between APs starting up at the same time
  562. VERIFY(cpu < s_processors.size());
  563. s_processors[cpu] = this;
  564. }
  565. }
  566. UNMAP_AFTER_INIT void Processor::detect_hypervisor()
  567. {
  568. CPUID hypervisor_leaf_range(0x40000000);
  569. // Get signature of hypervisor.
  570. alignas(sizeof(u32)) char hypervisor_signature_buffer[13];
  571. *reinterpret_cast<u32*>(hypervisor_signature_buffer) = hypervisor_leaf_range.ebx();
  572. *reinterpret_cast<u32*>(hypervisor_signature_buffer + 4) = hypervisor_leaf_range.ecx();
  573. *reinterpret_cast<u32*>(hypervisor_signature_buffer + 8) = hypervisor_leaf_range.edx();
  574. hypervisor_signature_buffer[12] = '\0';
  575. StringView hypervisor_signature(hypervisor_signature_buffer);
  576. dmesgln("CPU[{}]: CPUID hypervisor signature '{}' ({:#x} {:#x} {:#x}), max leaf {:#x}", current_id(), hypervisor_signature, hypervisor_leaf_range.ebx(), hypervisor_leaf_range.ecx(), hypervisor_leaf_range.edx(), hypervisor_leaf_range.eax());
  577. if (hypervisor_signature == "Microsoft Hv"sv)
  578. detect_hypervisor_hyperv(hypervisor_leaf_range);
  579. }
  580. UNMAP_AFTER_INIT void Processor::detect_hypervisor_hyperv(CPUID const& hypervisor_leaf_range)
  581. {
  582. if (hypervisor_leaf_range.eax() < 0x40000001)
  583. return;
  584. CPUID hypervisor_interface(0x40000001);
  585. // Get signature of hypervisor interface.
  586. alignas(sizeof(u32)) char interface_signature_buffer[5];
  587. *reinterpret_cast<u32*>(interface_signature_buffer) = hypervisor_interface.eax();
  588. interface_signature_buffer[4] = '\0';
  589. StringView hyperv_interface_signature(interface_signature_buffer);
  590. dmesgln("CPU[{}]: Hyper-V interface signature '{}' ({:#x})", current_id(), hyperv_interface_signature, hypervisor_interface.eax());
  591. if (hypervisor_leaf_range.eax() < 0x40000001)
  592. return;
  593. CPUID hypervisor_sysid(0x40000002);
  594. dmesgln("CPU[{}]: Hyper-V system identity {}.{}, build number {}", current_id(), hypervisor_sysid.ebx() >> 16, hypervisor_sysid.ebx() & 0xFFFF, hypervisor_sysid.eax());
  595. if (hypervisor_leaf_range.eax() < 0x40000005 || hyperv_interface_signature != "Hv#1"sv)
  596. return;
  597. dmesgln("CPU[{}]: Hyper-V hypervisor detected", current_id());
  598. // TODO: Actually do something with Hyper-V.
  599. }
  600. void Processor::write_raw_gdt_entry(u16 selector, u32 low, u32 high)
  601. {
  602. u16 i = (selector & 0xfffc) >> 3;
  603. u32 prev_gdt_length = m_gdt_length;
  604. if (i >= m_gdt_length) {
  605. m_gdt_length = i + 1;
  606. VERIFY(m_gdt_length <= sizeof(m_gdt) / sizeof(m_gdt[0]));
  607. m_gdtr.limit = (m_gdt_length + 1) * 8 - 1;
  608. }
  609. m_gdt[i].low = low;
  610. m_gdt[i].high = high;
  611. // clear selectors we may have skipped
  612. for (auto j = prev_gdt_length; j < i; ++j) {
  613. m_gdt[j].low = 0;
  614. m_gdt[j].high = 0;
  615. }
  616. }
  617. void Processor::write_gdt_entry(u16 selector, Descriptor& descriptor)
  618. {
  619. write_raw_gdt_entry(selector, descriptor.low, descriptor.high);
  620. }
  621. Descriptor& Processor::get_gdt_entry(u16 selector)
  622. {
  623. u16 i = (selector & 0xfffc) >> 3;
  624. return *(Descriptor*)(&m_gdt[i]);
  625. }
  626. void Processor::flush_gdt()
  627. {
  628. m_gdtr.address = m_gdt;
  629. m_gdtr.limit = (m_gdt_length * 8) - 1;
  630. asm volatile("lgdt %0" ::"m"(m_gdtr)
  631. : "memory");
  632. }
  633. const DescriptorTablePointer& Processor::get_gdtr()
  634. {
  635. return m_gdtr;
  636. }
  637. ErrorOr<Vector<FlatPtr, 32>> Processor::capture_stack_trace(Thread& thread, size_t max_frames)
  638. {
  639. FlatPtr frame_ptr = 0, ip = 0;
  640. Vector<FlatPtr, 32> stack_trace;
  641. auto walk_stack = [&](FlatPtr stack_ptr) -> ErrorOr<void> {
  642. constexpr size_t max_stack_frames = 4096;
  643. bool is_walking_userspace_stack = false;
  644. TRY(stack_trace.try_append(ip));
  645. size_t count = 1;
  646. while (stack_ptr && stack_trace.size() < max_stack_frames) {
  647. FlatPtr retaddr;
  648. count++;
  649. if (max_frames != 0 && count > max_frames)
  650. break;
  651. if (!Memory::is_user_address(VirtualAddress { stack_ptr })) {
  652. if (is_walking_userspace_stack) {
  653. dbgln("SHENANIGANS! Userspace stack points back into kernel memory");
  654. break;
  655. }
  656. } else {
  657. is_walking_userspace_stack = true;
  658. }
  659. if (Memory::is_user_range(VirtualAddress(stack_ptr), sizeof(FlatPtr) * 2)) {
  660. if (copy_from_user(&retaddr, &((FlatPtr*)stack_ptr)[1]).is_error() || !retaddr)
  661. break;
  662. TRY(stack_trace.try_append(retaddr));
  663. if (copy_from_user(&stack_ptr, (FlatPtr*)stack_ptr).is_error())
  664. break;
  665. } else {
  666. void* fault_at;
  667. if (!safe_memcpy(&retaddr, &((FlatPtr*)stack_ptr)[1], sizeof(FlatPtr), fault_at) || !retaddr)
  668. break;
  669. TRY(stack_trace.try_append(retaddr));
  670. if (!safe_memcpy(&stack_ptr, (FlatPtr*)stack_ptr, sizeof(FlatPtr), fault_at))
  671. break;
  672. }
  673. }
  674. return {};
  675. };
  676. auto capture_current_thread = [&]() {
  677. frame_ptr = (FlatPtr)__builtin_frame_address(0);
  678. ip = (FlatPtr)__builtin_return_address(0);
  679. return walk_stack(frame_ptr);
  680. };
  681. // Since the thread may be running on another processor, there
  682. // is a chance a context switch may happen while we're trying
  683. // to get it. It also won't be entirely accurate and merely
  684. // reflect the status at the last context switch.
  685. SpinlockLocker lock(g_scheduler_lock);
  686. if (&thread == Processor::current_thread()) {
  687. VERIFY(thread.state() == Thread::State::Running);
  688. // Leave the scheduler lock. If we trigger page faults we may
  689. // need to be preempted. Since this is our own thread it won't
  690. // cause any problems as the stack won't change below this frame.
  691. lock.unlock();
  692. TRY(capture_current_thread());
  693. } else if (thread.is_active()) {
  694. VERIFY(thread.cpu() != Processor::current_id());
  695. // If this is the case, the thread is currently running
  696. // on another processor. We can't trust the kernel stack as
  697. // it may be changing at any time. We need to probably send
  698. // an IPI to that processor, have it walk the stack and wait
  699. // until it returns the data back to us
  700. auto& proc = Processor::current();
  701. ErrorOr<void> result;
  702. smp_unicast(
  703. thread.cpu(),
  704. [&]() {
  705. dbgln("CPU[{}] getting stack for cpu #{}", Processor::current_id(), proc.id());
  706. ScopedAddressSpaceSwitcher switcher(thread.process());
  707. VERIFY(&Processor::current() != &proc);
  708. VERIFY(&thread == Processor::current_thread());
  709. // NOTE: Because the other processor is still holding the
  710. // scheduler lock while waiting for this callback to finish,
  711. // the current thread on the target processor cannot change
  712. // TODO: What to do about page faults here? We might deadlock
  713. // because the other processor is still holding the
  714. // scheduler lock...
  715. result = capture_current_thread();
  716. },
  717. false);
  718. TRY(result);
  719. } else {
  720. switch (thread.state()) {
  721. case Thread::State::Running:
  722. VERIFY_NOT_REACHED(); // should have been handled above
  723. case Thread::State::Runnable:
  724. case Thread::State::Stopped:
  725. case Thread::State::Blocked:
  726. case Thread::State::Dying:
  727. case Thread::State::Dead: {
  728. // We need to retrieve ebp from what was last pushed to the kernel
  729. // stack. Before switching out of that thread, it switch_context
  730. // pushed the callee-saved registers, and the last of them happens
  731. // to be ebp.
  732. ScopedAddressSpaceSwitcher switcher(thread.process());
  733. auto& regs = thread.regs();
  734. auto* stack_top = reinterpret_cast<FlatPtr*>(regs.sp());
  735. if (Memory::is_user_range(VirtualAddress(stack_top), sizeof(FlatPtr))) {
  736. if (copy_from_user(&frame_ptr, &((FlatPtr*)stack_top)[0]).is_error())
  737. frame_ptr = 0;
  738. } else {
  739. void* fault_at;
  740. if (!safe_memcpy(&frame_ptr, &((FlatPtr*)stack_top)[0], sizeof(FlatPtr), fault_at))
  741. frame_ptr = 0;
  742. }
  743. ip = regs.ip();
  744. // TODO: We need to leave the scheduler lock here, but we also
  745. // need to prevent the target thread from being run while
  746. // we walk the stack
  747. lock.unlock();
  748. TRY(walk_stack(frame_ptr));
  749. break;
  750. }
  751. default:
  752. dbgln("Cannot capture stack trace for thread {} in state {}", thread, thread.state_string());
  753. break;
  754. }
  755. }
  756. return stack_trace;
  757. }
  758. ProcessorContainer& Processor::processors()
  759. {
  760. return s_processors;
  761. }
  762. Processor& Processor::by_id(u32 id)
  763. {
  764. return *s_processors[id];
  765. }
  766. void Processor::enter_trap(TrapFrame& trap, bool raise_irq)
  767. {
  768. VERIFY_INTERRUPTS_DISABLED();
  769. VERIFY(&Processor::current() == this);
  770. trap.prev_irq_level = m_in_irq;
  771. if (raise_irq)
  772. m_in_irq++;
  773. auto* current_thread = Processor::current_thread();
  774. if (current_thread) {
  775. auto& current_trap = current_thread->current_trap();
  776. trap.next_trap = current_trap;
  777. current_trap = &trap;
  778. // The cs register of this trap tells us where we will return back to
  779. auto new_previous_mode = ((trap.regs->cs & 3) != 0) ? Thread::PreviousMode::UserMode : Thread::PreviousMode::KernelMode;
  780. if (current_thread->set_previous_mode(new_previous_mode) && trap.prev_irq_level == 0) {
  781. current_thread->update_time_scheduled(Scheduler::current_time(), new_previous_mode == Thread::PreviousMode::KernelMode, false);
  782. }
  783. } else {
  784. trap.next_trap = nullptr;
  785. }
  786. }
  787. void Processor::exit_trap(TrapFrame& trap)
  788. {
  789. VERIFY_INTERRUPTS_DISABLED();
  790. VERIFY(&Processor::current() == this);
  791. // Temporarily enter a critical section. This is to prevent critical
  792. // sections entered and left within e.g. smp_process_pending_messages
  793. // to trigger a context switch while we're executing this function
  794. // See the comment at the end of the function why we don't use
  795. // ScopedCritical here.
  796. m_in_critical = m_in_critical + 1;
  797. VERIFY(m_in_irq >= trap.prev_irq_level);
  798. m_in_irq = trap.prev_irq_level;
  799. if (s_smp_enabled)
  800. smp_process_pending_messages();
  801. // Process the deferred call queue. Among other things, this ensures
  802. // that any pending thread unblocks happen before we enter the scheduler.
  803. deferred_call_execute_pending();
  804. auto* current_thread = Processor::current_thread();
  805. if (current_thread) {
  806. auto& current_trap = current_thread->current_trap();
  807. current_trap = trap.next_trap;
  808. Thread::PreviousMode new_previous_mode;
  809. if (current_trap) {
  810. VERIFY(current_trap->regs);
  811. // If we have another higher level trap then we probably returned
  812. // from an interrupt or irq handler. The cs register of the
  813. // new/higher level trap tells us what the mode prior to it was
  814. new_previous_mode = ((current_trap->regs->cs & 3) != 0) ? Thread::PreviousMode::UserMode : Thread::PreviousMode::KernelMode;
  815. } else {
  816. // If we don't have a higher level trap then we're back in user mode.
  817. // Which means that the previous mode prior to being back in user mode was kernel mode
  818. new_previous_mode = Thread::PreviousMode::KernelMode;
  819. }
  820. if (current_thread->set_previous_mode(new_previous_mode))
  821. current_thread->update_time_scheduled(Scheduler::current_time(), true, false);
  822. }
  823. VERIFY_INTERRUPTS_DISABLED();
  824. // Leave the critical section without actually enabling interrupts.
  825. // We don't want context switches to happen until we're explicitly
  826. // triggering a switch in check_invoke_scheduler.
  827. m_in_critical = m_in_critical - 1;
  828. if (!m_in_irq && !m_in_critical)
  829. check_invoke_scheduler();
  830. }
  831. void Processor::check_invoke_scheduler()
  832. {
  833. InterruptDisabler disabler;
  834. VERIFY(!m_in_irq);
  835. VERIFY(!m_in_critical);
  836. VERIFY(&Processor::current() == this);
  837. if (m_invoke_scheduler_async && m_scheduler_initialized) {
  838. m_invoke_scheduler_async = false;
  839. Scheduler::invoke_async();
  840. }
  841. }
  842. void Processor::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  843. {
  844. auto ptr = vaddr.as_ptr();
  845. while (page_count > 0) {
  846. // clang-format off
  847. asm volatile("invlpg %0"
  848. :
  849. : "m"(*ptr)
  850. : "memory");
  851. // clang-format on
  852. ptr += PAGE_SIZE;
  853. page_count--;
  854. }
  855. }
  856. void Processor::flush_tlb(Memory::PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
  857. {
  858. if (s_smp_enabled && (!Memory::is_user_address(vaddr) || Process::current().thread_count() > 1))
  859. smp_broadcast_flush_tlb(page_directory, vaddr, page_count);
  860. else
  861. flush_tlb_local(vaddr, page_count);
  862. }
  863. void Processor::smp_return_to_pool(ProcessorMessage& msg)
  864. {
  865. ProcessorMessage* next = nullptr;
  866. for (;;) {
  867. msg.next = next;
  868. if (s_message_pool.compare_exchange_strong(next, &msg, AK::MemoryOrder::memory_order_acq_rel))
  869. break;
  870. Processor::pause();
  871. }
  872. }
  873. ProcessorMessage& Processor::smp_get_from_pool()
  874. {
  875. ProcessorMessage* msg;
  876. // The assumption is that messages are never removed from the pool!
  877. for (;;) {
  878. msg = s_message_pool.load(AK::MemoryOrder::memory_order_consume);
  879. if (!msg) {
  880. if (!Processor::current().smp_process_pending_messages()) {
  881. Processor::pause();
  882. }
  883. continue;
  884. }
  885. // If another processor were to use this message in the meanwhile,
  886. // "msg" is still valid (because it never gets freed). We'd detect
  887. // this because the expected value "msg" and pool would
  888. // no longer match, and the compare_exchange will fail. But accessing
  889. // "msg->next" is always safe here.
  890. if (s_message_pool.compare_exchange_strong(msg, msg->next, AK::MemoryOrder::memory_order_acq_rel)) {
  891. // We successfully "popped" this available message
  892. break;
  893. }
  894. }
  895. VERIFY(msg != nullptr);
  896. return *msg;
  897. }
  898. u32 Processor::smp_wake_n_idle_processors(u32 wake_count)
  899. {
  900. VERIFY_INTERRUPTS_DISABLED();
  901. VERIFY(wake_count > 0);
  902. if (!s_smp_enabled)
  903. return 0;
  904. // Wake at most N - 1 processors
  905. if (wake_count >= Processor::count()) {
  906. wake_count = Processor::count() - 1;
  907. VERIFY(wake_count > 0);
  908. }
  909. u32 current_id = Processor::current_id();
  910. u32 did_wake_count = 0;
  911. auto& apic = APIC::the();
  912. while (did_wake_count < wake_count) {
  913. // Try to get a set of idle CPUs and flip them to busy
  914. u32 idle_mask = s_idle_cpu_mask.load(AK::MemoryOrder::memory_order_relaxed) & ~(1u << current_id);
  915. u32 idle_count = popcount(idle_mask);
  916. if (idle_count == 0)
  917. break; // No (more) idle processor available
  918. u32 found_mask = 0;
  919. for (u32 i = 0; i < idle_count; i++) {
  920. u32 cpu = bit_scan_forward(idle_mask) - 1;
  921. idle_mask &= ~(1u << cpu);
  922. found_mask |= 1u << cpu;
  923. }
  924. idle_mask = s_idle_cpu_mask.fetch_and(~found_mask, AK::MemoryOrder::memory_order_acq_rel) & found_mask;
  925. if (idle_mask == 0)
  926. continue; // All of them were flipped to busy, try again
  927. idle_count = popcount(idle_mask);
  928. for (u32 i = 0; i < idle_count; i++) {
  929. u32 cpu = bit_scan_forward(idle_mask) - 1;
  930. idle_mask &= ~(1u << cpu);
  931. // Send an IPI to that CPU to wake it up. There is a possibility
  932. // someone else woke it up as well, or that it woke up due to
  933. // a timer interrupt. But we tried hard to avoid this...
  934. apic.send_ipi(cpu);
  935. did_wake_count++;
  936. }
  937. }
  938. return did_wake_count;
  939. }
  940. UNMAP_AFTER_INIT void Processor::smp_enable()
  941. {
  942. size_t msg_pool_size = Processor::count() * 100u;
  943. size_t msg_entries_cnt = Processor::count();
  944. auto msgs = new ProcessorMessage[msg_pool_size];
  945. auto msg_entries = new ProcessorMessageEntry[msg_pool_size * msg_entries_cnt];
  946. size_t msg_entry_i = 0;
  947. for (size_t i = 0; i < msg_pool_size; i++, msg_entry_i += msg_entries_cnt) {
  948. auto& msg = msgs[i];
  949. msg.next = i < msg_pool_size - 1 ? &msgs[i + 1] : nullptr;
  950. msg.per_proc_entries = &msg_entries[msg_entry_i];
  951. for (size_t k = 0; k < msg_entries_cnt; k++)
  952. msg_entries[msg_entry_i + k].msg = &msg;
  953. }
  954. s_message_pool.store(&msgs[0], AK::MemoryOrder::memory_order_release);
  955. // Start sending IPI messages
  956. s_smp_enabled = true;
  957. }
  958. void Processor::smp_cleanup_message(ProcessorMessage& msg)
  959. {
  960. switch (msg.type) {
  961. case ProcessorMessage::Callback:
  962. msg.callback_value().~Function();
  963. break;
  964. default:
  965. break;
  966. }
  967. }
  968. bool Processor::smp_process_pending_messages()
  969. {
  970. VERIFY(s_smp_enabled);
  971. bool did_process = false;
  972. enter_critical();
  973. if (auto pending_msgs = m_message_queue.exchange(nullptr, AK::MemoryOrder::memory_order_acq_rel)) {
  974. // We pulled the stack of pending messages in LIFO order, so we need to reverse the list first
  975. auto reverse_list =
  976. [](ProcessorMessageEntry* list) -> ProcessorMessageEntry* {
  977. ProcessorMessageEntry* rev_list = nullptr;
  978. while (list) {
  979. auto next = list->next;
  980. list->next = rev_list;
  981. rev_list = list;
  982. list = next;
  983. }
  984. return rev_list;
  985. };
  986. pending_msgs = reverse_list(pending_msgs);
  987. // now process in the right order
  988. ProcessorMessageEntry* next_msg;
  989. for (auto cur_msg = pending_msgs; cur_msg; cur_msg = next_msg) {
  990. next_msg = cur_msg->next;
  991. auto msg = cur_msg->msg;
  992. dbgln_if(SMP_DEBUG, "SMP[{}]: Processing message {}", current_id(), VirtualAddress(msg));
  993. switch (msg->type) {
  994. case ProcessorMessage::Callback:
  995. msg->invoke_callback();
  996. break;
  997. case ProcessorMessage::FlushTlb:
  998. if (Memory::is_user_address(VirtualAddress(msg->flush_tlb.ptr))) {
  999. // We assume that we don't cross into kernel land!
  1000. VERIFY(Memory::is_user_range(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count * PAGE_SIZE));
  1001. if (read_cr3() != msg->flush_tlb.page_directory->cr3()) {
  1002. // This processor isn't using this page directory right now, we can ignore this request
  1003. dbgln_if(SMP_DEBUG, "SMP[{}]: No need to flush {} pages at {}", current_id(), msg->flush_tlb.page_count, VirtualAddress(msg->flush_tlb.ptr));
  1004. break;
  1005. }
  1006. }
  1007. flush_tlb_local(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count);
  1008. break;
  1009. }
  1010. bool is_async = msg->async; // Need to cache this value *before* dropping the ref count!
  1011. auto prev_refs = msg->refs.fetch_sub(1u, AK::MemoryOrder::memory_order_acq_rel);
  1012. VERIFY(prev_refs != 0);
  1013. if (prev_refs == 1) {
  1014. // All processors handled this. If this is an async message,
  1015. // we need to clean it up and return it to the pool
  1016. if (is_async) {
  1017. smp_cleanup_message(*msg);
  1018. smp_return_to_pool(*msg);
  1019. }
  1020. }
  1021. if (m_halt_requested.load(AK::MemoryOrder::memory_order_relaxed))
  1022. halt_this();
  1023. }
  1024. did_process = true;
  1025. } else if (m_halt_requested.load(AK::MemoryOrder::memory_order_relaxed)) {
  1026. halt_this();
  1027. }
  1028. leave_critical();
  1029. return did_process;
  1030. }
  1031. bool Processor::smp_enqueue_message(ProcessorMessage& msg)
  1032. {
  1033. // Note that it's quite possible that the other processor may pop
  1034. // the queue at any given time. We rely on the fact that the messages
  1035. // are pooled and never get freed!
  1036. auto& msg_entry = msg.per_proc_entries[id()];
  1037. VERIFY(msg_entry.msg == &msg);
  1038. ProcessorMessageEntry* next = nullptr;
  1039. for (;;) {
  1040. msg_entry.next = next;
  1041. if (m_message_queue.compare_exchange_strong(next, &msg_entry, AK::MemoryOrder::memory_order_acq_rel))
  1042. break;
  1043. Processor::pause();
  1044. }
  1045. // If the enqueued message was the only message in the queue when posted,
  1046. // we return true. This is used by callers when deciding whether to generate an IPI.
  1047. return next == nullptr;
  1048. }
  1049. void Processor::smp_broadcast_message(ProcessorMessage& msg)
  1050. {
  1051. auto& current_processor = Processor::current();
  1052. dbgln_if(SMP_DEBUG, "SMP[{}]: Broadcast message {} to cpus: {} processor: {}", current_processor.id(), VirtualAddress(&msg), count(), VirtualAddress(&current_processor));
  1053. msg.refs.store(count() - 1, AK::MemoryOrder::memory_order_release);
  1054. VERIFY(msg.refs > 0);
  1055. bool need_broadcast = false;
  1056. for_each(
  1057. [&](Processor& proc) {
  1058. if (&proc != &current_processor) {
  1059. if (proc.smp_enqueue_message(msg))
  1060. need_broadcast = true;
  1061. }
  1062. });
  1063. // Now trigger an IPI on all other APs (unless all targets already had messages queued)
  1064. if (need_broadcast)
  1065. APIC::the().broadcast_ipi();
  1066. }
  1067. void Processor::smp_broadcast_wait_sync(ProcessorMessage& msg)
  1068. {
  1069. auto& cur_proc = Processor::current();
  1070. VERIFY(!msg.async);
  1071. // If synchronous then we must cleanup and return the message back
  1072. // to the pool. Otherwise, the last processor to complete it will return it
  1073. while (msg.refs.load(AK::MemoryOrder::memory_order_consume) != 0) {
  1074. Processor::pause();
  1075. // We need to process any messages that may have been sent to
  1076. // us while we're waiting. This also checks if another processor
  1077. // may have requested us to halt.
  1078. cur_proc.smp_process_pending_messages();
  1079. }
  1080. smp_cleanup_message(msg);
  1081. smp_return_to_pool(msg);
  1082. }
  1083. void Processor::smp_unicast_message(u32 cpu, ProcessorMessage& msg, bool async)
  1084. {
  1085. auto& current_processor = Processor::current();
  1086. VERIFY(cpu != current_processor.id());
  1087. auto& target_processor = processors()[cpu];
  1088. msg.async = async;
  1089. dbgln_if(SMP_DEBUG, "SMP[{}]: Send message {} to cpu #{} processor: {}", current_processor.id(), VirtualAddress(&msg), cpu, VirtualAddress(&target_processor));
  1090. msg.refs.store(1u, AK::MemoryOrder::memory_order_release);
  1091. if (target_processor->smp_enqueue_message(msg)) {
  1092. APIC::the().send_ipi(cpu);
  1093. }
  1094. if (!async) {
  1095. // If synchronous then we must cleanup and return the message back
  1096. // to the pool. Otherwise, the last processor to complete it will return it
  1097. while (msg.refs.load(AK::MemoryOrder::memory_order_consume) != 0) {
  1098. Processor::pause();
  1099. // We need to process any messages that may have been sent to
  1100. // us while we're waiting. This also checks if another processor
  1101. // may have requested us to halt.
  1102. current_processor.smp_process_pending_messages();
  1103. }
  1104. smp_cleanup_message(msg);
  1105. smp_return_to_pool(msg);
  1106. }
  1107. }
  1108. void Processor::smp_unicast(u32 cpu, Function<void()> callback, bool async)
  1109. {
  1110. auto& msg = smp_get_from_pool();
  1111. msg.type = ProcessorMessage::Callback;
  1112. new (msg.callback_storage) ProcessorMessage::CallbackFunction(move(callback));
  1113. smp_unicast_message(cpu, msg, async);
  1114. }
  1115. void Processor::smp_broadcast_flush_tlb(Memory::PageDirectory const* page_directory, VirtualAddress vaddr, size_t page_count)
  1116. {
  1117. auto& msg = smp_get_from_pool();
  1118. msg.async = false;
  1119. msg.type = ProcessorMessage::FlushTlb;
  1120. msg.flush_tlb.page_directory = page_directory;
  1121. msg.flush_tlb.ptr = vaddr.as_ptr();
  1122. msg.flush_tlb.page_count = page_count;
  1123. smp_broadcast_message(msg);
  1124. // While the other processors handle this request, we'll flush ours
  1125. flush_tlb_local(vaddr, page_count);
  1126. // Now wait until everybody is done as well
  1127. smp_broadcast_wait_sync(msg);
  1128. }
  1129. void Processor::smp_broadcast_halt()
  1130. {
  1131. // We don't want to use a message, because this could have been triggered
  1132. // by being out of memory and we might not be able to get a message
  1133. for_each(
  1134. [&](Processor& proc) {
  1135. proc.m_halt_requested.store(true, AK::MemoryOrder::memory_order_release);
  1136. });
  1137. // Now trigger an IPI on all other APs
  1138. APIC::the().broadcast_ipi();
  1139. }
  1140. void Processor::Processor::halt()
  1141. {
  1142. if (s_smp_enabled)
  1143. smp_broadcast_halt();
  1144. halt_this();
  1145. }
  1146. UNMAP_AFTER_INIT void Processor::deferred_call_pool_init()
  1147. {
  1148. size_t pool_count = sizeof(m_deferred_call_pool) / sizeof(m_deferred_call_pool[0]);
  1149. for (size_t i = 0; i < pool_count; i++) {
  1150. auto& entry = m_deferred_call_pool[i];
  1151. entry.next = i < pool_count - 1 ? &m_deferred_call_pool[i + 1] : nullptr;
  1152. new (entry.handler_storage) DeferredCallEntry::HandlerFunction;
  1153. entry.was_allocated = false;
  1154. }
  1155. m_pending_deferred_calls = nullptr;
  1156. m_free_deferred_call_pool_entry = &m_deferred_call_pool[0];
  1157. }
  1158. void Processor::deferred_call_return_to_pool(DeferredCallEntry* entry)
  1159. {
  1160. VERIFY(m_in_critical);
  1161. VERIFY(!entry->was_allocated);
  1162. entry->handler_value() = {};
  1163. entry->next = m_free_deferred_call_pool_entry;
  1164. m_free_deferred_call_pool_entry = entry;
  1165. }
  1166. DeferredCallEntry* Processor::deferred_call_get_free()
  1167. {
  1168. VERIFY(m_in_critical);
  1169. if (m_free_deferred_call_pool_entry) {
  1170. // Fast path, we have an entry in our pool
  1171. auto* entry = m_free_deferred_call_pool_entry;
  1172. m_free_deferred_call_pool_entry = entry->next;
  1173. VERIFY(!entry->was_allocated);
  1174. return entry;
  1175. }
  1176. auto* entry = new DeferredCallEntry;
  1177. new (entry->handler_storage) DeferredCallEntry::HandlerFunction;
  1178. entry->was_allocated = true;
  1179. return entry;
  1180. }
  1181. void Processor::deferred_call_execute_pending()
  1182. {
  1183. VERIFY(m_in_critical);
  1184. if (!m_pending_deferred_calls)
  1185. return;
  1186. auto* pending_list = m_pending_deferred_calls;
  1187. m_pending_deferred_calls = nullptr;
  1188. // We pulled the stack of pending deferred calls in LIFO order, so we need to reverse the list first
  1189. auto reverse_list =
  1190. [](DeferredCallEntry* list) -> DeferredCallEntry* {
  1191. DeferredCallEntry* rev_list = nullptr;
  1192. while (list) {
  1193. auto next = list->next;
  1194. list->next = rev_list;
  1195. rev_list = list;
  1196. list = next;
  1197. }
  1198. return rev_list;
  1199. };
  1200. pending_list = reverse_list(pending_list);
  1201. do {
  1202. pending_list->invoke_handler();
  1203. // Return the entry back to the pool, or free it
  1204. auto* next = pending_list->next;
  1205. if (pending_list->was_allocated) {
  1206. pending_list->handler_value().~Function();
  1207. delete pending_list;
  1208. } else
  1209. deferred_call_return_to_pool(pending_list);
  1210. pending_list = next;
  1211. } while (pending_list);
  1212. }
  1213. void Processor::deferred_call_queue_entry(DeferredCallEntry* entry)
  1214. {
  1215. VERIFY(m_in_critical);
  1216. entry->next = m_pending_deferred_calls;
  1217. m_pending_deferred_calls = entry;
  1218. }
  1219. void Processor::deferred_call_queue(Function<void()> callback)
  1220. {
  1221. // NOTE: If we are called outside of a critical section and outside
  1222. // of an irq handler, the function will be executed before we return!
  1223. ScopedCritical critical;
  1224. auto& cur_proc = Processor::current();
  1225. auto* entry = cur_proc.deferred_call_get_free();
  1226. entry->handler_value() = move(callback);
  1227. cur_proc.deferred_call_queue_entry(entry);
  1228. }
  1229. UNMAP_AFTER_INIT void Processor::gdt_init()
  1230. {
  1231. m_gdt_length = 0;
  1232. m_gdtr.address = nullptr;
  1233. m_gdtr.limit = 0;
  1234. write_raw_gdt_entry(0x0000, 0x00000000, 0x00000000);
  1235. #if ARCH(I386)
  1236. write_raw_gdt_entry(GDT_SELECTOR_CODE0, 0x0000ffff, 0x00cf9a00); // code0
  1237. write_raw_gdt_entry(GDT_SELECTOR_DATA0, 0x0000ffff, 0x00cf9200); // data0
  1238. write_raw_gdt_entry(GDT_SELECTOR_CODE3, 0x0000ffff, 0x00cffa00); // code3
  1239. write_raw_gdt_entry(GDT_SELECTOR_DATA3, 0x0000ffff, 0x00cff200); // data3
  1240. #else
  1241. write_raw_gdt_entry(GDT_SELECTOR_CODE0, 0x0000ffff, 0x00af9a00); // code0
  1242. write_raw_gdt_entry(GDT_SELECTOR_DATA0, 0x0000ffff, 0x00af9200); // data0
  1243. write_raw_gdt_entry(GDT_SELECTOR_DATA3, 0x0000ffff, 0x008ff200); // data3
  1244. write_raw_gdt_entry(GDT_SELECTOR_CODE3, 0x0000ffff, 0x00affa00); // code3
  1245. #endif
  1246. #if ARCH(I386)
  1247. Descriptor tls_descriptor {};
  1248. tls_descriptor.low = tls_descriptor.high = 0;
  1249. tls_descriptor.dpl = 3;
  1250. tls_descriptor.segment_present = 1;
  1251. tls_descriptor.granularity = 0;
  1252. tls_descriptor.operation_size64 = 0;
  1253. tls_descriptor.operation_size32 = 1;
  1254. tls_descriptor.descriptor_type = 1;
  1255. tls_descriptor.type = 2;
  1256. write_gdt_entry(GDT_SELECTOR_TLS, tls_descriptor); // tls3
  1257. Descriptor gs_descriptor {};
  1258. gs_descriptor.set_base(VirtualAddress { this });
  1259. gs_descriptor.set_limit(sizeof(Processor) - 1);
  1260. gs_descriptor.dpl = 0;
  1261. gs_descriptor.segment_present = 1;
  1262. gs_descriptor.granularity = 0;
  1263. gs_descriptor.operation_size64 = 0;
  1264. gs_descriptor.operation_size32 = 1;
  1265. gs_descriptor.descriptor_type = 1;
  1266. gs_descriptor.type = 2;
  1267. write_gdt_entry(GDT_SELECTOR_PROC, gs_descriptor); // gs0
  1268. #endif
  1269. Descriptor tss_descriptor {};
  1270. tss_descriptor.set_base(VirtualAddress { (size_t)&m_tss & 0xffffffff });
  1271. tss_descriptor.set_limit(sizeof(TSS) - 1);
  1272. tss_descriptor.dpl = 0;
  1273. tss_descriptor.segment_present = 1;
  1274. tss_descriptor.granularity = 0;
  1275. tss_descriptor.operation_size64 = 0;
  1276. tss_descriptor.operation_size32 = 1;
  1277. tss_descriptor.descriptor_type = 0;
  1278. tss_descriptor.type = Descriptor::SystemType::AvailableTSS;
  1279. write_gdt_entry(GDT_SELECTOR_TSS, tss_descriptor); // tss
  1280. #if ARCH(X86_64)
  1281. Descriptor tss_descriptor_part2 {};
  1282. tss_descriptor_part2.low = (size_t)&m_tss >> 32;
  1283. write_gdt_entry(GDT_SELECTOR_TSS_PART2, tss_descriptor_part2);
  1284. #endif
  1285. flush_gdt();
  1286. load_task_register(GDT_SELECTOR_TSS);
  1287. #if ARCH(X86_64)
  1288. MSR gs_base(MSR_GS_BASE);
  1289. gs_base.set((u64)this);
  1290. #else
  1291. asm volatile(
  1292. "mov %%ax, %%ds\n"
  1293. "mov %%ax, %%es\n"
  1294. "mov %%ax, %%fs\n"
  1295. "mov %%ax, %%ss\n" ::"a"(GDT_SELECTOR_DATA0)
  1296. : "memory");
  1297. set_gs(GDT_SELECTOR_PROC);
  1298. #endif
  1299. #if ARCH(I386)
  1300. // Make sure CS points to the kernel code descriptor.
  1301. // clang-format off
  1302. asm volatile(
  1303. "ljmpl $" __STRINGIFY(GDT_SELECTOR_CODE0) ", $sanity\n"
  1304. "sanity:\n");
  1305. // clang-format on
  1306. #endif
  1307. }
  1308. extern "C" void context_first_init([[maybe_unused]] Thread* from_thread, [[maybe_unused]] Thread* to_thread, [[maybe_unused]] TrapFrame* trap)
  1309. {
  1310. VERIFY(!are_interrupts_enabled());
  1311. VERIFY(is_kernel_mode());
  1312. dbgln_if(CONTEXT_SWITCH_DEBUG, "switch_context <-- from {} {} to {} {} (context_first_init)", VirtualAddress(from_thread), *from_thread, VirtualAddress(to_thread), *to_thread);
  1313. VERIFY(to_thread == Thread::current());
  1314. Scheduler::enter_current(*from_thread);
  1315. auto in_critical = to_thread->saved_critical();
  1316. VERIFY(in_critical > 0);
  1317. Processor::restore_in_critical(in_critical);
  1318. // Since we got here and don't have Scheduler::context_switch in the
  1319. // call stack (because this is the first time we switched into this
  1320. // context), we need to notify the scheduler so that it can release
  1321. // the scheduler lock. We don't want to enable interrupts at this point
  1322. // as we're still in the middle of a context switch. Doing so could
  1323. // trigger a context switch within a context switch, leading to a crash.
  1324. FlatPtr flags = trap->regs->flags();
  1325. Scheduler::leave_on_first_switch(flags & ~0x200);
  1326. }
  1327. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
  1328. {
  1329. VERIFY(from_thread == to_thread || from_thread->state() != Thread::State::Running);
  1330. VERIFY(to_thread->state() == Thread::State::Running);
  1331. bool has_fxsr = Processor::current().has_feature(CPUFeature::FXSR);
  1332. Processor::set_current_thread(*to_thread);
  1333. auto& from_regs = from_thread->regs();
  1334. auto& to_regs = to_thread->regs();
  1335. // NOTE: IOPL should never be non-zero in any situation, so let's panic immediately
  1336. // instead of carrying on with elevated I/O privileges.
  1337. VERIFY(get_iopl_from_eflags(to_regs.flags()) == 0);
  1338. if (has_fxsr)
  1339. asm volatile("fxsave %0"
  1340. : "=m"(from_thread->fpu_state()));
  1341. else
  1342. asm volatile("fnsave %0"
  1343. : "=m"(from_thread->fpu_state()));
  1344. #if ARCH(I386)
  1345. from_regs.fs = get_fs();
  1346. from_regs.gs = get_gs();
  1347. set_fs(to_regs.fs);
  1348. set_gs(to_regs.gs);
  1349. #endif
  1350. if (from_thread->process().is_traced())
  1351. read_debug_registers_into(from_thread->debug_register_state());
  1352. if (to_thread->process().is_traced()) {
  1353. write_debug_registers_from(to_thread->debug_register_state());
  1354. } else {
  1355. clear_debug_registers();
  1356. }
  1357. auto& processor = Processor::current();
  1358. #if ARCH(I386)
  1359. auto& tls_descriptor = processor.get_gdt_entry(GDT_SELECTOR_TLS);
  1360. tls_descriptor.set_base(to_thread->thread_specific_data());
  1361. tls_descriptor.set_limit(to_thread->thread_specific_region_size());
  1362. #else
  1363. MSR fs_base_msr(MSR_FS_BASE);
  1364. fs_base_msr.set(to_thread->thread_specific_data().get());
  1365. #endif
  1366. if (from_regs.cr3 != to_regs.cr3)
  1367. write_cr3(to_regs.cr3);
  1368. to_thread->set_cpu(processor.id());
  1369. auto in_critical = to_thread->saved_critical();
  1370. VERIFY(in_critical > 0);
  1371. Processor::restore_in_critical(in_critical);
  1372. if (has_fxsr)
  1373. asm volatile("fxrstor %0" ::"m"(to_thread->fpu_state()));
  1374. else
  1375. asm volatile("frstor %0" ::"m"(to_thread->fpu_state()));
  1376. }
  1377. extern "C" FlatPtr do_init_context(Thread* thread, u32 flags)
  1378. {
  1379. VERIFY_INTERRUPTS_DISABLED();
  1380. thread->regs().set_flags(flags);
  1381. return Processor::current().init_context(*thread, true);
  1382. }
  1383. void Processor::assume_context(Thread& thread, FlatPtr flags)
  1384. {
  1385. dbgln_if(CONTEXT_SWITCH_DEBUG, "Assume context for thread {} {}", VirtualAddress(&thread), thread);
  1386. VERIFY_INTERRUPTS_DISABLED();
  1387. Scheduler::prepare_after_exec();
  1388. // in_critical() should be 2 here. The critical section in Process::exec
  1389. // and then the scheduler lock
  1390. VERIFY(Processor::in_critical() == 2);
  1391. do_assume_context(&thread, flags);
  1392. VERIFY_NOT_REACHED();
  1393. }
  1394. u64 Processor::time_spent_idle() const
  1395. {
  1396. return m_idle_thread->time_in_user() + m_idle_thread->time_in_kernel();
  1397. }
  1398. }