CPU.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Assertions.h>
  27. #include <AK/ScopeGuard.h>
  28. #include <AK/String.h>
  29. #include <AK/StringBuilder.h>
  30. #include <AK/Types.h>
  31. #include <Kernel/Arch/i386/CPU.h>
  32. #include <Kernel/Arch/i386/ISRStubs.h>
  33. #include <Kernel/Arch/i386/ProcessorInfo.h>
  34. #include <Kernel/Arch/i386/SafeMem.h>
  35. #include <Kernel/Debug.h>
  36. #include <Kernel/IO.h>
  37. #include <Kernel/Interrupts/APIC.h>
  38. #include <Kernel/Interrupts/GenericInterruptHandler.h>
  39. #include <Kernel/Interrupts/IRQHandler.h>
  40. #include <Kernel/Interrupts/InterruptManagement.h>
  41. #include <Kernel/Interrupts/SharedIRQHandler.h>
  42. #include <Kernel/Interrupts/SpuriousInterruptHandler.h>
  43. #include <Kernel/Interrupts/UnhandledInterruptHandler.h>
  44. #include <Kernel/KSyms.h>
  45. #include <Kernel/Process.h>
  46. #include <Kernel/Random.h>
  47. #include <Kernel/SpinLock.h>
  48. #include <Kernel/Thread.h>
  49. #include <Kernel/VM/MemoryManager.h>
  50. #include <Kernel/VM/PageDirectory.h>
  51. #include <Kernel/VM/ProcessPagingScope.h>
  52. #include <LibC/mallocdefs.h>
  53. namespace Kernel {
  54. static DescriptorTablePointer s_idtr;
  55. static Descriptor s_idt[256];
  56. static GenericInterruptHandler* s_interrupt_handler[GENERIC_INTERRUPT_HANDLERS_COUNT];
  57. static EntropySource s_entropy_source_interrupts { EntropySource::Static::Interrupts };
  58. // The compiler can't see the calls to these functions inside assembly.
  59. // Declare them, to avoid dead code warnings.
  60. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread);
  61. extern "C" void context_first_init(Thread* from_thread, Thread* to_thread, TrapFrame* trap);
  62. extern "C" u32 do_init_context(Thread* thread, u32 flags);
  63. extern "C" void exit_kernel_thread(void);
  64. extern "C" void pre_init_finished(void);
  65. extern "C" void post_init_finished(void);
  66. extern "C" void handle_interrupt(TrapFrame*);
  67. // clang-format off
  68. #define EH_ENTRY(ec, title) \
  69. extern "C" void title##_asm_entry(); \
  70. extern "C" void title##_handler(TrapFrame*); \
  71. asm( \
  72. ".globl " #title "_asm_entry\n" \
  73. "" #title "_asm_entry: \n" \
  74. " pusha\n" \
  75. " pushl %ds\n" \
  76. " pushl %es\n" \
  77. " pushl %fs\n" \
  78. " pushl %gs\n" \
  79. " pushl %ss\n" \
  80. " mov $" __STRINGIFY(GDT_SELECTOR_DATA0) ", %ax\n" \
  81. " mov %ax, %ds\n" \
  82. " mov %ax, %es\n" \
  83. " mov $" __STRINGIFY(GDT_SELECTOR_PROC) ", %ax\n" \
  84. " mov %ax, %fs\n" \
  85. " pushl %esp \n" /* set TrapFrame::regs */ \
  86. " subl $" __STRINGIFY(TRAP_FRAME_SIZE - 4) ", %esp \n" \
  87. " pushl %esp \n" \
  88. " cld\n" \
  89. " call enter_trap_no_irq \n" \
  90. " call " #title "_handler\n" \
  91. " jmp common_trap_exit \n");
  92. #define EH_ENTRY_NO_CODE(ec, title) \
  93. extern "C" void title##_handler(TrapFrame*); \
  94. extern "C" void title##_asm_entry(); \
  95. asm( \
  96. ".globl " #title "_asm_entry\n" \
  97. "" #title "_asm_entry: \n" \
  98. " pushl $0x0\n" \
  99. " pusha\n" \
  100. " pushl %ds\n" \
  101. " pushl %es\n" \
  102. " pushl %fs\n" \
  103. " pushl %gs\n" \
  104. " pushl %ss\n" \
  105. " mov $" __STRINGIFY(GDT_SELECTOR_DATA0) ", %ax\n" \
  106. " mov %ax, %ds\n" \
  107. " mov %ax, %es\n" \
  108. " mov $" __STRINGIFY(GDT_SELECTOR_PROC) ", %ax\n" \
  109. " mov %ax, %fs\n" \
  110. " pushl %esp \n" /* set TrapFrame::regs */ \
  111. " subl $" __STRINGIFY(TRAP_FRAME_SIZE - 4) ", %esp \n" \
  112. " pushl %esp \n" \
  113. " cld\n" \
  114. " call enter_trap_no_irq \n" \
  115. " call " #title "_handler\n" \
  116. " jmp common_trap_exit \n");
  117. // clang-format on
  118. static void dump(const RegisterState& regs)
  119. {
  120. u16 ss;
  121. u32 esp;
  122. if (!(regs.cs & 3)) {
  123. ss = regs.ss;
  124. esp = regs.esp;
  125. } else {
  126. ss = regs.userspace_ss;
  127. esp = regs.userspace_esp;
  128. }
  129. klog() << "exception code: " << String::format("%04x", regs.exception_code) << " (isr: " << String::format("%04x", regs.isr_number);
  130. klog() << " pc=" << String::format("%04x", (u16)regs.cs) << ":" << String::format("%08x", regs.eip) << " flags=" << String::format("%04x", (u16)regs.eflags);
  131. klog() << " stk=" << String::format("%04x", ss) << ":" << String::format("%08x", esp);
  132. klog() << " ds=" << String::format("%04x", (u16)regs.ds) << " es=" << String::format("%04x", (u16)regs.es) << " fs=" << String::format("%04x", (u16)regs.fs) << " gs=" << String::format("%04x", (u16)regs.gs);
  133. klog() << "eax=" << String::format("%08x", regs.eax) << " ebx=" << String::format("%08x", regs.ebx) << " ecx=" << String::format("%08x", regs.ecx) << " edx=" << String::format("%08x", regs.edx);
  134. klog() << "ebp=" << String::format("%08x", regs.ebp) << " esp=" << String::format("%08x", regs.esp) << " esi=" << String::format("%08x", regs.esi) << " edi=" << String::format("%08x", regs.edi);
  135. u32 cr0;
  136. asm("movl %%cr0, %%eax"
  137. : "=a"(cr0));
  138. u32 cr2;
  139. asm("movl %%cr2, %%eax"
  140. : "=a"(cr2));
  141. u32 cr3 = read_cr3();
  142. u32 cr4;
  143. asm("movl %%cr4, %%eax"
  144. : "=a"(cr4));
  145. klog() << "cr0=" << String::format("%08x", cr0) << " cr2=" << String::format("%08x", cr2) << " cr3=" << String::format("%08x", cr3) << " cr4=" << String::format("%08x", cr4);
  146. auto process = Process::current();
  147. u8 code[8];
  148. void* fault_at;
  149. if (process && safe_memcpy(code, (void*)regs.eip, 8, fault_at)) {
  150. SmapDisabler disabler;
  151. klog() << "code: " << String::format("%02x", code[0]) << " " << String::format("%02x", code[1]) << " " << String::format("%02x", code[2]) << " " << String::format("%02x", code[3]) << " " << String::format("%02x", code[4]) << " " << String::format("%02x", code[5]) << " " << String::format("%02x", code[6]) << " " << String::format("%02x", code[7]);
  152. }
  153. }
  154. void handle_crash(RegisterState& regs, const char* description, int signal, bool out_of_memory)
  155. {
  156. auto process = Process::current();
  157. if (!process) {
  158. klog() << description << " with !current";
  159. Processor::halt();
  160. }
  161. // If a process crashed while inspecting another process,
  162. // make sure we switch back to the right page tables.
  163. MM.enter_process_paging_scope(*process);
  164. klog() << "CRASH: CPU #" << Processor::id() << " " << description << ". Ring " << (regs.cs & 3) << ".";
  165. dump(regs);
  166. if (!(regs.cs & 3)) {
  167. klog() << "Crash in ring 0 :(";
  168. dump_backtrace();
  169. Processor::halt();
  170. }
  171. cli();
  172. process->crash(signal, regs.eip, out_of_memory);
  173. }
  174. EH_ENTRY_NO_CODE(6, illegal_instruction);
  175. void illegal_instruction_handler(TrapFrame* trap)
  176. {
  177. clac();
  178. handle_crash(*trap->regs, "Illegal instruction", SIGILL);
  179. }
  180. EH_ENTRY_NO_CODE(0, divide_error);
  181. void divide_error_handler(TrapFrame* trap)
  182. {
  183. clac();
  184. handle_crash(*trap->regs, "Divide error", SIGFPE);
  185. }
  186. EH_ENTRY(13, general_protection_fault);
  187. void general_protection_fault_handler(TrapFrame* trap)
  188. {
  189. clac();
  190. handle_crash(*trap->regs, "General protection fault", SIGSEGV);
  191. }
  192. // 7: FPU not available exception
  193. EH_ENTRY_NO_CODE(7, fpu_exception);
  194. void fpu_exception_handler(TrapFrame*)
  195. {
  196. // Just clear the TS flag. We've already restored the FPU state eagerly.
  197. // FIXME: It would be nice if we didn't have to do this at all.
  198. asm volatile("clts");
  199. }
  200. // 14: Page Fault
  201. EH_ENTRY(14, page_fault);
  202. void page_fault_handler(TrapFrame* trap)
  203. {
  204. clac();
  205. auto& regs = *trap->regs;
  206. u32 fault_address;
  207. asm("movl %%cr2, %%eax"
  208. : "=a"(fault_address));
  209. if constexpr (PAGE_FAULT_DEBUG) {
  210. u32 fault_page_directory = read_cr3();
  211. dbgln("CPU #{} ring {} {} page fault in PD={:#x}, {}{} {}",
  212. Processor::is_initialized() ? Processor::id() : 0,
  213. regs.cs & 3,
  214. regs.exception_code & 1 ? "PV" : "NP",
  215. fault_page_directory,
  216. regs.exception_code & 8 ? "reserved-bit " : "",
  217. regs.exception_code & 2 ? "write" : "read",
  218. VirtualAddress(fault_address));
  219. dump(regs);
  220. }
  221. bool faulted_in_kernel = !(regs.cs & 3);
  222. if (faulted_in_kernel && Processor::current().in_irq()) {
  223. // If we're faulting in an IRQ handler, first check if we failed
  224. // due to safe_memcpy, safe_strnlen, or safe_memset. If we did,
  225. // gracefully continue immediately. Because we're in an IRQ handler
  226. // we can't really try to resolve the page fault in a meaningful
  227. // way, so we need to do this before calling into
  228. // MemoryManager::handle_page_fault, which would just bail and
  229. // request a crash
  230. if (handle_safe_access_fault(regs, fault_address))
  231. return;
  232. }
  233. auto current_thread = Thread::current();
  234. if (current_thread)
  235. current_thread->set_handling_page_fault(true);
  236. ScopeGuard guard = [current_thread] {
  237. if (current_thread)
  238. current_thread->set_handling_page_fault(false);
  239. };
  240. if (!faulted_in_kernel && !MM.validate_user_stack(current_thread->process(), VirtualAddress(regs.userspace_esp))) {
  241. dbgln("Invalid stack pointer: {}", VirtualAddress(regs.userspace_esp));
  242. handle_crash(regs, "Bad stack on page fault", SIGSTKFLT);
  243. ASSERT_NOT_REACHED();
  244. }
  245. auto response = MM.handle_page_fault(PageFault(regs.exception_code, VirtualAddress(fault_address)));
  246. if (response == PageFaultResponse::ShouldCrash || response == PageFaultResponse::OutOfMemory) {
  247. if (faulted_in_kernel && handle_safe_access_fault(regs, fault_address)) {
  248. // If this would be a ring0 (kernel) fault and the fault was triggered by
  249. // safe_memcpy, safe_strnlen, or safe_memset then we resume execution at
  250. // the appropriate _fault label rather than crashing
  251. return;
  252. }
  253. if (response != PageFaultResponse::OutOfMemory) {
  254. if (current_thread->has_signal_handler(SIGSEGV)) {
  255. current_thread->send_urgent_signal_to_self(SIGSEGV);
  256. return;
  257. }
  258. }
  259. dbgln("Unrecoverable page fault, {}{}{} address {}",
  260. regs.exception_code & PageFaultFlags::ReservedBitViolation ? "reserved bit violation / " : "",
  261. regs.exception_code & PageFaultFlags::InstructionFetch ? "instruction fetch / " : "",
  262. regs.exception_code & PageFaultFlags::Write ? "write to" : "read from",
  263. VirtualAddress(fault_address));
  264. u32 malloc_scrub_pattern = explode_byte(MALLOC_SCRUB_BYTE);
  265. u32 free_scrub_pattern = explode_byte(FREE_SCRUB_BYTE);
  266. u32 kmalloc_scrub_pattern = explode_byte(KMALLOC_SCRUB_BYTE);
  267. u32 kfree_scrub_pattern = explode_byte(KFREE_SCRUB_BYTE);
  268. u32 slab_alloc_scrub_pattern = explode_byte(SLAB_ALLOC_SCRUB_BYTE);
  269. u32 slab_dealloc_scrub_pattern = explode_byte(SLAB_DEALLOC_SCRUB_BYTE);
  270. if ((fault_address & 0xffff0000) == (malloc_scrub_pattern & 0xffff0000)) {
  271. dbgln("Note: Address {} looks like it may be uninitialized malloc() memory", VirtualAddress(fault_address));
  272. } else if ((fault_address & 0xffff0000) == (free_scrub_pattern & 0xffff0000)) {
  273. dbgln("Note: Address {} looks like it may be recently free()'d memory", VirtualAddress(fault_address));
  274. } else if ((fault_address & 0xffff0000) == (kmalloc_scrub_pattern & 0xffff0000)) {
  275. dbgln("Note: Address {} looks like it may be uninitialized kmalloc() memory", VirtualAddress(fault_address));
  276. } else if ((fault_address & 0xffff0000) == (kfree_scrub_pattern & 0xffff0000)) {
  277. dbgln("Note: Address {} looks like it may be recently kfree()'d memory", VirtualAddress(fault_address));
  278. } else if ((fault_address & 0xffff0000) == (slab_alloc_scrub_pattern & 0xffff0000)) {
  279. dbgln("Note: Address {} looks like it may be uninitialized slab_alloc() memory", VirtualAddress(fault_address));
  280. } else if ((fault_address & 0xffff0000) == (slab_dealloc_scrub_pattern & 0xffff0000)) {
  281. dbgln("Note: Address {} looks like it may be recently slab_dealloc()'d memory", VirtualAddress(fault_address));
  282. } else if (fault_address < 4096) {
  283. dbgln("Note: Address {} looks like a possible nullptr dereference", VirtualAddress(fault_address));
  284. }
  285. handle_crash(regs, "Page Fault", SIGSEGV, response == PageFaultResponse::OutOfMemory);
  286. } else if (response == PageFaultResponse::Continue) {
  287. #if PAGE_FAULT_DEBUG
  288. dbgln("Continuing after resolved page fault");
  289. #endif
  290. } else {
  291. ASSERT_NOT_REACHED();
  292. }
  293. }
  294. EH_ENTRY_NO_CODE(1, debug);
  295. void debug_handler(TrapFrame* trap)
  296. {
  297. clac();
  298. auto& regs = *trap->regs;
  299. auto current_thread = Thread::current();
  300. auto& process = current_thread->process();
  301. if ((regs.cs & 3) == 0) {
  302. klog() << "Debug Exception in Ring0";
  303. Processor::halt();
  304. return;
  305. }
  306. constexpr u8 REASON_SINGLESTEP = 14;
  307. bool is_reason_singlestep = (read_dr6() & (1 << REASON_SINGLESTEP));
  308. if (!is_reason_singlestep)
  309. return;
  310. if (auto tracer = process.tracer()) {
  311. tracer->set_regs(regs);
  312. }
  313. current_thread->send_urgent_signal_to_self(SIGTRAP);
  314. }
  315. EH_ENTRY_NO_CODE(3, breakpoint);
  316. void breakpoint_handler(TrapFrame* trap)
  317. {
  318. clac();
  319. auto& regs = *trap->regs;
  320. auto current_thread = Thread::current();
  321. auto& process = current_thread->process();
  322. if ((regs.cs & 3) == 0) {
  323. klog() << "Breakpoint Trap in Ring0";
  324. Processor::halt();
  325. return;
  326. }
  327. if (auto tracer = process.tracer()) {
  328. tracer->set_regs(regs);
  329. }
  330. current_thread->send_urgent_signal_to_self(SIGTRAP);
  331. }
  332. #define EH(i, msg) \
  333. static void _exception##i() \
  334. { \
  335. klog() << msg; \
  336. u32 cr0, cr2, cr3, cr4; \
  337. asm("movl %%cr0, %%eax" \
  338. : "=a"(cr0)); \
  339. asm("movl %%cr2, %%eax" \
  340. : "=a"(cr2)); \
  341. asm("movl %%cr3, %%eax" \
  342. : "=a"(cr3)); \
  343. asm("movl %%cr4, %%eax" \
  344. : "=a"(cr4)); \
  345. klog() << "CR0=" << String::format("%x", cr0) << " CR2=" << String::format("%x", cr2) << " CR3=" << String::format("%x", cr3) << " CR4=" << String::format("%x", cr4); \
  346. Processor::halt(); \
  347. }
  348. EH(2, "Unknown error")
  349. EH(4, "Overflow")
  350. EH(5, "Bounds check")
  351. EH(8, "Double fault")
  352. EH(9, "Coprocessor segment overrun")
  353. EH(10, "Invalid TSS")
  354. EH(11, "Segment not present")
  355. EH(12, "Stack exception")
  356. EH(15, "Unknown error")
  357. EH(16, "Coprocessor error")
  358. const DescriptorTablePointer& get_idtr()
  359. {
  360. return s_idtr;
  361. }
  362. static void unimp_trap()
  363. {
  364. klog() << "Unhandled IRQ.";
  365. Processor::Processor::halt();
  366. }
  367. GenericInterruptHandler& get_interrupt_handler(u8 interrupt_number)
  368. {
  369. ASSERT(s_interrupt_handler[interrupt_number] != nullptr);
  370. return *s_interrupt_handler[interrupt_number];
  371. }
  372. static void revert_to_unused_handler(u8 interrupt_number)
  373. {
  374. new UnhandledInterruptHandler(interrupt_number);
  375. }
  376. void register_generic_interrupt_handler(u8 interrupt_number, GenericInterruptHandler& handler)
  377. {
  378. ASSERT(interrupt_number < GENERIC_INTERRUPT_HANDLERS_COUNT);
  379. if (s_interrupt_handler[interrupt_number] != nullptr) {
  380. if (s_interrupt_handler[interrupt_number]->type() == HandlerType::UnhandledInterruptHandler) {
  381. s_interrupt_handler[interrupt_number] = &handler;
  382. return;
  383. }
  384. if (s_interrupt_handler[interrupt_number]->is_shared_handler() && !s_interrupt_handler[interrupt_number]->is_sharing_with_others()) {
  385. ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::SharedIRQHandler);
  386. static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->register_handler(handler);
  387. return;
  388. }
  389. if (!s_interrupt_handler[interrupt_number]->is_shared_handler()) {
  390. if (s_interrupt_handler[interrupt_number]->type() == HandlerType::SpuriousInterruptHandler) {
  391. static_cast<SpuriousInterruptHandler*>(s_interrupt_handler[interrupt_number])->register_handler(handler);
  392. return;
  393. }
  394. ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::IRQHandler);
  395. auto& previous_handler = *s_interrupt_handler[interrupt_number];
  396. s_interrupt_handler[interrupt_number] = nullptr;
  397. SharedIRQHandler::initialize(interrupt_number);
  398. static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->register_handler(previous_handler);
  399. static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->register_handler(handler);
  400. return;
  401. }
  402. ASSERT_NOT_REACHED();
  403. } else {
  404. s_interrupt_handler[interrupt_number] = &handler;
  405. }
  406. }
  407. void unregister_generic_interrupt_handler(u8 interrupt_number, GenericInterruptHandler& handler)
  408. {
  409. ASSERT(s_interrupt_handler[interrupt_number] != nullptr);
  410. if (s_interrupt_handler[interrupt_number]->type() == HandlerType::UnhandledInterruptHandler) {
  411. dbgln("Trying to unregister unused handler (?)");
  412. return;
  413. }
  414. if (s_interrupt_handler[interrupt_number]->is_shared_handler() && !s_interrupt_handler[interrupt_number]->is_sharing_with_others()) {
  415. ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::SharedIRQHandler);
  416. static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->unregister_handler(handler);
  417. if (!static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->sharing_devices_count()) {
  418. revert_to_unused_handler(interrupt_number);
  419. }
  420. return;
  421. }
  422. if (!s_interrupt_handler[interrupt_number]->is_shared_handler()) {
  423. ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::IRQHandler);
  424. revert_to_unused_handler(interrupt_number);
  425. return;
  426. }
  427. ASSERT_NOT_REACHED();
  428. }
  429. void register_interrupt_handler(u8 index, void (*f)())
  430. {
  431. s_idt[index].low = 0x00080000 | LSW((f));
  432. s_idt[index].high = ((u32)(f)&0xffff0000) | 0x8e00;
  433. }
  434. void register_user_callable_interrupt_handler(u8 index, void (*f)())
  435. {
  436. s_idt[index].low = 0x00080000 | LSW((f));
  437. s_idt[index].high = ((u32)(f)&0xffff0000) | 0xef00;
  438. }
  439. void flush_idt()
  440. {
  441. asm("lidt %0" ::"m"(s_idtr));
  442. }
  443. static void idt_init()
  444. {
  445. s_idtr.address = s_idt;
  446. s_idtr.limit = 256 * 8 - 1;
  447. register_interrupt_handler(0x00, divide_error_asm_entry);
  448. register_user_callable_interrupt_handler(0x01, debug_asm_entry);
  449. register_interrupt_handler(0x02, _exception2);
  450. register_user_callable_interrupt_handler(0x03, breakpoint_asm_entry);
  451. register_interrupt_handler(0x04, _exception4);
  452. register_interrupt_handler(0x05, _exception5);
  453. register_interrupt_handler(0x06, illegal_instruction_asm_entry);
  454. register_interrupt_handler(0x07, fpu_exception_asm_entry);
  455. register_interrupt_handler(0x08, _exception8);
  456. register_interrupt_handler(0x09, _exception9);
  457. register_interrupt_handler(0x0a, _exception10);
  458. register_interrupt_handler(0x0b, _exception11);
  459. register_interrupt_handler(0x0c, _exception12);
  460. register_interrupt_handler(0x0d, general_protection_fault_asm_entry);
  461. register_interrupt_handler(0x0e, page_fault_asm_entry);
  462. register_interrupt_handler(0x0f, _exception15);
  463. register_interrupt_handler(0x10, _exception16);
  464. for (u8 i = 0x11; i < 0x50; i++)
  465. register_interrupt_handler(i, unimp_trap);
  466. register_interrupt_handler(0x50, interrupt_80_asm_entry);
  467. register_interrupt_handler(0x51, interrupt_81_asm_entry);
  468. register_interrupt_handler(0x52, interrupt_82_asm_entry);
  469. register_interrupt_handler(0x53, interrupt_83_asm_entry);
  470. register_interrupt_handler(0x54, interrupt_84_asm_entry);
  471. register_interrupt_handler(0x55, interrupt_85_asm_entry);
  472. register_interrupt_handler(0x56, interrupt_86_asm_entry);
  473. register_interrupt_handler(0x57, interrupt_87_asm_entry);
  474. register_interrupt_handler(0x58, interrupt_88_asm_entry);
  475. register_interrupt_handler(0x59, interrupt_89_asm_entry);
  476. register_interrupt_handler(0x5a, interrupt_90_asm_entry);
  477. register_interrupt_handler(0x5b, interrupt_91_asm_entry);
  478. register_interrupt_handler(0x5c, interrupt_92_asm_entry);
  479. register_interrupt_handler(0x5d, interrupt_93_asm_entry);
  480. register_interrupt_handler(0x5e, interrupt_94_asm_entry);
  481. register_interrupt_handler(0x5f, interrupt_95_asm_entry);
  482. register_interrupt_handler(0x60, interrupt_96_asm_entry);
  483. register_interrupt_handler(0x61, interrupt_97_asm_entry);
  484. register_interrupt_handler(0x62, interrupt_98_asm_entry);
  485. register_interrupt_handler(0x63, interrupt_99_asm_entry);
  486. register_interrupt_handler(0x64, interrupt_100_asm_entry);
  487. register_interrupt_handler(0x65, interrupt_101_asm_entry);
  488. register_interrupt_handler(0x66, interrupt_102_asm_entry);
  489. register_interrupt_handler(0x67, interrupt_103_asm_entry);
  490. register_interrupt_handler(0x68, interrupt_104_asm_entry);
  491. register_interrupt_handler(0x69, interrupt_105_asm_entry);
  492. register_interrupt_handler(0x6a, interrupt_106_asm_entry);
  493. register_interrupt_handler(0x6b, interrupt_107_asm_entry);
  494. register_interrupt_handler(0x6c, interrupt_108_asm_entry);
  495. register_interrupt_handler(0x6d, interrupt_109_asm_entry);
  496. register_interrupt_handler(0x6e, interrupt_110_asm_entry);
  497. register_interrupt_handler(0x6f, interrupt_111_asm_entry);
  498. register_interrupt_handler(0x70, interrupt_112_asm_entry);
  499. register_interrupt_handler(0x71, interrupt_113_asm_entry);
  500. register_interrupt_handler(0x72, interrupt_114_asm_entry);
  501. register_interrupt_handler(0x73, interrupt_115_asm_entry);
  502. register_interrupt_handler(0x74, interrupt_116_asm_entry);
  503. register_interrupt_handler(0x75, interrupt_117_asm_entry);
  504. register_interrupt_handler(0x76, interrupt_118_asm_entry);
  505. register_interrupt_handler(0x77, interrupt_119_asm_entry);
  506. register_interrupt_handler(0x78, interrupt_120_asm_entry);
  507. register_interrupt_handler(0x79, interrupt_121_asm_entry);
  508. register_interrupt_handler(0x7a, interrupt_122_asm_entry);
  509. register_interrupt_handler(0x7b, interrupt_123_asm_entry);
  510. register_interrupt_handler(0x7c, interrupt_124_asm_entry);
  511. register_interrupt_handler(0x7d, interrupt_125_asm_entry);
  512. register_interrupt_handler(0x7e, interrupt_126_asm_entry);
  513. register_interrupt_handler(0x7f, interrupt_127_asm_entry);
  514. register_interrupt_handler(0x80, interrupt_128_asm_entry);
  515. register_interrupt_handler(0x81, interrupt_129_asm_entry);
  516. register_interrupt_handler(0x82, interrupt_130_asm_entry);
  517. register_interrupt_handler(0x83, interrupt_131_asm_entry);
  518. register_interrupt_handler(0x84, interrupt_132_asm_entry);
  519. register_interrupt_handler(0x85, interrupt_133_asm_entry);
  520. register_interrupt_handler(0x86, interrupt_134_asm_entry);
  521. register_interrupt_handler(0x87, interrupt_135_asm_entry);
  522. register_interrupt_handler(0x88, interrupt_136_asm_entry);
  523. register_interrupt_handler(0x89, interrupt_137_asm_entry);
  524. register_interrupt_handler(0x8a, interrupt_138_asm_entry);
  525. register_interrupt_handler(0x8b, interrupt_139_asm_entry);
  526. register_interrupt_handler(0x8c, interrupt_140_asm_entry);
  527. register_interrupt_handler(0x8d, interrupt_141_asm_entry);
  528. register_interrupt_handler(0x8e, interrupt_142_asm_entry);
  529. register_interrupt_handler(0x8f, interrupt_143_asm_entry);
  530. register_interrupt_handler(0x90, interrupt_144_asm_entry);
  531. register_interrupt_handler(0x91, interrupt_145_asm_entry);
  532. register_interrupt_handler(0x92, interrupt_146_asm_entry);
  533. register_interrupt_handler(0x93, interrupt_147_asm_entry);
  534. register_interrupt_handler(0x94, interrupt_148_asm_entry);
  535. register_interrupt_handler(0x95, interrupt_149_asm_entry);
  536. register_interrupt_handler(0x96, interrupt_150_asm_entry);
  537. register_interrupt_handler(0x97, interrupt_151_asm_entry);
  538. register_interrupt_handler(0x98, interrupt_152_asm_entry);
  539. register_interrupt_handler(0x99, interrupt_153_asm_entry);
  540. register_interrupt_handler(0x9a, interrupt_154_asm_entry);
  541. register_interrupt_handler(0x9b, interrupt_155_asm_entry);
  542. register_interrupt_handler(0x9c, interrupt_156_asm_entry);
  543. register_interrupt_handler(0x9d, interrupt_157_asm_entry);
  544. register_interrupt_handler(0x9e, interrupt_158_asm_entry);
  545. register_interrupt_handler(0x9f, interrupt_159_asm_entry);
  546. register_interrupt_handler(0xa0, interrupt_160_asm_entry);
  547. register_interrupt_handler(0xa1, interrupt_161_asm_entry);
  548. register_interrupt_handler(0xa2, interrupt_162_asm_entry);
  549. register_interrupt_handler(0xa3, interrupt_163_asm_entry);
  550. register_interrupt_handler(0xa4, interrupt_164_asm_entry);
  551. register_interrupt_handler(0xa5, interrupt_165_asm_entry);
  552. register_interrupt_handler(0xa6, interrupt_166_asm_entry);
  553. register_interrupt_handler(0xa7, interrupt_167_asm_entry);
  554. register_interrupt_handler(0xa8, interrupt_168_asm_entry);
  555. register_interrupt_handler(0xa9, interrupt_169_asm_entry);
  556. register_interrupt_handler(0xaa, interrupt_170_asm_entry);
  557. register_interrupt_handler(0xab, interrupt_171_asm_entry);
  558. register_interrupt_handler(0xac, interrupt_172_asm_entry);
  559. register_interrupt_handler(0xad, interrupt_173_asm_entry);
  560. register_interrupt_handler(0xae, interrupt_174_asm_entry);
  561. register_interrupt_handler(0xaf, interrupt_175_asm_entry);
  562. register_interrupt_handler(0xb0, interrupt_176_asm_entry);
  563. register_interrupt_handler(0xb1, interrupt_177_asm_entry);
  564. register_interrupt_handler(0xb2, interrupt_178_asm_entry);
  565. register_interrupt_handler(0xb3, interrupt_179_asm_entry);
  566. register_interrupt_handler(0xb4, interrupt_180_asm_entry);
  567. register_interrupt_handler(0xb5, interrupt_181_asm_entry);
  568. register_interrupt_handler(0xb6, interrupt_182_asm_entry);
  569. register_interrupt_handler(0xb7, interrupt_183_asm_entry);
  570. register_interrupt_handler(0xb8, interrupt_184_asm_entry);
  571. register_interrupt_handler(0xb9, interrupt_185_asm_entry);
  572. register_interrupt_handler(0xba, interrupt_186_asm_entry);
  573. register_interrupt_handler(0xbb, interrupt_187_asm_entry);
  574. register_interrupt_handler(0xbc, interrupt_188_asm_entry);
  575. register_interrupt_handler(0xbd, interrupt_189_asm_entry);
  576. register_interrupt_handler(0xbe, interrupt_190_asm_entry);
  577. register_interrupt_handler(0xbf, interrupt_191_asm_entry);
  578. register_interrupt_handler(0xc0, interrupt_192_asm_entry);
  579. register_interrupt_handler(0xc1, interrupt_193_asm_entry);
  580. register_interrupt_handler(0xc2, interrupt_194_asm_entry);
  581. register_interrupt_handler(0xc3, interrupt_195_asm_entry);
  582. register_interrupt_handler(0xc4, interrupt_196_asm_entry);
  583. register_interrupt_handler(0xc5, interrupt_197_asm_entry);
  584. register_interrupt_handler(0xc6, interrupt_198_asm_entry);
  585. register_interrupt_handler(0xc7, interrupt_199_asm_entry);
  586. register_interrupt_handler(0xc8, interrupt_200_asm_entry);
  587. register_interrupt_handler(0xc9, interrupt_201_asm_entry);
  588. register_interrupt_handler(0xca, interrupt_202_asm_entry);
  589. register_interrupt_handler(0xcb, interrupt_203_asm_entry);
  590. register_interrupt_handler(0xcc, interrupt_204_asm_entry);
  591. register_interrupt_handler(0xcd, interrupt_205_asm_entry);
  592. register_interrupt_handler(0xce, interrupt_206_asm_entry);
  593. register_interrupt_handler(0xcf, interrupt_207_asm_entry);
  594. register_interrupt_handler(0xd0, interrupt_208_asm_entry);
  595. register_interrupt_handler(0xd1, interrupt_209_asm_entry);
  596. register_interrupt_handler(0xd2, interrupt_210_asm_entry);
  597. register_interrupt_handler(0xd3, interrupt_211_asm_entry);
  598. register_interrupt_handler(0xd4, interrupt_212_asm_entry);
  599. register_interrupt_handler(0xd5, interrupt_213_asm_entry);
  600. register_interrupt_handler(0xd6, interrupt_214_asm_entry);
  601. register_interrupt_handler(0xd7, interrupt_215_asm_entry);
  602. register_interrupt_handler(0xd8, interrupt_216_asm_entry);
  603. register_interrupt_handler(0xd9, interrupt_217_asm_entry);
  604. register_interrupt_handler(0xda, interrupt_218_asm_entry);
  605. register_interrupt_handler(0xdb, interrupt_219_asm_entry);
  606. register_interrupt_handler(0xdc, interrupt_220_asm_entry);
  607. register_interrupt_handler(0xdd, interrupt_221_asm_entry);
  608. register_interrupt_handler(0xde, interrupt_222_asm_entry);
  609. register_interrupt_handler(0xdf, interrupt_223_asm_entry);
  610. register_interrupt_handler(0xe0, interrupt_224_asm_entry);
  611. register_interrupt_handler(0xe1, interrupt_225_asm_entry);
  612. register_interrupt_handler(0xe2, interrupt_226_asm_entry);
  613. register_interrupt_handler(0xe3, interrupt_227_asm_entry);
  614. register_interrupt_handler(0xe4, interrupt_228_asm_entry);
  615. register_interrupt_handler(0xe5, interrupt_229_asm_entry);
  616. register_interrupt_handler(0xe6, interrupt_230_asm_entry);
  617. register_interrupt_handler(0xe7, interrupt_231_asm_entry);
  618. register_interrupt_handler(0xe8, interrupt_232_asm_entry);
  619. register_interrupt_handler(0xe9, interrupt_233_asm_entry);
  620. register_interrupt_handler(0xea, interrupt_234_asm_entry);
  621. register_interrupt_handler(0xeb, interrupt_235_asm_entry);
  622. register_interrupt_handler(0xec, interrupt_236_asm_entry);
  623. register_interrupt_handler(0xed, interrupt_237_asm_entry);
  624. register_interrupt_handler(0xee, interrupt_238_asm_entry);
  625. register_interrupt_handler(0xef, interrupt_239_asm_entry);
  626. register_interrupt_handler(0xf0, interrupt_240_asm_entry);
  627. register_interrupt_handler(0xf1, interrupt_241_asm_entry);
  628. register_interrupt_handler(0xf2, interrupt_242_asm_entry);
  629. register_interrupt_handler(0xf3, interrupt_243_asm_entry);
  630. register_interrupt_handler(0xf4, interrupt_244_asm_entry);
  631. register_interrupt_handler(0xf5, interrupt_245_asm_entry);
  632. register_interrupt_handler(0xf6, interrupt_246_asm_entry);
  633. register_interrupt_handler(0xf7, interrupt_247_asm_entry);
  634. register_interrupt_handler(0xf8, interrupt_248_asm_entry);
  635. register_interrupt_handler(0xf9, interrupt_249_asm_entry);
  636. register_interrupt_handler(0xfa, interrupt_250_asm_entry);
  637. register_interrupt_handler(0xfb, interrupt_251_asm_entry);
  638. register_interrupt_handler(0xfc, interrupt_252_asm_entry);
  639. register_interrupt_handler(0xfd, interrupt_253_asm_entry);
  640. register_interrupt_handler(0xfe, interrupt_254_asm_entry);
  641. register_interrupt_handler(0xff, interrupt_255_asm_entry);
  642. dbgln("Installing Unhandled Handlers");
  643. for (u8 i = 0; i < GENERIC_INTERRUPT_HANDLERS_COUNT; ++i) {
  644. new UnhandledInterruptHandler(i);
  645. }
  646. flush_idt();
  647. }
  648. void load_task_register(u16 selector)
  649. {
  650. asm("ltr %0" ::"r"(selector));
  651. }
  652. void handle_interrupt(TrapFrame* trap)
  653. {
  654. clac();
  655. auto& regs = *trap->regs;
  656. ASSERT(regs.isr_number >= IRQ_VECTOR_BASE && regs.isr_number <= (IRQ_VECTOR_BASE + GENERIC_INTERRUPT_HANDLERS_COUNT));
  657. u8 irq = (u8)(regs.isr_number - 0x50);
  658. s_entropy_source_interrupts.add_random_event(irq);
  659. auto* handler = s_interrupt_handler[irq];
  660. ASSERT(handler);
  661. handler->increment_invoking_counter();
  662. handler->handle_interrupt(regs);
  663. handler->eoi();
  664. }
  665. void enter_trap_no_irq(TrapFrame* trap)
  666. {
  667. InterruptDisabler disable;
  668. Processor::current().enter_trap(*trap, false);
  669. }
  670. void enter_trap(TrapFrame* trap)
  671. {
  672. InterruptDisabler disable;
  673. Processor::current().enter_trap(*trap, true);
  674. }
  675. void exit_trap(TrapFrame* trap)
  676. {
  677. InterruptDisabler disable;
  678. return Processor::current().exit_trap(*trap);
  679. }
  680. static void sse_init()
  681. {
  682. asm volatile(
  683. "mov %cr0, %eax\n"
  684. "andl $0xfffffffb, %eax\n"
  685. "orl $0x2, %eax\n"
  686. "mov %eax, %cr0\n"
  687. "mov %cr4, %eax\n"
  688. "orl $0x600, %eax\n"
  689. "mov %eax, %cr4\n");
  690. }
  691. u32 read_cr0()
  692. {
  693. u32 cr0;
  694. asm("movl %%cr0, %%eax"
  695. : "=a"(cr0));
  696. return cr0;
  697. }
  698. u32 read_cr3()
  699. {
  700. u32 cr3;
  701. asm("movl %%cr3, %%eax"
  702. : "=a"(cr3));
  703. return cr3;
  704. }
  705. void write_cr3(u32 cr3)
  706. {
  707. // NOTE: If you're here from a GPF crash, it's very likely that a PDPT entry is incorrect, not this!
  708. asm volatile("movl %%eax, %%cr3" ::"a"(cr3)
  709. : "memory");
  710. }
  711. u32 read_cr4()
  712. {
  713. u32 cr4;
  714. asm("movl %%cr4, %%eax"
  715. : "=a"(cr4));
  716. return cr4;
  717. }
  718. u32 read_dr6()
  719. {
  720. u32 dr6;
  721. asm("movl %%dr6, %%eax"
  722. : "=a"(dr6));
  723. return dr6;
  724. }
  725. FPUState Processor::s_clean_fpu_state;
  726. static Vector<Processor*>* s_processors;
  727. static SpinLock s_processor_lock;
  728. volatile u32 Processor::g_total_processors;
  729. static volatile bool s_smp_enabled;
  730. Vector<Processor*>& Processor::processors()
  731. {
  732. ASSERT(s_processors);
  733. return *s_processors;
  734. }
  735. Processor& Processor::by_id(u32 cpu)
  736. {
  737. // s_processors does not need to be protected by a lock of any kind.
  738. // It is populated early in the boot process, and the BSP is waiting
  739. // for all APs to finish, after which this array never gets modified
  740. // again, so it's safe to not protect access to it here
  741. auto& procs = processors();
  742. ASSERT(procs[cpu] != nullptr);
  743. ASSERT(procs.size() > cpu);
  744. return *procs[cpu];
  745. }
  746. [[noreturn]] static inline void halt_this()
  747. {
  748. for (;;) {
  749. asm volatile("cli; hlt");
  750. }
  751. }
  752. void Processor::cpu_detect()
  753. {
  754. // NOTE: This is called during Processor::early_initialize, we cannot
  755. // safely log at this point because we don't have kmalloc
  756. // initialized yet!
  757. auto set_feature =
  758. [&](CPUFeature f) {
  759. m_features = static_cast<CPUFeature>(static_cast<u32>(m_features) | static_cast<u32>(f));
  760. };
  761. m_features = static_cast<CPUFeature>(0);
  762. CPUID processor_info(0x1);
  763. if (processor_info.edx() & (1 << 4))
  764. set_feature(CPUFeature::TSC);
  765. if (processor_info.edx() & (1 << 6))
  766. set_feature(CPUFeature::PAE);
  767. if (processor_info.edx() & (1 << 13))
  768. set_feature(CPUFeature::PGE);
  769. if (processor_info.edx() & (1 << 23))
  770. set_feature(CPUFeature::MMX);
  771. if (processor_info.edx() & (1 << 25))
  772. set_feature(CPUFeature::SSE);
  773. if (processor_info.edx() & (1 << 26))
  774. set_feature(CPUFeature::SSE2);
  775. if (processor_info.ecx() & (1 << 0))
  776. set_feature(CPUFeature::SSE3);
  777. if (processor_info.ecx() & (1 << 9))
  778. set_feature(CPUFeature::SSSE3);
  779. if (processor_info.ecx() & (1 << 19))
  780. set_feature(CPUFeature::SSE4_1);
  781. if (processor_info.ecx() & (1 << 20))
  782. set_feature(CPUFeature::SSE4_2);
  783. if (processor_info.ecx() & (1 << 30))
  784. set_feature(CPUFeature::RDRAND);
  785. if (processor_info.edx() & (1 << 11)) {
  786. u32 stepping = processor_info.eax() & 0xf;
  787. u32 model = (processor_info.eax() >> 4) & 0xf;
  788. u32 family = (processor_info.eax() >> 8) & 0xf;
  789. if (!(family == 6 && model < 3 && stepping < 3))
  790. set_feature(CPUFeature::SEP);
  791. if ((family == 6 && model >= 3) || (family == 0xf && model >= 0xe))
  792. set_feature(CPUFeature::CONSTANT_TSC);
  793. }
  794. u32 max_extended_leaf = CPUID(0x80000000).eax();
  795. ASSERT(max_extended_leaf >= 0x80000001);
  796. CPUID extended_processor_info(0x80000001);
  797. if (extended_processor_info.edx() & (1 << 20))
  798. set_feature(CPUFeature::NX);
  799. if (extended_processor_info.edx() & (1 << 27))
  800. set_feature(CPUFeature::RDTSCP);
  801. if (extended_processor_info.edx() & (1 << 11)) {
  802. // Only available in 64 bit mode
  803. set_feature(CPUFeature::SYSCALL);
  804. }
  805. if (max_extended_leaf >= 0x80000007) {
  806. CPUID cpuid(0x80000007);
  807. if (cpuid.edx() & (1 << 8)) {
  808. set_feature(CPUFeature::CONSTANT_TSC);
  809. set_feature(CPUFeature::NONSTOP_TSC);
  810. }
  811. }
  812. if (max_extended_leaf >= 0x80000008) {
  813. // CPUID.80000008H:EAX[7:0] reports the physical-address width supported by the processor.
  814. CPUID cpuid(0x80000008);
  815. m_physical_address_bit_width = cpuid.eax() & 0xff;
  816. } else {
  817. // 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.
  818. m_physical_address_bit_width = has_feature(CPUFeature::PAE) ? 36 : 32;
  819. }
  820. CPUID extended_features(0x7);
  821. if (extended_features.ebx() & (1 << 20))
  822. set_feature(CPUFeature::SMAP);
  823. if (extended_features.ebx() & (1 << 7))
  824. set_feature(CPUFeature::SMEP);
  825. if (extended_features.ecx() & (1 << 2))
  826. set_feature(CPUFeature::UMIP);
  827. if (extended_features.ebx() & (1 << 18))
  828. set_feature(CPUFeature::RDSEED);
  829. }
  830. void Processor::cpu_setup()
  831. {
  832. // NOTE: This is called during Processor::early_initialize, we cannot
  833. // safely log at this point because we don't have kmalloc
  834. // initialized yet!
  835. cpu_detect();
  836. if (has_feature(CPUFeature::SSE))
  837. sse_init();
  838. asm volatile(
  839. "movl %%cr0, %%eax\n"
  840. "orl $0x00010000, %%eax\n"
  841. "movl %%eax, %%cr0\n" ::
  842. : "%eax", "memory");
  843. if (has_feature(CPUFeature::PGE)) {
  844. // Turn on CR4.PGE so the CPU will respect the G bit in page tables.
  845. asm volatile(
  846. "mov %cr4, %eax\n"
  847. "orl $0x80, %eax\n"
  848. "mov %eax, %cr4\n");
  849. }
  850. if (has_feature(CPUFeature::NX)) {
  851. // Turn on IA32_EFER.NXE
  852. asm volatile(
  853. "movl $0xc0000080, %ecx\n"
  854. "rdmsr\n"
  855. "orl $0x800, %eax\n"
  856. "wrmsr\n");
  857. }
  858. if (has_feature(CPUFeature::SMEP)) {
  859. // Turn on CR4.SMEP
  860. asm volatile(
  861. "mov %cr4, %eax\n"
  862. "orl $0x100000, %eax\n"
  863. "mov %eax, %cr4\n");
  864. }
  865. if (has_feature(CPUFeature::SMAP)) {
  866. // Turn on CR4.SMAP
  867. asm volatile(
  868. "mov %cr4, %eax\n"
  869. "orl $0x200000, %eax\n"
  870. "mov %eax, %cr4\n");
  871. }
  872. if (has_feature(CPUFeature::UMIP)) {
  873. asm volatile(
  874. "mov %cr4, %eax\n"
  875. "orl $0x800, %eax\n"
  876. "mov %eax, %cr4\n");
  877. }
  878. if (has_feature(CPUFeature::TSC)) {
  879. asm volatile(
  880. "mov %cr4, %eax\n"
  881. "orl $0x4, %eax\n"
  882. "mov %eax, %cr4\n");
  883. }
  884. }
  885. String Processor::features_string() const
  886. {
  887. StringBuilder builder;
  888. auto feature_to_str =
  889. [](CPUFeature f) -> const char* {
  890. switch (f) {
  891. case CPUFeature::NX:
  892. return "nx";
  893. case CPUFeature::PAE:
  894. return "pae";
  895. case CPUFeature::PGE:
  896. return "pge";
  897. case CPUFeature::RDRAND:
  898. return "rdrand";
  899. case CPUFeature::RDSEED:
  900. return "rdseed";
  901. case CPUFeature::SMAP:
  902. return "smap";
  903. case CPUFeature::SMEP:
  904. return "smep";
  905. case CPUFeature::SSE:
  906. return "sse";
  907. case CPUFeature::TSC:
  908. return "tsc";
  909. case CPUFeature::RDTSCP:
  910. return "rdtscp";
  911. case CPUFeature::CONSTANT_TSC:
  912. return "constant_tsc";
  913. case CPUFeature::NONSTOP_TSC:
  914. return "nonstop_tsc";
  915. case CPUFeature::UMIP:
  916. return "umip";
  917. case CPUFeature::SEP:
  918. return "sep";
  919. case CPUFeature::SYSCALL:
  920. return "syscall";
  921. case CPUFeature::MMX:
  922. return "mmx";
  923. case CPUFeature::SSE2:
  924. return "sse2";
  925. case CPUFeature::SSE3:
  926. return "sse3";
  927. case CPUFeature::SSSE3:
  928. return "ssse3";
  929. case CPUFeature::SSE4_1:
  930. return "sse4.1";
  931. case CPUFeature::SSE4_2:
  932. return "sse4.2";
  933. // no default statement here intentionally so that we get
  934. // a warning if a new feature is forgotten to be added here
  935. }
  936. // Shouldn't ever happen
  937. return "???";
  938. };
  939. bool first = true;
  940. for (u32 flag = 1; flag != 0; flag <<= 1) {
  941. if ((static_cast<u32>(m_features) & flag) != 0) {
  942. if (first)
  943. first = false;
  944. else
  945. builder.append(' ');
  946. auto str = feature_to_str(static_cast<CPUFeature>(flag));
  947. builder.append(str, strlen(str));
  948. }
  949. }
  950. return builder.build();
  951. }
  952. void Processor::early_initialize(u32 cpu)
  953. {
  954. m_self = this;
  955. m_cpu = cpu;
  956. m_in_irq = 0;
  957. m_in_critical = 0;
  958. m_invoke_scheduler_async = false;
  959. m_scheduler_initialized = false;
  960. m_message_queue = nullptr;
  961. m_idle_thread = nullptr;
  962. m_current_thread = nullptr;
  963. m_scheduler_data = nullptr;
  964. m_mm_data = nullptr;
  965. m_info = nullptr;
  966. m_halt_requested = false;
  967. if (cpu == 0) {
  968. s_smp_enabled = false;
  969. atomic_store(&g_total_processors, 1u, AK::MemoryOrder::memory_order_release);
  970. } else {
  971. atomic_fetch_add(&g_total_processors, 1u, AK::MemoryOrder::memory_order_acq_rel);
  972. }
  973. deferred_call_pool_init();
  974. cpu_setup();
  975. gdt_init();
  976. ASSERT(is_initialized()); // sanity check
  977. ASSERT(&current() == this); // sanity check
  978. }
  979. void Processor::initialize(u32 cpu)
  980. {
  981. ASSERT(m_self == this);
  982. ASSERT(&current() == this); // sanity check
  983. klog() << "CPU[" << id() << "]: Supported features: " << features_string();
  984. if (!has_feature(CPUFeature::RDRAND))
  985. klog() << "CPU[" << id() << "]: No RDRAND support detected, randomness will be poor";
  986. klog() << "CPU[" << id() << "]: Physical address bit width: " << m_physical_address_bit_width;
  987. if (cpu == 0)
  988. idt_init();
  989. else
  990. flush_idt();
  991. if (cpu == 0) {
  992. ASSERT((FlatPtr(&s_clean_fpu_state) & 0xF) == 0);
  993. asm volatile("fninit");
  994. asm volatile("fxsave %0"
  995. : "=m"(s_clean_fpu_state));
  996. }
  997. m_info = new ProcessorInfo(*this);
  998. {
  999. ScopedSpinLock lock(s_processor_lock);
  1000. // We need to prevent races between APs starting up at the same time
  1001. if (!s_processors)
  1002. s_processors = new Vector<Processor*>();
  1003. if (cpu >= s_processors->size())
  1004. s_processors->resize(cpu + 1);
  1005. (*s_processors)[cpu] = this;
  1006. }
  1007. }
  1008. void Processor::write_raw_gdt_entry(u16 selector, u32 low, u32 high)
  1009. {
  1010. u16 i = (selector & 0xfffc) >> 3;
  1011. u32 prev_gdt_length = m_gdt_length;
  1012. if (i > m_gdt_length) {
  1013. m_gdt_length = i + 1;
  1014. ASSERT(m_gdt_length <= sizeof(m_gdt) / sizeof(m_gdt[0]));
  1015. m_gdtr.limit = (m_gdt_length + 1) * 8 - 1;
  1016. }
  1017. m_gdt[i].low = low;
  1018. m_gdt[i].high = high;
  1019. // clear selectors we may have skipped
  1020. while (i < prev_gdt_length) {
  1021. m_gdt[i].low = 0;
  1022. m_gdt[i].high = 0;
  1023. i++;
  1024. }
  1025. }
  1026. void Processor::write_gdt_entry(u16 selector, Descriptor& descriptor)
  1027. {
  1028. write_raw_gdt_entry(selector, descriptor.low, descriptor.high);
  1029. }
  1030. Descriptor& Processor::get_gdt_entry(u16 selector)
  1031. {
  1032. u16 i = (selector & 0xfffc) >> 3;
  1033. return *(Descriptor*)(&m_gdt[i]);
  1034. }
  1035. void Processor::flush_gdt()
  1036. {
  1037. m_gdtr.address = m_gdt;
  1038. m_gdtr.limit = (m_gdt_length * 8) - 1;
  1039. asm volatile("lgdt %0" ::"m"(m_gdtr)
  1040. : "memory");
  1041. }
  1042. const DescriptorTablePointer& Processor::get_gdtr()
  1043. {
  1044. return m_gdtr;
  1045. }
  1046. Vector<FlatPtr> Processor::capture_stack_trace(Thread& thread, size_t max_frames)
  1047. {
  1048. FlatPtr frame_ptr = 0, eip = 0;
  1049. Vector<FlatPtr, 32> stack_trace;
  1050. auto walk_stack = [&](FlatPtr stack_ptr) {
  1051. static constexpr size_t max_stack_frames = 4096;
  1052. stack_trace.append(eip);
  1053. size_t count = 1;
  1054. while (stack_ptr && stack_trace.size() < max_stack_frames) {
  1055. FlatPtr retaddr;
  1056. count++;
  1057. if (max_frames != 0 && count > max_frames)
  1058. break;
  1059. if (is_user_range(VirtualAddress(stack_ptr), sizeof(FlatPtr) * 2)) {
  1060. if (!copy_from_user(&retaddr, &((FlatPtr*)stack_ptr)[1]) || !retaddr)
  1061. break;
  1062. stack_trace.append(retaddr);
  1063. if (!copy_from_user(&stack_ptr, (FlatPtr*)stack_ptr))
  1064. break;
  1065. } else {
  1066. void* fault_at;
  1067. if (!safe_memcpy(&retaddr, &((FlatPtr*)stack_ptr)[1], sizeof(FlatPtr), fault_at) || !retaddr)
  1068. break;
  1069. stack_trace.append(retaddr);
  1070. if (!safe_memcpy(&stack_ptr, (FlatPtr*)stack_ptr, sizeof(FlatPtr), fault_at))
  1071. break;
  1072. }
  1073. }
  1074. };
  1075. auto capture_current_thread = [&]() {
  1076. frame_ptr = (FlatPtr)__builtin_frame_address(0);
  1077. eip = (FlatPtr)__builtin_return_address(0);
  1078. walk_stack(frame_ptr);
  1079. };
  1080. // Since the thread may be running on another processor, there
  1081. // is a chance a context switch may happen while we're trying
  1082. // to get it. It also won't be entirely accurate and merely
  1083. // reflect the status at the last context switch.
  1084. ScopedSpinLock lock(g_scheduler_lock);
  1085. if (&thread == Processor::current_thread()) {
  1086. ASSERT(thread.state() == Thread::Running);
  1087. // Leave the scheduler lock. If we trigger page faults we may
  1088. // need to be preempted. Since this is our own thread it won't
  1089. // cause any problems as the stack won't change below this frame.
  1090. lock.unlock();
  1091. capture_current_thread();
  1092. } else if (thread.is_active()) {
  1093. ASSERT(thread.cpu() != Processor::id());
  1094. // If this is the case, the thread is currently running
  1095. // on another processor. We can't trust the kernel stack as
  1096. // it may be changing at any time. We need to probably send
  1097. // an IPI to that processor, have it walk the stack and wait
  1098. // until it returns the data back to us
  1099. auto& proc = Processor::current();
  1100. smp_unicast(
  1101. thread.cpu(),
  1102. [&]() {
  1103. dbgln("CPU[{}] getting stack for cpu #{}", Processor::id(), proc.get_id());
  1104. ProcessPagingScope paging_scope(thread.process());
  1105. ASSERT(&Processor::current() != &proc);
  1106. ASSERT(&thread == Processor::current_thread());
  1107. // NOTE: Because the other processor is still holding the
  1108. // scheduler lock while waiting for this callback to finish,
  1109. // the current thread on the target processor cannot change
  1110. // TODO: What to do about page faults here? We might deadlock
  1111. // because the other processor is still holding the
  1112. // scheduler lock...
  1113. capture_current_thread();
  1114. },
  1115. false);
  1116. } else {
  1117. switch (thread.state()) {
  1118. case Thread::Running:
  1119. ASSERT_NOT_REACHED(); // should have been handled above
  1120. case Thread::Runnable:
  1121. case Thread::Stopped:
  1122. case Thread::Blocked:
  1123. case Thread::Dying:
  1124. case Thread::Dead: {
  1125. // We need to retrieve ebp from what was last pushed to the kernel
  1126. // stack. Before switching out of that thread, it switch_context
  1127. // pushed the callee-saved registers, and the last of them happens
  1128. // to be ebp.
  1129. ProcessPagingScope paging_scope(thread.process());
  1130. auto& tss = thread.tss();
  1131. u32* stack_top = reinterpret_cast<u32*>(tss.esp);
  1132. if (is_user_range(VirtualAddress(stack_top), sizeof(FlatPtr))) {
  1133. if (!copy_from_user(&frame_ptr, &((FlatPtr*)stack_top)[0]))
  1134. frame_ptr = 0;
  1135. } else {
  1136. void* fault_at;
  1137. if (!safe_memcpy(&frame_ptr, &((FlatPtr*)stack_top)[0], sizeof(FlatPtr), fault_at))
  1138. frame_ptr = 0;
  1139. }
  1140. eip = tss.eip;
  1141. // TODO: We need to leave the scheduler lock here, but we also
  1142. // need to prevent the target thread from being run while
  1143. // we walk the stack
  1144. lock.unlock();
  1145. walk_stack(frame_ptr);
  1146. break;
  1147. }
  1148. default:
  1149. dbgln("Cannot capture stack trace for thread {} in state {}", thread, thread.state_string());
  1150. break;
  1151. }
  1152. }
  1153. return stack_trace;
  1154. }
  1155. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
  1156. {
  1157. ASSERT(from_thread == to_thread || from_thread->state() != Thread::Running);
  1158. ASSERT(to_thread->state() == Thread::Running);
  1159. Processor::set_current_thread(*to_thread);
  1160. auto& from_tss = from_thread->tss();
  1161. auto& to_tss = to_thread->tss();
  1162. asm volatile("fxsave %0"
  1163. : "=m"(from_thread->fpu_state()));
  1164. from_tss.fs = get_fs();
  1165. from_tss.gs = get_gs();
  1166. set_fs(to_tss.fs);
  1167. set_gs(to_tss.gs);
  1168. auto& processor = Processor::current();
  1169. auto& tls_descriptor = processor.get_gdt_entry(GDT_SELECTOR_TLS);
  1170. tls_descriptor.set_base(to_thread->thread_specific_data().as_ptr());
  1171. tls_descriptor.set_limit(to_thread->thread_specific_region_size());
  1172. if (from_tss.cr3 != to_tss.cr3)
  1173. write_cr3(to_tss.cr3);
  1174. to_thread->set_cpu(processor.get_id());
  1175. processor.restore_in_critical(to_thread->saved_critical());
  1176. asm volatile("fxrstor %0" ::"m"(to_thread->fpu_state()));
  1177. // TODO: debug registers
  1178. // TODO: ioperm?
  1179. }
  1180. #define ENTER_THREAD_CONTEXT_ARGS_SIZE (2 * 4) // to_thread, from_thread
  1181. void Processor::switch_context(Thread*& from_thread, Thread*& to_thread)
  1182. {
  1183. ASSERT(!in_irq());
  1184. ASSERT(m_in_critical == 1);
  1185. ASSERT(is_kernel_mode());
  1186. dbgln_if(CONTEXT_SWITCH_DEBUG, "switch_context --> switching out of: {} {}", VirtualAddress(from_thread), *from_thread);
  1187. from_thread->save_critical(m_in_critical);
  1188. // clang-format off
  1189. // Switch to new thread context, passing from_thread and to_thread
  1190. // through to the new context using registers edx and eax
  1191. asm volatile(
  1192. // NOTE: changing how much we push to the stack affects
  1193. // SWITCH_CONTEXT_TO_STACK_SIZE and thread_context_first_enter()!
  1194. "pushfl \n"
  1195. "pushl %%ebx \n"
  1196. "pushl %%esi \n"
  1197. "pushl %%edi \n"
  1198. "pushl %%ebp \n"
  1199. "movl %%esp, %[from_esp] \n"
  1200. "movl $1f, %[from_eip] \n"
  1201. "movl %[to_esp0], %%ebx \n"
  1202. "movl %%ebx, %[tss_esp0] \n"
  1203. "movl %[to_esp], %%esp \n"
  1204. "pushl %[to_thread] \n"
  1205. "pushl %[from_thread] \n"
  1206. "pushl %[to_eip] \n"
  1207. "cld \n"
  1208. "jmp enter_thread_context \n"
  1209. "1: \n"
  1210. "popl %%edx \n"
  1211. "popl %%eax \n"
  1212. "popl %%ebp \n"
  1213. "popl %%edi \n"
  1214. "popl %%esi \n"
  1215. "popl %%ebx \n"
  1216. "popfl \n"
  1217. : [from_esp] "=m" (from_thread->tss().esp),
  1218. [from_eip] "=m" (from_thread->tss().eip),
  1219. [tss_esp0] "=m" (m_tss.esp0),
  1220. "=d" (from_thread), // needed so that from_thread retains the correct value
  1221. "=a" (to_thread) // needed so that to_thread retains the correct value
  1222. : [to_esp] "g" (to_thread->tss().esp),
  1223. [to_esp0] "g" (to_thread->tss().esp0),
  1224. [to_eip] "c" (to_thread->tss().eip),
  1225. [from_thread] "d" (from_thread),
  1226. [to_thread] "a" (to_thread)
  1227. : "memory"
  1228. );
  1229. // clang-format on
  1230. dbgln_if(CONTEXT_SWITCH_DEBUG, "switch_context <-- from {} {} to {} {}", VirtualAddress(from_thread), *from_thread, VirtualAddress(to_thread), *to_thread);
  1231. Processor::current().restore_in_critical(to_thread->saved_critical());
  1232. }
  1233. extern "C" void context_first_init([[maybe_unused]] Thread* from_thread, [[maybe_unused]] Thread* to_thread, [[maybe_unused]] TrapFrame* trap)
  1234. {
  1235. ASSERT(!are_interrupts_enabled());
  1236. ASSERT(is_kernel_mode());
  1237. dbgln_if(CONTEXT_SWITCH_DEBUG, "switch_context <-- from {} {} to {} {} (context_first_init)", VirtualAddress(from_thread), *from_thread, VirtualAddress(to_thread), *to_thread);
  1238. ASSERT(to_thread == Thread::current());
  1239. Scheduler::enter_current(*from_thread, true);
  1240. // Since we got here and don't have Scheduler::context_switch in the
  1241. // call stack (because this is the first time we switched into this
  1242. // context), we need to notify the scheduler so that it can release
  1243. // the scheduler lock. We don't want to enable interrupts at this point
  1244. // as we're still in the middle of a context switch. Doing so could
  1245. // trigger a context switch within a context switch, leading to a crash.
  1246. Scheduler::leave_on_first_switch(trap->regs->eflags & ~0x200);
  1247. }
  1248. extern "C" void thread_context_first_enter(void);
  1249. // clang-format off
  1250. asm(
  1251. // enter_thread_context returns to here first time a thread is executing
  1252. ".globl thread_context_first_enter \n"
  1253. "thread_context_first_enter: \n"
  1254. // switch_context will have pushed from_thread and to_thread to our new
  1255. // stack prior to thread_context_first_enter() being called, and the
  1256. // pointer to TrapFrame was the top of the stack before that
  1257. " movl 8(%esp), %ebx \n" // save pointer to TrapFrame
  1258. " cld \n"
  1259. " call context_first_init \n"
  1260. " addl $" __STRINGIFY(ENTER_THREAD_CONTEXT_ARGS_SIZE) ", %esp \n"
  1261. " movl %ebx, 0(%esp) \n" // push pointer to TrapFrame
  1262. " jmp common_trap_exit \n"
  1263. );
  1264. // clang-format on
  1265. void exit_kernel_thread(void)
  1266. {
  1267. Thread::current()->exit();
  1268. }
  1269. u32 Processor::init_context(Thread& thread, bool leave_crit)
  1270. {
  1271. ASSERT(is_kernel_mode());
  1272. ASSERT(g_scheduler_lock.is_locked());
  1273. if (leave_crit) {
  1274. // Leave the critical section we set up in in Process::exec,
  1275. // but because we still have the scheduler lock we should end up with 1
  1276. m_in_critical--; // leave it without triggering anything or restoring flags
  1277. ASSERT(in_critical() == 1);
  1278. }
  1279. u32 kernel_stack_top = thread.kernel_stack_top();
  1280. u32 stack_top = kernel_stack_top;
  1281. // TODO: handle NT?
  1282. ASSERT((cpu_flags() & 0x24000) == 0); // Assume !(NT | VM)
  1283. auto& tss = thread.tss();
  1284. bool return_to_user = (tss.cs & 3) != 0;
  1285. // make room for an interrupt frame
  1286. if (!return_to_user) {
  1287. // userspace_esp and userspace_ss are not popped off by iret
  1288. // unless we're switching back to user mode
  1289. stack_top -= sizeof(RegisterState) - 2 * sizeof(u32);
  1290. // For kernel threads we'll push the thread function argument
  1291. // which should be in tss.esp and exit_kernel_thread as return
  1292. // address.
  1293. stack_top -= 2 * sizeof(u32);
  1294. *reinterpret_cast<u32*>(kernel_stack_top - 2 * sizeof(u32)) = tss.esp;
  1295. *reinterpret_cast<u32*>(kernel_stack_top - 3 * sizeof(u32)) = FlatPtr(&exit_kernel_thread);
  1296. } else {
  1297. stack_top -= sizeof(RegisterState);
  1298. }
  1299. // we want to end up 16-byte aligned, %esp + 4 should be aligned
  1300. stack_top -= sizeof(u32);
  1301. *reinterpret_cast<u32*>(kernel_stack_top - sizeof(u32)) = 0;
  1302. // set up the stack so that after returning from thread_context_first_enter()
  1303. // we will end up either in kernel mode or user mode, depending on how the thread is set up
  1304. // However, the first step is to always start in kernel mode with thread_context_first_enter
  1305. RegisterState& iretframe = *reinterpret_cast<RegisterState*>(stack_top);
  1306. iretframe.ss = tss.ss;
  1307. iretframe.gs = tss.gs;
  1308. iretframe.fs = tss.fs;
  1309. iretframe.es = tss.es;
  1310. iretframe.ds = tss.ds;
  1311. iretframe.edi = tss.edi;
  1312. iretframe.esi = tss.esi;
  1313. iretframe.ebp = tss.ebp;
  1314. iretframe.esp = 0;
  1315. iretframe.ebx = tss.ebx;
  1316. iretframe.edx = tss.edx;
  1317. iretframe.ecx = tss.ecx;
  1318. iretframe.eax = tss.eax;
  1319. iretframe.eflags = tss.eflags;
  1320. iretframe.eip = tss.eip;
  1321. iretframe.cs = tss.cs;
  1322. if (return_to_user) {
  1323. iretframe.userspace_esp = tss.esp;
  1324. iretframe.userspace_ss = tss.ss;
  1325. }
  1326. // make space for a trap frame
  1327. stack_top -= sizeof(TrapFrame);
  1328. TrapFrame& trap = *reinterpret_cast<TrapFrame*>(stack_top);
  1329. trap.regs = &iretframe;
  1330. trap.prev_irq_level = 0;
  1331. trap.next_trap = nullptr;
  1332. stack_top -= sizeof(u32); // pointer to TrapFrame
  1333. *reinterpret_cast<u32*>(stack_top) = stack_top + 4;
  1334. if constexpr (CONTEXT_SWITCH_DEBUG) {
  1335. if (return_to_user) {
  1336. dbgln("init_context {} ({}) set up to execute at eip={}:{}, esp={}, stack_top={}, user_top={}:{}",
  1337. thread,
  1338. VirtualAddress(&thread),
  1339. iretframe.cs, tss.eip,
  1340. VirtualAddress(tss.esp),
  1341. VirtualAddress(stack_top),
  1342. iretframe.userspace_ss,
  1343. iretframe.userspace_esp);
  1344. } else {
  1345. dbgln("init_context {} ({}) set up to execute at eip={}:{}, esp={}, stack_top={}",
  1346. thread,
  1347. VirtualAddress(&thread),
  1348. iretframe.cs, tss.eip,
  1349. VirtualAddress(tss.esp),
  1350. VirtualAddress(stack_top));
  1351. }
  1352. }
  1353. // make switch_context() always first return to thread_context_first_enter()
  1354. // in kernel mode, so set up these values so that we end up popping iretframe
  1355. // off the stack right after the context switch completed, at which point
  1356. // control is transferred to what iretframe is pointing to.
  1357. tss.eip = FlatPtr(&thread_context_first_enter);
  1358. tss.esp0 = kernel_stack_top;
  1359. tss.esp = stack_top;
  1360. tss.cs = GDT_SELECTOR_CODE0;
  1361. tss.ds = GDT_SELECTOR_DATA0;
  1362. tss.es = GDT_SELECTOR_DATA0;
  1363. tss.gs = GDT_SELECTOR_DATA0;
  1364. tss.ss = GDT_SELECTOR_DATA0;
  1365. tss.fs = GDT_SELECTOR_PROC;
  1366. return stack_top;
  1367. }
  1368. extern "C" u32 do_init_context(Thread* thread, u32 flags)
  1369. {
  1370. ASSERT_INTERRUPTS_DISABLED();
  1371. thread->tss().eflags = flags;
  1372. return Processor::current().init_context(*thread, true);
  1373. }
  1374. extern "C" void do_assume_context(Thread* thread, u32 flags);
  1375. // clang-format off
  1376. asm(
  1377. ".global do_assume_context \n"
  1378. "do_assume_context: \n"
  1379. " movl 4(%esp), %ebx \n"
  1380. " movl 8(%esp), %esi \n"
  1381. // We're going to call Processor::init_context, so just make sure
  1382. // we have enough stack space so we don't stomp over it
  1383. " subl $(" __STRINGIFY(4 + REGISTER_STATE_SIZE + TRAP_FRAME_SIZE + 4) "), %esp \n"
  1384. " pushl %esi \n"
  1385. " pushl %ebx \n"
  1386. " cld \n"
  1387. " call do_init_context \n"
  1388. " addl $8, %esp \n"
  1389. " movl %eax, %esp \n" // move stack pointer to what Processor::init_context set up for us
  1390. " pushl %ebx \n" // push to_thread
  1391. " pushl %ebx \n" // push from_thread
  1392. " pushl $thread_context_first_enter \n" // should be same as tss.eip
  1393. " jmp enter_thread_context \n"
  1394. );
  1395. // clang-format on
  1396. void Processor::assume_context(Thread& thread, u32 flags)
  1397. {
  1398. dbgln_if(CONTEXT_SWITCH_DEBUG, "Assume context for thread {} {}", VirtualAddress(&thread), thread);
  1399. ASSERT_INTERRUPTS_DISABLED();
  1400. Scheduler::prepare_after_exec();
  1401. // in_critical() should be 2 here. The critical section in Process::exec
  1402. // and then the scheduler lock
  1403. ASSERT(Processor::current().in_critical() == 2);
  1404. do_assume_context(&thread, flags);
  1405. ASSERT_NOT_REACHED();
  1406. }
  1407. extern "C" void pre_init_finished(void)
  1408. {
  1409. ASSERT(g_scheduler_lock.own_lock());
  1410. // Because init_finished() will wait on the other APs, we need
  1411. // to release the scheduler lock so that the other APs can also get
  1412. // to this point
  1413. // The target flags will get restored upon leaving the trap
  1414. u32 prev_flags = cpu_flags();
  1415. Scheduler::leave_on_first_switch(prev_flags);
  1416. }
  1417. extern "C" void post_init_finished(void)
  1418. {
  1419. // We need to re-acquire the scheduler lock before a context switch
  1420. // transfers control into the idle loop, which needs the lock held
  1421. Scheduler::prepare_for_idle_loop();
  1422. }
  1423. void Processor::initialize_context_switching(Thread& initial_thread)
  1424. {
  1425. ASSERT(initial_thread.process().is_kernel_process());
  1426. auto& tss = initial_thread.tss();
  1427. m_tss = tss;
  1428. m_tss.esp0 = tss.esp0;
  1429. m_tss.ss0 = GDT_SELECTOR_DATA0;
  1430. // user mode needs to be able to switch to kernel mode:
  1431. m_tss.cs = m_tss.ds = m_tss.es = m_tss.gs = m_tss.ss = GDT_SELECTOR_CODE0 | 3;
  1432. m_tss.fs = GDT_SELECTOR_PROC | 3;
  1433. m_scheduler_initialized = true;
  1434. // clang-format off
  1435. asm volatile(
  1436. "movl %[new_esp], %%esp \n" // switch to new stack
  1437. "pushl %[from_to_thread] \n" // to_thread
  1438. "pushl %[from_to_thread] \n" // from_thread
  1439. "pushl $" __STRINGIFY(GDT_SELECTOR_CODE0) " \n"
  1440. "pushl %[new_eip] \n" // save the entry eip to the stack
  1441. "movl %%esp, %%ebx \n"
  1442. "addl $20, %%ebx \n" // calculate pointer to TrapFrame
  1443. "pushl %%ebx \n"
  1444. "cld \n"
  1445. "pushl %[cpu] \n" // push argument for init_finished before register is clobbered
  1446. "call pre_init_finished \n"
  1447. "call init_finished \n"
  1448. "addl $4, %%esp \n"
  1449. "call post_init_finished \n"
  1450. "call enter_trap_no_irq \n"
  1451. "addl $4, %%esp \n"
  1452. "lret \n"
  1453. :: [new_esp] "g" (tss.esp),
  1454. [new_eip] "a" (tss.eip),
  1455. [from_to_thread] "b" (&initial_thread),
  1456. [cpu] "c" (id())
  1457. );
  1458. // clang-format on
  1459. ASSERT_NOT_REACHED();
  1460. }
  1461. void Processor::enter_trap(TrapFrame& trap, bool raise_irq)
  1462. {
  1463. ASSERT_INTERRUPTS_DISABLED();
  1464. ASSERT(&Processor::current() == this);
  1465. trap.prev_irq_level = m_in_irq;
  1466. if (raise_irq)
  1467. m_in_irq++;
  1468. auto* current_thread = Processor::current_thread();
  1469. if (current_thread) {
  1470. auto& current_trap = current_thread->current_trap();
  1471. trap.next_trap = current_trap;
  1472. current_trap = &trap;
  1473. // The cs register of this trap tells us where we will return back to
  1474. current_thread->set_previous_mode(((trap.regs->cs & 3) != 0) ? Thread::PreviousMode::UserMode : Thread::PreviousMode::KernelMode);
  1475. } else {
  1476. trap.next_trap = nullptr;
  1477. }
  1478. }
  1479. void Processor::exit_trap(TrapFrame& trap)
  1480. {
  1481. ASSERT_INTERRUPTS_DISABLED();
  1482. ASSERT(&Processor::current() == this);
  1483. ASSERT(m_in_irq >= trap.prev_irq_level);
  1484. m_in_irq = trap.prev_irq_level;
  1485. smp_process_pending_messages();
  1486. if (!m_in_irq && !m_in_critical)
  1487. check_invoke_scheduler();
  1488. auto* current_thread = Processor::current_thread();
  1489. if (current_thread) {
  1490. auto& current_trap = current_thread->current_trap();
  1491. current_trap = trap.next_trap;
  1492. if (current_trap) {
  1493. ASSERT(current_trap->regs);
  1494. // If we have another higher level trap then we probably returned
  1495. // from an interrupt or irq handler. The cs register of the
  1496. // new/higher level trap tells us what the mode prior to it was
  1497. current_thread->set_previous_mode(((current_trap->regs->cs & 3) != 0) ? Thread::PreviousMode::UserMode : Thread::PreviousMode::KernelMode);
  1498. } else {
  1499. // If we don't have a higher level trap then we're back in user mode.
  1500. // Unless we're a kernel process, in which case we're always in kernel mode
  1501. current_thread->set_previous_mode(current_thread->process().is_kernel_process() ? Thread::PreviousMode::KernelMode : Thread::PreviousMode::UserMode);
  1502. }
  1503. }
  1504. }
  1505. void Processor::check_invoke_scheduler()
  1506. {
  1507. ASSERT(!m_in_irq);
  1508. ASSERT(!m_in_critical);
  1509. if (m_invoke_scheduler_async && m_scheduler_initialized) {
  1510. m_invoke_scheduler_async = false;
  1511. Scheduler::invoke_async();
  1512. }
  1513. }
  1514. void Processor::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  1515. {
  1516. auto ptr = vaddr.as_ptr();
  1517. while (page_count > 0) {
  1518. // clang-format off
  1519. asm volatile("invlpg %0"
  1520. :
  1521. : "m"(*ptr)
  1522. : "memory");
  1523. // clang-format on
  1524. ptr += PAGE_SIZE;
  1525. page_count--;
  1526. }
  1527. }
  1528. void Processor::flush_tlb(const PageDirectory* page_directory, VirtualAddress vaddr, size_t page_count)
  1529. {
  1530. if (s_smp_enabled && (!is_user_address(vaddr) || Process::current()->thread_count() > 1))
  1531. smp_broadcast_flush_tlb(page_directory, vaddr, page_count);
  1532. else
  1533. flush_tlb_local(vaddr, page_count);
  1534. }
  1535. static volatile ProcessorMessage* s_message_pool;
  1536. void Processor::smp_return_to_pool(ProcessorMessage& msg)
  1537. {
  1538. ProcessorMessage* next = nullptr;
  1539. do {
  1540. msg.next = next;
  1541. } while (!atomic_compare_exchange_strong(&s_message_pool, next, &msg, AK::MemoryOrder::memory_order_acq_rel));
  1542. }
  1543. ProcessorMessage& Processor::smp_get_from_pool()
  1544. {
  1545. ProcessorMessage* msg;
  1546. // The assumption is that messages are never removed from the pool!
  1547. for (;;) {
  1548. msg = atomic_load(&s_message_pool, AK::MemoryOrder::memory_order_consume);
  1549. if (!msg) {
  1550. if (!Processor::current().smp_process_pending_messages()) {
  1551. // TODO: pause for a bit?
  1552. }
  1553. continue;
  1554. }
  1555. // If another processor were to use this message in the meanwhile,
  1556. // "msg" is still valid (because it never gets freed). We'd detect
  1557. // this because the expected value "msg" and pool would
  1558. // no longer match, and the compare_exchange will fail. But accessing
  1559. // "msg->next" is always safe here.
  1560. if (atomic_compare_exchange_strong(&s_message_pool, msg, msg->next, AK::MemoryOrder::memory_order_acq_rel)) {
  1561. // We successfully "popped" this available message
  1562. break;
  1563. }
  1564. }
  1565. ASSERT(msg != nullptr);
  1566. return *msg;
  1567. }
  1568. Atomic<u32> Processor::s_idle_cpu_mask { 0 };
  1569. u32 Processor::smp_wake_n_idle_processors(u32 wake_count)
  1570. {
  1571. ASSERT(Processor::current().in_critical());
  1572. ASSERT(wake_count > 0);
  1573. if (!s_smp_enabled)
  1574. return 0;
  1575. // Wake at most N - 1 processors
  1576. if (wake_count >= Processor::count()) {
  1577. wake_count = Processor::count() - 1;
  1578. ASSERT(wake_count > 0);
  1579. }
  1580. u32 current_id = Processor::current().id();
  1581. u32 did_wake_count = 0;
  1582. auto& apic = APIC::the();
  1583. while (did_wake_count < wake_count) {
  1584. // Try to get a set of idle CPUs and flip them to busy
  1585. u32 idle_mask = s_idle_cpu_mask.load(AK::MemoryOrder::memory_order_relaxed) & ~(1u << current_id);
  1586. u32 idle_count = __builtin_popcountl(idle_mask);
  1587. if (idle_count == 0)
  1588. break; // No (more) idle processor available
  1589. u32 found_mask = 0;
  1590. for (u32 i = 0; i < idle_count; i++) {
  1591. u32 cpu = __builtin_ffsl(idle_mask) - 1;
  1592. idle_mask &= ~(1u << cpu);
  1593. found_mask |= 1u << cpu;
  1594. }
  1595. idle_mask = s_idle_cpu_mask.fetch_and(~found_mask, AK::MemoryOrder::memory_order_acq_rel) & found_mask;
  1596. if (idle_mask == 0)
  1597. continue; // All of them were flipped to busy, try again
  1598. idle_count = __builtin_popcountl(idle_mask);
  1599. for (u32 i = 0; i < idle_count; i++) {
  1600. u32 cpu = __builtin_ffsl(idle_mask) - 1;
  1601. idle_mask &= ~(1u << cpu);
  1602. // Send an IPI to that CPU to wake it up. There is a possibility
  1603. // someone else woke it up as well, or that it woke up due to
  1604. // a timer interrupt. But we tried hard to avoid this...
  1605. apic.send_ipi(cpu);
  1606. did_wake_count++;
  1607. }
  1608. }
  1609. return did_wake_count;
  1610. }
  1611. void Processor::smp_enable()
  1612. {
  1613. size_t msg_pool_size = Processor::count() * 100u;
  1614. size_t msg_entries_cnt = Processor::count();
  1615. auto msgs = new ProcessorMessage[msg_pool_size];
  1616. auto msg_entries = new ProcessorMessageEntry[msg_pool_size * msg_entries_cnt];
  1617. size_t msg_entry_i = 0;
  1618. for (size_t i = 0; i < msg_pool_size; i++, msg_entry_i += msg_entries_cnt) {
  1619. auto& msg = msgs[i];
  1620. msg.next = i < msg_pool_size - 1 ? &msgs[i + 1] : nullptr;
  1621. msg.per_proc_entries = &msg_entries[msg_entry_i];
  1622. for (size_t k = 0; k < msg_entries_cnt; k++)
  1623. msg_entries[msg_entry_i + k].msg = &msg;
  1624. }
  1625. atomic_store(&s_message_pool, &msgs[0], AK::MemoryOrder::memory_order_release);
  1626. // Start sending IPI messages
  1627. s_smp_enabled = true;
  1628. }
  1629. void Processor::smp_cleanup_message(ProcessorMessage& msg)
  1630. {
  1631. switch (msg.type) {
  1632. case ProcessorMessage::CallbackWithData:
  1633. if (msg.callback_with_data.free)
  1634. msg.callback_with_data.free(msg.callback_with_data.data);
  1635. break;
  1636. default:
  1637. break;
  1638. }
  1639. }
  1640. bool Processor::smp_process_pending_messages()
  1641. {
  1642. bool did_process = false;
  1643. u32 prev_flags;
  1644. enter_critical(prev_flags);
  1645. if (auto pending_msgs = atomic_exchange(&m_message_queue, nullptr, AK::MemoryOrder::memory_order_acq_rel)) {
  1646. // We pulled the stack of pending messages in LIFO order, so we need to reverse the list first
  1647. auto reverse_list =
  1648. [](ProcessorMessageEntry* list) -> ProcessorMessageEntry* {
  1649. ProcessorMessageEntry* rev_list = nullptr;
  1650. while (list) {
  1651. auto next = list->next;
  1652. list->next = rev_list;
  1653. rev_list = list;
  1654. list = next;
  1655. }
  1656. return rev_list;
  1657. };
  1658. pending_msgs = reverse_list(pending_msgs);
  1659. // now process in the right order
  1660. ProcessorMessageEntry* next_msg;
  1661. for (auto cur_msg = pending_msgs; cur_msg; cur_msg = next_msg) {
  1662. next_msg = cur_msg->next;
  1663. auto msg = cur_msg->msg;
  1664. dbgln_if(SMP_DEBUG, "SMP[{}]: Processing message {}", id(), VirtualAddress(msg));
  1665. switch (msg->type) {
  1666. case ProcessorMessage::Callback:
  1667. msg->callback.handler();
  1668. break;
  1669. case ProcessorMessage::CallbackWithData:
  1670. msg->callback_with_data.handler(msg->callback_with_data.data);
  1671. break;
  1672. case ProcessorMessage::FlushTlb:
  1673. if (is_user_address(VirtualAddress(msg->flush_tlb.ptr))) {
  1674. // We assume that we don't cross into kernel land!
  1675. ASSERT(is_user_range(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count * PAGE_SIZE));
  1676. if (read_cr3() != msg->flush_tlb.page_directory->cr3()) {
  1677. // This processor isn't using this page directory right now, we can ignore this request
  1678. dbgln_if(SMP_DEBUG, "SMP[{}]: No need to flush {} pages at {}", id(), msg->flush_tlb.page_count, VirtualAddress(msg->flush_tlb.ptr));
  1679. break;
  1680. }
  1681. }
  1682. flush_tlb_local(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count);
  1683. break;
  1684. }
  1685. bool is_async = msg->async; // Need to cache this value *before* dropping the ref count!
  1686. auto prev_refs = atomic_fetch_sub(&msg->refs, 1u, AK::MemoryOrder::memory_order_acq_rel);
  1687. ASSERT(prev_refs != 0);
  1688. if (prev_refs == 1) {
  1689. // All processors handled this. If this is an async message,
  1690. // we need to clean it up and return it to the pool
  1691. if (is_async) {
  1692. smp_cleanup_message(*msg);
  1693. smp_return_to_pool(*msg);
  1694. }
  1695. }
  1696. if (m_halt_requested.load(AK::MemoryOrder::memory_order_relaxed))
  1697. halt_this();
  1698. }
  1699. did_process = true;
  1700. } else if (m_halt_requested.load(AK::MemoryOrder::memory_order_relaxed)) {
  1701. halt_this();
  1702. }
  1703. leave_critical(prev_flags);
  1704. return did_process;
  1705. }
  1706. bool Processor::smp_queue_message(ProcessorMessage& msg)
  1707. {
  1708. // Note that it's quite possible that the other processor may pop
  1709. // the queue at any given time. We rely on the fact that the messages
  1710. // are pooled and never get freed!
  1711. auto& msg_entry = msg.per_proc_entries[id()];
  1712. ASSERT(msg_entry.msg == &msg);
  1713. ProcessorMessageEntry* next = nullptr;
  1714. do {
  1715. msg_entry.next = next;
  1716. } while (!atomic_compare_exchange_strong(&m_message_queue, next, &msg_entry, AK::MemoryOrder::memory_order_acq_rel));
  1717. return next == nullptr;
  1718. }
  1719. void Processor::smp_broadcast_message(ProcessorMessage& msg)
  1720. {
  1721. auto& cur_proc = Processor::current();
  1722. dbgln_if(SMP_DEBUG, "SMP[{}]: Broadcast message {} to cpus: {} proc: {}", cur_proc.get_id(), VirtualAddress(&msg), count(), VirtualAddress(&cur_proc));
  1723. atomic_store(&msg.refs, count() - 1, AK::MemoryOrder::memory_order_release);
  1724. ASSERT(msg.refs > 0);
  1725. bool need_broadcast = false;
  1726. for_each(
  1727. [&](Processor& proc) -> IterationDecision {
  1728. if (&proc != &cur_proc) {
  1729. if (proc.smp_queue_message(msg))
  1730. need_broadcast = true;
  1731. }
  1732. return IterationDecision::Continue;
  1733. });
  1734. // Now trigger an IPI on all other APs (unless all targets already had messages queued)
  1735. if (need_broadcast)
  1736. APIC::the().broadcast_ipi();
  1737. }
  1738. void Processor::smp_broadcast_wait_sync(ProcessorMessage& msg)
  1739. {
  1740. auto& cur_proc = Processor::current();
  1741. ASSERT(!msg.async);
  1742. // If synchronous then we must cleanup and return the message back
  1743. // to the pool. Otherwise, the last processor to complete it will return it
  1744. while (atomic_load(&msg.refs, AK::MemoryOrder::memory_order_consume) != 0) {
  1745. // TODO: pause for a bit?
  1746. // We need to process any messages that may have been sent to
  1747. // us while we're waiting. This also checks if another processor
  1748. // may have requested us to halt.
  1749. cur_proc.smp_process_pending_messages();
  1750. }
  1751. smp_cleanup_message(msg);
  1752. smp_return_to_pool(msg);
  1753. }
  1754. void Processor::smp_broadcast(void (*callback)(void*), void* data, void (*free_data)(void*), bool async)
  1755. {
  1756. auto& msg = smp_get_from_pool();
  1757. msg.async = async;
  1758. msg.type = ProcessorMessage::CallbackWithData;
  1759. msg.callback_with_data.handler = callback;
  1760. msg.callback_with_data.data = data;
  1761. msg.callback_with_data.free = free_data;
  1762. smp_broadcast_message(msg);
  1763. if (!async)
  1764. smp_broadcast_wait_sync(msg);
  1765. }
  1766. void Processor::smp_broadcast(void (*callback)(), bool async)
  1767. {
  1768. auto& msg = smp_get_from_pool();
  1769. msg.async = async;
  1770. msg.type = ProcessorMessage::CallbackWithData;
  1771. msg.callback.handler = callback;
  1772. smp_broadcast_message(msg);
  1773. if (!async)
  1774. smp_broadcast_wait_sync(msg);
  1775. }
  1776. void Processor::smp_unicast_message(u32 cpu, ProcessorMessage& msg, bool async)
  1777. {
  1778. auto& cur_proc = Processor::current();
  1779. ASSERT(cpu != cur_proc.get_id());
  1780. auto& target_proc = processors()[cpu];
  1781. msg.async = async;
  1782. dbgln_if(SMP_DEBUG, "SMP[{}]: Send message {} to cpu #{} proc: {}", cur_proc.get_id(), VirtualAddress(&msg), cpu, VirtualAddress(&target_proc));
  1783. atomic_store(&msg.refs, 1u, AK::MemoryOrder::memory_order_release);
  1784. if (target_proc->smp_queue_message(msg)) {
  1785. APIC::the().send_ipi(cpu);
  1786. }
  1787. if (!async) {
  1788. // If synchronous then we must cleanup and return the message back
  1789. // to the pool. Otherwise, the last processor to complete it will return it
  1790. while (atomic_load(&msg.refs, AK::MemoryOrder::memory_order_consume) != 0) {
  1791. // TODO: pause for a bit?
  1792. // We need to process any messages that may have been sent to
  1793. // us while we're waiting. This also checks if another processor
  1794. // may have requested us to halt.
  1795. cur_proc.smp_process_pending_messages();
  1796. }
  1797. smp_cleanup_message(msg);
  1798. smp_return_to_pool(msg);
  1799. }
  1800. }
  1801. void Processor::smp_unicast(u32 cpu, void (*callback)(void*), void* data, void (*free_data)(void*), bool async)
  1802. {
  1803. auto& msg = smp_get_from_pool();
  1804. msg.type = ProcessorMessage::CallbackWithData;
  1805. msg.callback_with_data.handler = callback;
  1806. msg.callback_with_data.data = data;
  1807. msg.callback_with_data.free = free_data;
  1808. smp_unicast_message(cpu, msg, async);
  1809. }
  1810. void Processor::smp_unicast(u32 cpu, void (*callback)(), bool async)
  1811. {
  1812. auto& msg = smp_get_from_pool();
  1813. msg.type = ProcessorMessage::CallbackWithData;
  1814. msg.callback.handler = callback;
  1815. smp_unicast_message(cpu, msg, async);
  1816. }
  1817. void Processor::smp_broadcast_flush_tlb(const PageDirectory* page_directory, VirtualAddress vaddr, size_t page_count)
  1818. {
  1819. auto& msg = smp_get_from_pool();
  1820. msg.async = false;
  1821. msg.type = ProcessorMessage::FlushTlb;
  1822. msg.flush_tlb.page_directory = page_directory;
  1823. msg.flush_tlb.ptr = vaddr.as_ptr();
  1824. msg.flush_tlb.page_count = page_count;
  1825. smp_broadcast_message(msg);
  1826. // While the other processors handle this request, we'll flush ours
  1827. flush_tlb_local(vaddr, page_count);
  1828. // Now wait until everybody is done as well
  1829. smp_broadcast_wait_sync(msg);
  1830. }
  1831. void Processor::smp_broadcast_halt()
  1832. {
  1833. // We don't want to use a message, because this could have been triggered
  1834. // by being out of memory and we might not be able to get a message
  1835. for_each(
  1836. [&](Processor& proc) -> IterationDecision {
  1837. proc.m_halt_requested.store(true, AK::MemoryOrder::memory_order_release);
  1838. return IterationDecision::Continue;
  1839. });
  1840. // Now trigger an IPI on all other APs
  1841. APIC::the().broadcast_ipi();
  1842. }
  1843. void Processor::Processor::halt()
  1844. {
  1845. if (s_smp_enabled)
  1846. smp_broadcast_halt();
  1847. halt_this();
  1848. }
  1849. void Processor::deferred_call_pool_init()
  1850. {
  1851. size_t pool_count = sizeof(m_deferred_call_pool) / sizeof(m_deferred_call_pool[0]);
  1852. for (size_t i = 0; i < pool_count; i++) {
  1853. auto& entry = m_deferred_call_pool[i];
  1854. entry.next = i < pool_count - 1 ? &m_deferred_call_pool[i + 1] : nullptr;
  1855. entry.was_allocated = false;
  1856. }
  1857. m_pending_deferred_calls = nullptr;
  1858. m_free_deferred_call_pool_entry = &m_deferred_call_pool[0];
  1859. }
  1860. void Processor::deferred_call_return_to_pool(DeferredCallEntry* entry)
  1861. {
  1862. ASSERT(m_in_critical);
  1863. ASSERT(!entry->was_allocated);
  1864. entry->next = m_free_deferred_call_pool_entry;
  1865. m_free_deferred_call_pool_entry = entry;
  1866. }
  1867. DeferredCallEntry* Processor::deferred_call_get_free()
  1868. {
  1869. ASSERT(m_in_critical);
  1870. if (m_free_deferred_call_pool_entry) {
  1871. // Fast path, we have an entry in our pool
  1872. auto* entry = m_free_deferred_call_pool_entry;
  1873. m_free_deferred_call_pool_entry = entry->next;
  1874. ASSERT(!entry->was_allocated);
  1875. return entry;
  1876. }
  1877. auto* entry = new DeferredCallEntry;
  1878. entry->was_allocated = true;
  1879. return entry;
  1880. }
  1881. void Processor::deferred_call_execute_pending()
  1882. {
  1883. ASSERT(m_in_critical);
  1884. if (!m_pending_deferred_calls)
  1885. return;
  1886. auto* pending_list = m_pending_deferred_calls;
  1887. m_pending_deferred_calls = nullptr;
  1888. // We pulled the stack of pending deferred calls in LIFO order, so we need to reverse the list first
  1889. auto reverse_list =
  1890. [](DeferredCallEntry* list) -> DeferredCallEntry* {
  1891. DeferredCallEntry* rev_list = nullptr;
  1892. while (list) {
  1893. auto next = list->next;
  1894. list->next = rev_list;
  1895. rev_list = list;
  1896. list = next;
  1897. }
  1898. return rev_list;
  1899. };
  1900. pending_list = reverse_list(pending_list);
  1901. do {
  1902. // Call the appropriate callback handler
  1903. if (pending_list->have_data) {
  1904. pending_list->callback_with_data.handler(pending_list->callback_with_data.data);
  1905. if (pending_list->callback_with_data.free)
  1906. pending_list->callback_with_data.free(pending_list->callback_with_data.data);
  1907. } else {
  1908. pending_list->callback.handler();
  1909. }
  1910. // Return the entry back to the pool, or free it
  1911. auto* next = pending_list->next;
  1912. if (pending_list->was_allocated)
  1913. delete pending_list;
  1914. else
  1915. deferred_call_return_to_pool(pending_list);
  1916. pending_list = next;
  1917. } while (pending_list);
  1918. }
  1919. void Processor::deferred_call_queue_entry(DeferredCallEntry* entry)
  1920. {
  1921. ASSERT(m_in_critical);
  1922. entry->next = m_pending_deferred_calls;
  1923. m_pending_deferred_calls = entry;
  1924. }
  1925. void Processor::deferred_call_queue(void (*callback)())
  1926. {
  1927. // NOTE: If we are called outside of a critical section and outside
  1928. // of an irq handler, the function will be executed before we return!
  1929. ScopedCritical critical;
  1930. auto& cur_proc = Processor::current();
  1931. auto* entry = cur_proc.deferred_call_get_free();
  1932. entry->have_data = false;
  1933. entry->callback.handler = callback;
  1934. cur_proc.deferred_call_queue_entry(entry);
  1935. }
  1936. void Processor::deferred_call_queue(void (*callback)(void*), void* data, void (*free_data)(void*))
  1937. {
  1938. // NOTE: If we are called outside of a critical section and outside
  1939. // of an irq handler, the function will be executed before we return!
  1940. ScopedCritical critical;
  1941. auto& cur_proc = Processor::current();
  1942. auto* entry = cur_proc.deferred_call_get_free();
  1943. entry->have_data = true;
  1944. entry->callback_with_data.handler = callback;
  1945. entry->callback_with_data.data = data;
  1946. entry->callback_with_data.free = free_data;
  1947. cur_proc.deferred_call_queue_entry(entry);
  1948. }
  1949. void Processor::gdt_init()
  1950. {
  1951. m_gdt_length = 0;
  1952. m_gdtr.address = nullptr;
  1953. m_gdtr.limit = 0;
  1954. write_raw_gdt_entry(0x0000, 0x00000000, 0x00000000);
  1955. write_raw_gdt_entry(GDT_SELECTOR_CODE0, 0x0000ffff, 0x00cf9a00); // code0
  1956. write_raw_gdt_entry(GDT_SELECTOR_DATA0, 0x0000ffff, 0x00cf9200); // data0
  1957. write_raw_gdt_entry(GDT_SELECTOR_CODE3, 0x0000ffff, 0x00cffa00); // code3
  1958. write_raw_gdt_entry(GDT_SELECTOR_DATA3, 0x0000ffff, 0x00cff200); // data3
  1959. Descriptor tls_descriptor;
  1960. tls_descriptor.low = tls_descriptor.high = 0;
  1961. tls_descriptor.dpl = 3;
  1962. tls_descriptor.segment_present = 1;
  1963. tls_descriptor.granularity = 0;
  1964. tls_descriptor.zero = 0;
  1965. tls_descriptor.operation_size = 1;
  1966. tls_descriptor.descriptor_type = 1;
  1967. tls_descriptor.type = 2;
  1968. write_gdt_entry(GDT_SELECTOR_TLS, tls_descriptor); // tls3
  1969. Descriptor fs_descriptor;
  1970. fs_descriptor.set_base(this);
  1971. fs_descriptor.set_limit(sizeof(Processor));
  1972. fs_descriptor.dpl = 0;
  1973. fs_descriptor.segment_present = 1;
  1974. fs_descriptor.granularity = 0;
  1975. fs_descriptor.zero = 0;
  1976. fs_descriptor.operation_size = 1;
  1977. fs_descriptor.descriptor_type = 1;
  1978. fs_descriptor.type = 2;
  1979. write_gdt_entry(GDT_SELECTOR_PROC, fs_descriptor); // fs0
  1980. Descriptor tss_descriptor;
  1981. tss_descriptor.set_base(&m_tss);
  1982. tss_descriptor.set_limit(sizeof(TSS32));
  1983. tss_descriptor.dpl = 0;
  1984. tss_descriptor.segment_present = 1;
  1985. tss_descriptor.granularity = 0;
  1986. tss_descriptor.zero = 0;
  1987. tss_descriptor.operation_size = 1;
  1988. tss_descriptor.descriptor_type = 0;
  1989. tss_descriptor.type = 9;
  1990. write_gdt_entry(GDT_SELECTOR_TSS, tss_descriptor); // tss
  1991. flush_gdt();
  1992. load_task_register(GDT_SELECTOR_TSS);
  1993. asm volatile(
  1994. "mov %%ax, %%ds\n"
  1995. "mov %%ax, %%es\n"
  1996. "mov %%ax, %%gs\n"
  1997. "mov %%ax, %%ss\n" ::"a"(GDT_SELECTOR_DATA0)
  1998. : "memory");
  1999. set_fs(GDT_SELECTOR_PROC);
  2000. // Make sure CS points to the kernel code descriptor.
  2001. // clang-format off
  2002. asm volatile(
  2003. "ljmpl $" __STRINGIFY(GDT_SELECTOR_CODE0) ", $sanity\n"
  2004. "sanity:\n");
  2005. // clang-format on
  2006. }
  2007. void Processor::set_thread_specific(u8* data, size_t len)
  2008. {
  2009. auto& descriptor = get_gdt_entry(GDT_SELECTOR_TLS);
  2010. descriptor.set_base(data);
  2011. descriptor.set_limit(len);
  2012. }
  2013. void copy_kernel_registers_into_ptrace_registers(PtraceRegisters& ptrace_regs, const RegisterState& kernel_regs)
  2014. {
  2015. ptrace_regs.eax = kernel_regs.eax,
  2016. ptrace_regs.ecx = kernel_regs.ecx,
  2017. ptrace_regs.edx = kernel_regs.edx,
  2018. ptrace_regs.ebx = kernel_regs.ebx,
  2019. ptrace_regs.esp = kernel_regs.userspace_esp,
  2020. ptrace_regs.ebp = kernel_regs.ebp,
  2021. ptrace_regs.esi = kernel_regs.esi,
  2022. ptrace_regs.edi = kernel_regs.edi,
  2023. ptrace_regs.eip = kernel_regs.eip,
  2024. ptrace_regs.eflags = kernel_regs.eflags,
  2025. ptrace_regs.cs = 0;
  2026. ptrace_regs.ss = 0;
  2027. ptrace_regs.ds = 0;
  2028. ptrace_regs.es = 0;
  2029. ptrace_regs.fs = 0;
  2030. ptrace_regs.gs = 0;
  2031. }
  2032. void copy_ptrace_registers_into_kernel_registers(RegisterState& kernel_regs, const PtraceRegisters& ptrace_regs)
  2033. {
  2034. kernel_regs.eax = ptrace_regs.eax;
  2035. kernel_regs.ecx = ptrace_regs.ecx;
  2036. kernel_regs.edx = ptrace_regs.edx;
  2037. kernel_regs.ebx = ptrace_regs.ebx;
  2038. kernel_regs.esp = ptrace_regs.esp;
  2039. kernel_regs.ebp = ptrace_regs.ebp;
  2040. kernel_regs.esi = ptrace_regs.esi;
  2041. kernel_regs.edi = ptrace_regs.edi;
  2042. kernel_regs.eip = ptrace_regs.eip;
  2043. kernel_regs.eflags = (kernel_regs.eflags & ~safe_eflags_mask) | (ptrace_regs.eflags & safe_eflags_mask);
  2044. }
  2045. }
  2046. #ifdef DEBUG
  2047. void __assertion_failed(const char* msg, const char* file, unsigned line, const char* func)
  2048. {
  2049. asm volatile("cli");
  2050. klog() << "ASSERTION FAILED: " << msg << "\n"
  2051. << file << ":" << line << " in " << func;
  2052. // Switch back to the current process's page tables if there are any.
  2053. // Otherwise stack walking will be a disaster.
  2054. auto process = Process::current();
  2055. if (process)
  2056. MM.enter_process_paging_scope(*process);
  2057. Kernel::dump_backtrace();
  2058. Processor::halt();
  2059. }
  2060. #endif
  2061. NonMaskableInterruptDisabler::NonMaskableInterruptDisabler()
  2062. {
  2063. IO::out8(0x70, IO::in8(0x70) | 0x80);
  2064. }
  2065. NonMaskableInterruptDisabler::~NonMaskableInterruptDisabler()
  2066. {
  2067. IO::out8(0x70, IO::in8(0x70) & 0x7F);
  2068. }