CPU.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  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/String.h>
  28. #include <AK/StringBuilder.h>
  29. #include <AK/Types.h>
  30. #include <Kernel/Arch/i386/CPU.h>
  31. #include <Kernel/Arch/i386/ISRStubs.h>
  32. #include <Kernel/Arch/i386/ProcessorInfo.h>
  33. #include <Kernel/IO.h>
  34. #include <Kernel/Interrupts/APIC.h>
  35. #include <Kernel/Interrupts/GenericInterruptHandler.h>
  36. #include <Kernel/Interrupts/IRQHandler.h>
  37. #include <Kernel/Interrupts/InterruptManagement.h>
  38. #include <Kernel/Interrupts/SharedIRQHandler.h>
  39. #include <Kernel/Interrupts/SpuriousInterruptHandler.h>
  40. #include <Kernel/Interrupts/UnhandledInterruptHandler.h>
  41. #include <Kernel/KSyms.h>
  42. #include <Kernel/Process.h>
  43. #include <Kernel/SpinLock.h>
  44. #include <Kernel/Thread.h>
  45. #include <Kernel/VM/MemoryManager.h>
  46. #include <Kernel/VM/PageDirectory.h>
  47. #include <LibC/mallocdefs.h>
  48. //#define PAGE_FAULT_DEBUG
  49. //#define CONTEXT_SWITCH_DEBUG
  50. //#define SMP_DEBUG
  51. namespace Kernel {
  52. static DescriptorTablePointer s_idtr;
  53. static Descriptor s_idt[256];
  54. static GenericInterruptHandler* s_interrupt_handler[GENERIC_INTERRUPT_HANDLERS_COUNT];
  55. // The compiler can't see the calls to these functions inside assembly.
  56. // Declare them, to avoid dead code warnings.
  57. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread);
  58. extern "C" void context_first_init(Thread* from_thread, Thread* to_thread, TrapFrame* trap);
  59. extern "C" u32 do_init_context(Thread* thread, u32 flags);
  60. extern "C" void pre_init_finished(void);
  61. extern "C" void post_init_finished(void);
  62. extern "C" void handle_interrupt(TrapFrame*);
  63. #define EH_ENTRY(ec, title) \
  64. extern "C" void title##_asm_entry(); \
  65. extern "C" void title##_handler(TrapFrame*); \
  66. asm( \
  67. ".globl " #title "_asm_entry\n" \
  68. "" #title "_asm_entry: \n" \
  69. " pusha\n" \
  70. " pushl %ds\n" \
  71. " pushl %es\n" \
  72. " pushl %fs\n" \
  73. " pushl %gs\n" \
  74. " pushl %ss\n" \
  75. " mov $" __STRINGIFY(GDT_SELECTOR_DATA0) ", %ax\n" \
  76. " mov %ax, %ds\n" \
  77. " mov %ax, %es\n" \
  78. " mov $" __STRINGIFY(GDT_SELECTOR_PROC) ", %ax\n" \
  79. " mov %ax, %fs\n" \
  80. " pushl %esp \n" /* set TrapFrame::regs */ \
  81. " subl $" __STRINGIFY(TRAP_FRAME_SIZE - 4) ", %esp \n" \
  82. " pushl %esp \n" \
  83. " cld\n" \
  84. " call enter_trap_no_irq \n" \
  85. " call " #title "_handler\n" \
  86. " jmp common_trap_exit \n");
  87. #define EH_ENTRY_NO_CODE(ec, title) \
  88. extern "C" void title##_handler(TrapFrame*); \
  89. extern "C" void title##_asm_entry(); \
  90. asm( \
  91. ".globl " #title "_asm_entry\n" \
  92. "" #title "_asm_entry: \n" \
  93. " pushl $0x0\n" \
  94. " pusha\n" \
  95. " pushl %ds\n" \
  96. " pushl %es\n" \
  97. " pushl %fs\n" \
  98. " pushl %gs\n" \
  99. " pushl %ss\n" \
  100. " mov $" __STRINGIFY(GDT_SELECTOR_DATA0) ", %ax\n" \
  101. " mov %ax, %ds\n" \
  102. " mov %ax, %es\n" \
  103. " mov $" __STRINGIFY(GDT_SELECTOR_PROC) ", %ax\n" \
  104. " mov %ax, %fs\n" \
  105. " pushl %esp \n" /* set TrapFrame::regs */ \
  106. " subl $" __STRINGIFY(TRAP_FRAME_SIZE - 4) ", %esp \n" \
  107. " pushl %esp \n" \
  108. " cld\n" \
  109. " call enter_trap_no_irq \n" \
  110. " call " #title "_handler\n" \
  111. " jmp common_trap_exit \n");
  112. static void dump(const RegisterState& regs)
  113. {
  114. u16 ss;
  115. u32 esp;
  116. auto process = Process::current();
  117. if (!process || process->is_ring0()) {
  118. ss = regs.ss;
  119. esp = regs.esp;
  120. } else {
  121. ss = regs.userspace_ss;
  122. esp = regs.userspace_esp;
  123. }
  124. klog() << "exception code: " << String::format("%04x", regs.exception_code) << " (isr: " << String::format("%04x", regs.isr_number);
  125. klog() << " pc=" << String::format("%04x", (u16)regs.cs) << ":" << String::format("%08x", regs.eip) << " flags=" << String::format("%04x", (u16)regs.eflags);
  126. klog() << " stk=" << String::format("%04x", ss) << ":" << String::format("%08x", esp);
  127. 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);
  128. 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);
  129. 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);
  130. u32 cr0;
  131. asm("movl %%cr0, %%eax"
  132. : "=a"(cr0));
  133. u32 cr2;
  134. asm("movl %%cr2, %%eax"
  135. : "=a"(cr2));
  136. u32 cr3 = read_cr3();
  137. u32 cr4;
  138. asm("movl %%cr4, %%eax"
  139. : "=a"(cr4));
  140. klog() << "cr0=" << String::format("%08x", cr0) << " cr2=" << String::format("%08x", cr2) << " cr3=" << String::format("%08x", cr3) << " cr4=" << String::format("%08x", cr4);
  141. if (process && process->validate_read((void*)regs.eip, 8)) {
  142. SmapDisabler disabler;
  143. u8* codeptr = (u8*)regs.eip;
  144. klog() << "code: " << String::format("%02x", codeptr[0]) << " " << String::format("%02x", codeptr[1]) << " " << String::format("%02x", codeptr[2]) << " " << String::format("%02x", codeptr[3]) << " " << String::format("%02x", codeptr[4]) << " " << String::format("%02x", codeptr[5]) << " " << String::format("%02x", codeptr[6]) << " " << String::format("%02x", codeptr[7]);
  145. }
  146. }
  147. void handle_crash(RegisterState& regs, const char* description, int signal, bool out_of_memory)
  148. {
  149. auto process = Process::current();
  150. if (!process) {
  151. klog() << description << " with !current";
  152. Processor::halt();
  153. }
  154. // If a process crashed while inspecting another process,
  155. // make sure we switch back to the right page tables.
  156. MM.enter_process_paging_scope(*process);
  157. klog() << "CRASH: CPU #" << Processor::current().id() << " " << description << ". Ring " << (process->is_ring0() ? 0 : 3) << ".";
  158. dump(regs);
  159. if (process->is_ring0()) {
  160. klog() << "Crash in ring 0 :(";
  161. dump_backtrace();
  162. Processor::halt();
  163. }
  164. cli();
  165. process->crash(signal, regs.eip, out_of_memory);
  166. }
  167. EH_ENTRY_NO_CODE(6, illegal_instruction);
  168. void illegal_instruction_handler(TrapFrame* trap)
  169. {
  170. clac();
  171. handle_crash(*trap->regs, "Illegal instruction", SIGILL);
  172. }
  173. EH_ENTRY_NO_CODE(0, divide_error);
  174. void divide_error_handler(TrapFrame* trap)
  175. {
  176. clac();
  177. handle_crash(*trap->regs, "Divide error", SIGFPE);
  178. }
  179. EH_ENTRY(13, general_protection_fault);
  180. void general_protection_fault_handler(TrapFrame* trap)
  181. {
  182. clac();
  183. handle_crash(*trap->regs, "General protection fault", SIGSEGV);
  184. }
  185. // 7: FPU not available exception
  186. EH_ENTRY_NO_CODE(7, fpu_exception);
  187. void fpu_exception_handler(TrapFrame*)
  188. {
  189. // Just clear the TS flag. We've already restored the FPU state eagerly.
  190. // FIXME: It would be nice if we didn't have to do this at all.
  191. asm volatile("clts");
  192. }
  193. // 14: Page Fault
  194. EH_ENTRY(14, page_fault);
  195. void page_fault_handler(TrapFrame* trap)
  196. {
  197. clac();
  198. auto& regs = *trap->regs;
  199. u32 fault_address;
  200. asm("movl %%cr2, %%eax"
  201. : "=a"(fault_address));
  202. #ifdef PAGE_FAULT_DEBUG
  203. u32 fault_page_directory = read_cr3();
  204. dbg() << "CPU #" << (Processor::is_initialized() ? Processor::current().id() : 0) << " ring " << (regs.cs & 3)
  205. << " " << (regs.exception_code & 1 ? "PV" : "NP")
  206. << " page fault in PD=" << String::format("%x", fault_page_directory) << ", "
  207. << (regs.exception_code & 8 ? "reserved-bit " : "")
  208. << (regs.exception_code & 2 ? "write" : "read")
  209. << " " << VirtualAddress(fault_address);
  210. #endif
  211. #ifdef PAGE_FAULT_DEBUG
  212. dump(regs);
  213. #endif
  214. bool faulted_in_userspace = (regs.cs & 3) == 3;
  215. auto current_thread = Thread::current();
  216. if (faulted_in_userspace && !MM.validate_user_stack(current_thread->process(), VirtualAddress(regs.userspace_esp))) {
  217. dbg() << "Invalid stack pointer: " << VirtualAddress(regs.userspace_esp);
  218. handle_crash(regs, "Bad stack on page fault", SIGSTKFLT);
  219. ASSERT_NOT_REACHED();
  220. }
  221. auto response = MM.handle_page_fault(PageFault(regs.exception_code, VirtualAddress(fault_address)));
  222. if (response == PageFaultResponse::ShouldCrash || response == PageFaultResponse::OutOfMemory) {
  223. if (response != PageFaultResponse::OutOfMemory) {
  224. if (current_thread->has_signal_handler(SIGSEGV)) {
  225. current_thread->send_urgent_signal_to_self(SIGSEGV);
  226. return;
  227. }
  228. }
  229. dbg() << "Unrecoverable page fault, "
  230. << (regs.exception_code & PageFaultFlags::ReservedBitViolation ? "reserved bit violation / " : "")
  231. << (regs.exception_code & PageFaultFlags::InstructionFetch ? "instruction fetch / " : "")
  232. << (regs.exception_code & PageFaultFlags::Write ? "write to" : "read from")
  233. << " address " << VirtualAddress(fault_address);
  234. u32 malloc_scrub_pattern = explode_byte(MALLOC_SCRUB_BYTE);
  235. u32 free_scrub_pattern = explode_byte(FREE_SCRUB_BYTE);
  236. u32 kmalloc_scrub_pattern = explode_byte(KMALLOC_SCRUB_BYTE);
  237. u32 kfree_scrub_pattern = explode_byte(KFREE_SCRUB_BYTE);
  238. u32 slab_alloc_scrub_pattern = explode_byte(SLAB_ALLOC_SCRUB_BYTE);
  239. u32 slab_dealloc_scrub_pattern = explode_byte(SLAB_DEALLOC_SCRUB_BYTE);
  240. if ((fault_address & 0xffff0000) == (malloc_scrub_pattern & 0xffff0000)) {
  241. dbg() << "Note: Address " << VirtualAddress(fault_address) << " looks like it may be uninitialized malloc() memory";
  242. } else if ((fault_address & 0xffff0000) == (free_scrub_pattern & 0xffff0000)) {
  243. dbg() << "Note: Address " << VirtualAddress(fault_address) << " looks like it may be recently free()'d memory";
  244. } else if ((fault_address & 0xffff0000) == (kmalloc_scrub_pattern & 0xffff0000)) {
  245. dbg() << "Note: Address " << VirtualAddress(fault_address) << " looks like it may be uninitialized kmalloc() memory";
  246. } else if ((fault_address & 0xffff0000) == (kfree_scrub_pattern & 0xffff0000)) {
  247. dbg() << "Note: Address " << VirtualAddress(fault_address) << " looks like it may be recently kfree()'d memory";
  248. } else if ((fault_address & 0xffff0000) == (slab_alloc_scrub_pattern & 0xffff0000)) {
  249. dbg() << "Note: Address " << VirtualAddress(fault_address) << " looks like it may be uninitialized slab_alloc() memory";
  250. } else if ((fault_address & 0xffff0000) == (slab_dealloc_scrub_pattern & 0xffff0000)) {
  251. dbg() << "Note: Address " << VirtualAddress(fault_address) << " looks like it may be recently slab_dealloc()'d memory";
  252. } else if (fault_address < 4096) {
  253. dbg() << "Note: Address " << VirtualAddress(fault_address) << " looks like a possible nullptr dereference";
  254. }
  255. handle_crash(regs, "Page Fault", SIGSEGV, response == PageFaultResponse::OutOfMemory);
  256. } else if (response == PageFaultResponse::Continue) {
  257. #ifdef PAGE_FAULT_DEBUG
  258. dbg() << "Continuing after resolved page fault";
  259. #endif
  260. } else {
  261. ASSERT_NOT_REACHED();
  262. }
  263. }
  264. EH_ENTRY_NO_CODE(1, debug);
  265. void debug_handler(TrapFrame* trap)
  266. {
  267. clac();
  268. auto& regs = *trap->regs;
  269. auto current_thread = Thread::current();
  270. if (&current_thread->process() == nullptr || (regs.cs & 3) == 0) {
  271. klog() << "Debug Exception in Ring0";
  272. Processor::halt();
  273. return;
  274. }
  275. constexpr u8 REASON_SINGLESTEP = 14;
  276. bool is_reason_singlestep = (read_dr6() & (1 << REASON_SINGLESTEP));
  277. if (!is_reason_singlestep)
  278. return;
  279. if (current_thread->tracer()) {
  280. current_thread->tracer()->set_regs(regs);
  281. }
  282. current_thread->send_urgent_signal_to_self(SIGTRAP);
  283. }
  284. EH_ENTRY_NO_CODE(3, breakpoint);
  285. void breakpoint_handler(TrapFrame* trap)
  286. {
  287. clac();
  288. auto& regs = *trap->regs;
  289. auto current_thread = Thread::current();
  290. if (&current_thread->process() == nullptr || (regs.cs & 3) == 0) {
  291. klog() << "Breakpoint Trap in Ring0";
  292. Processor::halt();
  293. return;
  294. }
  295. if (current_thread->tracer()) {
  296. current_thread->tracer()->set_regs(regs);
  297. }
  298. current_thread->send_urgent_signal_to_self(SIGTRAP);
  299. }
  300. #define EH(i, msg) \
  301. static void _exception##i() \
  302. { \
  303. klog() << msg; \
  304. u32 cr0, cr2, cr3, cr4; \
  305. asm("movl %%cr0, %%eax" \
  306. : "=a"(cr0)); \
  307. asm("movl %%cr2, %%eax" \
  308. : "=a"(cr2)); \
  309. asm("movl %%cr3, %%eax" \
  310. : "=a"(cr3)); \
  311. asm("movl %%cr4, %%eax" \
  312. : "=a"(cr4)); \
  313. klog() << "CR0=" << String::format("%x", cr0) << " CR2=" << String::format("%x", cr2) << " CR3=" << String::format("%x", cr3) << " CR4=" << String::format("%x", cr4); \
  314. Processor::halt(); \
  315. }
  316. EH(2, "Unknown error")
  317. EH(4, "Overflow")
  318. EH(5, "Bounds check")
  319. EH(8, "Double fault")
  320. EH(9, "Coprocessor segment overrun")
  321. EH(10, "Invalid TSS")
  322. EH(11, "Segment not present")
  323. EH(12, "Stack exception")
  324. EH(15, "Unknown error")
  325. EH(16, "Coprocessor error")
  326. const DescriptorTablePointer& get_idtr()
  327. {
  328. return s_idtr;
  329. }
  330. static void unimp_trap()
  331. {
  332. klog() << "Unhandled IRQ.";
  333. Processor::Processor::halt();
  334. }
  335. GenericInterruptHandler& get_interrupt_handler(u8 interrupt_number)
  336. {
  337. ASSERT(s_interrupt_handler[interrupt_number] != nullptr);
  338. return *s_interrupt_handler[interrupt_number];
  339. }
  340. static void revert_to_unused_handler(u8 interrupt_number)
  341. {
  342. new UnhandledInterruptHandler(interrupt_number);
  343. }
  344. void register_generic_interrupt_handler(u8 interrupt_number, GenericInterruptHandler& handler)
  345. {
  346. ASSERT(interrupt_number < GENERIC_INTERRUPT_HANDLERS_COUNT);
  347. if (s_interrupt_handler[interrupt_number] != nullptr) {
  348. if (s_interrupt_handler[interrupt_number]->type() == HandlerType::UnhandledInterruptHandler) {
  349. s_interrupt_handler[interrupt_number] = &handler;
  350. return;
  351. }
  352. if (s_interrupt_handler[interrupt_number]->is_shared_handler() && !s_interrupt_handler[interrupt_number]->is_sharing_with_others()) {
  353. ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::SharedIRQHandler);
  354. static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->register_handler(handler);
  355. return;
  356. }
  357. if (!s_interrupt_handler[interrupt_number]->is_shared_handler()) {
  358. ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::IRQHandler);
  359. auto& previous_handler = *s_interrupt_handler[interrupt_number];
  360. s_interrupt_handler[interrupt_number] = nullptr;
  361. SharedIRQHandler::initialize(interrupt_number);
  362. static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->register_handler(previous_handler);
  363. static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->register_handler(handler);
  364. return;
  365. }
  366. ASSERT_NOT_REACHED();
  367. } else {
  368. s_interrupt_handler[interrupt_number] = &handler;
  369. }
  370. }
  371. void unregister_generic_interrupt_handler(u8 interrupt_number, GenericInterruptHandler& handler)
  372. {
  373. ASSERT(s_interrupt_handler[interrupt_number] != nullptr);
  374. if (s_interrupt_handler[interrupt_number]->type() == HandlerType::UnhandledInterruptHandler) {
  375. dbg() << "Trying to unregister unused handler (?)";
  376. return;
  377. }
  378. if (s_interrupt_handler[interrupt_number]->is_shared_handler() && !s_interrupt_handler[interrupt_number]->is_sharing_with_others()) {
  379. ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::SharedIRQHandler);
  380. static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->unregister_handler(handler);
  381. if (!static_cast<SharedIRQHandler*>(s_interrupt_handler[interrupt_number])->sharing_devices_count()) {
  382. revert_to_unused_handler(interrupt_number);
  383. }
  384. return;
  385. }
  386. if (!s_interrupt_handler[interrupt_number]->is_shared_handler()) {
  387. ASSERT(s_interrupt_handler[interrupt_number]->type() == HandlerType::IRQHandler);
  388. revert_to_unused_handler(interrupt_number);
  389. return;
  390. }
  391. ASSERT_NOT_REACHED();
  392. }
  393. void register_interrupt_handler(u8 index, void (*f)())
  394. {
  395. s_idt[index].low = 0x00080000 | LSW((f));
  396. s_idt[index].high = ((u32)(f)&0xffff0000) | 0x8e00;
  397. }
  398. void register_user_callable_interrupt_handler(u8 index, void (*f)())
  399. {
  400. s_idt[index].low = 0x00080000 | LSW((f));
  401. s_idt[index].high = ((u32)(f)&0xffff0000) | 0xef00;
  402. }
  403. void flush_idt()
  404. {
  405. asm("lidt %0" ::"m"(s_idtr));
  406. }
  407. static void idt_init()
  408. {
  409. s_idtr.address = s_idt;
  410. s_idtr.limit = 256 * 8 - 1;
  411. register_interrupt_handler(0x00, divide_error_asm_entry);
  412. register_user_callable_interrupt_handler(0x01, debug_asm_entry);
  413. register_interrupt_handler(0x02, _exception2);
  414. register_user_callable_interrupt_handler(0x03, breakpoint_asm_entry);
  415. register_interrupt_handler(0x04, _exception4);
  416. register_interrupt_handler(0x05, _exception5);
  417. register_interrupt_handler(0x06, illegal_instruction_asm_entry);
  418. register_interrupt_handler(0x07, fpu_exception_asm_entry);
  419. register_interrupt_handler(0x08, _exception8);
  420. register_interrupt_handler(0x09, _exception9);
  421. register_interrupt_handler(0x0a, _exception10);
  422. register_interrupt_handler(0x0b, _exception11);
  423. register_interrupt_handler(0x0c, _exception12);
  424. register_interrupt_handler(0x0d, general_protection_fault_asm_entry);
  425. register_interrupt_handler(0x0e, page_fault_asm_entry);
  426. register_interrupt_handler(0x0f, _exception15);
  427. register_interrupt_handler(0x10, _exception16);
  428. for (u8 i = 0x11; i < 0x50; i++)
  429. register_interrupt_handler(i, unimp_trap);
  430. register_interrupt_handler(0x50, interrupt_80_asm_entry);
  431. register_interrupt_handler(0x51, interrupt_81_asm_entry);
  432. register_interrupt_handler(0x52, interrupt_82_asm_entry);
  433. register_interrupt_handler(0x53, interrupt_83_asm_entry);
  434. register_interrupt_handler(0x54, interrupt_84_asm_entry);
  435. register_interrupt_handler(0x55, interrupt_85_asm_entry);
  436. register_interrupt_handler(0x56, interrupt_86_asm_entry);
  437. register_interrupt_handler(0x57, interrupt_87_asm_entry);
  438. register_interrupt_handler(0x58, interrupt_88_asm_entry);
  439. register_interrupt_handler(0x59, interrupt_89_asm_entry);
  440. register_interrupt_handler(0x5a, interrupt_90_asm_entry);
  441. register_interrupt_handler(0x5b, interrupt_91_asm_entry);
  442. register_interrupt_handler(0x5c, interrupt_92_asm_entry);
  443. register_interrupt_handler(0x5d, interrupt_93_asm_entry);
  444. register_interrupt_handler(0x5e, interrupt_94_asm_entry);
  445. register_interrupt_handler(0x5f, interrupt_95_asm_entry);
  446. register_interrupt_handler(0x60, interrupt_96_asm_entry);
  447. register_interrupt_handler(0x61, interrupt_97_asm_entry);
  448. register_interrupt_handler(0x62, interrupt_98_asm_entry);
  449. register_interrupt_handler(0x63, interrupt_99_asm_entry);
  450. register_interrupt_handler(0x64, interrupt_100_asm_entry);
  451. register_interrupt_handler(0x65, interrupt_101_asm_entry);
  452. register_interrupt_handler(0x66, interrupt_102_asm_entry);
  453. register_interrupt_handler(0x67, interrupt_103_asm_entry);
  454. register_interrupt_handler(0x68, interrupt_104_asm_entry);
  455. register_interrupt_handler(0x69, interrupt_105_asm_entry);
  456. register_interrupt_handler(0x6a, interrupt_106_asm_entry);
  457. register_interrupt_handler(0x6b, interrupt_107_asm_entry);
  458. register_interrupt_handler(0x6c, interrupt_108_asm_entry);
  459. register_interrupt_handler(0x6d, interrupt_109_asm_entry);
  460. register_interrupt_handler(0x6e, interrupt_110_asm_entry);
  461. register_interrupt_handler(0x6f, interrupt_111_asm_entry);
  462. register_interrupt_handler(0x70, interrupt_112_asm_entry);
  463. register_interrupt_handler(0x71, interrupt_113_asm_entry);
  464. register_interrupt_handler(0x72, interrupt_114_asm_entry);
  465. register_interrupt_handler(0x73, interrupt_115_asm_entry);
  466. register_interrupt_handler(0x74, interrupt_116_asm_entry);
  467. register_interrupt_handler(0x75, interrupt_117_asm_entry);
  468. register_interrupt_handler(0x76, interrupt_118_asm_entry);
  469. register_interrupt_handler(0x77, interrupt_119_asm_entry);
  470. register_interrupt_handler(0x78, interrupt_120_asm_entry);
  471. register_interrupt_handler(0x79, interrupt_121_asm_entry);
  472. register_interrupt_handler(0x7a, interrupt_122_asm_entry);
  473. register_interrupt_handler(0x7b, interrupt_123_asm_entry);
  474. register_interrupt_handler(0x7c, interrupt_124_asm_entry);
  475. register_interrupt_handler(0x7d, interrupt_125_asm_entry);
  476. register_interrupt_handler(0x7e, interrupt_126_asm_entry);
  477. register_interrupt_handler(0x7f, interrupt_127_asm_entry);
  478. register_interrupt_handler(0x80, interrupt_128_asm_entry);
  479. register_interrupt_handler(0x81, interrupt_129_asm_entry);
  480. register_interrupt_handler(0x82, interrupt_130_asm_entry);
  481. register_interrupt_handler(0x83, interrupt_131_asm_entry);
  482. register_interrupt_handler(0x84, interrupt_132_asm_entry);
  483. register_interrupt_handler(0x85, interrupt_133_asm_entry);
  484. register_interrupt_handler(0x86, interrupt_134_asm_entry);
  485. register_interrupt_handler(0x87, interrupt_135_asm_entry);
  486. register_interrupt_handler(0x88, interrupt_136_asm_entry);
  487. register_interrupt_handler(0x89, interrupt_137_asm_entry);
  488. register_interrupt_handler(0x8a, interrupt_138_asm_entry);
  489. register_interrupt_handler(0x8b, interrupt_139_asm_entry);
  490. register_interrupt_handler(0x8c, interrupt_140_asm_entry);
  491. register_interrupt_handler(0x8d, interrupt_141_asm_entry);
  492. register_interrupt_handler(0x8e, interrupt_142_asm_entry);
  493. register_interrupt_handler(0x8f, interrupt_143_asm_entry);
  494. register_interrupt_handler(0x90, interrupt_144_asm_entry);
  495. register_interrupt_handler(0x91, interrupt_145_asm_entry);
  496. register_interrupt_handler(0x92, interrupt_146_asm_entry);
  497. register_interrupt_handler(0x93, interrupt_147_asm_entry);
  498. register_interrupt_handler(0x94, interrupt_148_asm_entry);
  499. register_interrupt_handler(0x95, interrupt_149_asm_entry);
  500. register_interrupt_handler(0x96, interrupt_150_asm_entry);
  501. register_interrupt_handler(0x97, interrupt_151_asm_entry);
  502. register_interrupt_handler(0x98, interrupt_152_asm_entry);
  503. register_interrupt_handler(0x99, interrupt_153_asm_entry);
  504. register_interrupt_handler(0x9a, interrupt_154_asm_entry);
  505. register_interrupt_handler(0x9b, interrupt_155_asm_entry);
  506. register_interrupt_handler(0x9c, interrupt_156_asm_entry);
  507. register_interrupt_handler(0x9d, interrupt_157_asm_entry);
  508. register_interrupt_handler(0x9e, interrupt_158_asm_entry);
  509. register_interrupt_handler(0x9f, interrupt_159_asm_entry);
  510. register_interrupt_handler(0xa0, interrupt_160_asm_entry);
  511. register_interrupt_handler(0xa1, interrupt_161_asm_entry);
  512. register_interrupt_handler(0xa2, interrupt_162_asm_entry);
  513. register_interrupt_handler(0xa3, interrupt_163_asm_entry);
  514. register_interrupt_handler(0xa4, interrupt_164_asm_entry);
  515. register_interrupt_handler(0xa5, interrupt_165_asm_entry);
  516. register_interrupt_handler(0xa6, interrupt_166_asm_entry);
  517. register_interrupt_handler(0xa7, interrupt_167_asm_entry);
  518. register_interrupt_handler(0xa8, interrupt_168_asm_entry);
  519. register_interrupt_handler(0xa9, interrupt_169_asm_entry);
  520. register_interrupt_handler(0xaa, interrupt_170_asm_entry);
  521. register_interrupt_handler(0xab, interrupt_171_asm_entry);
  522. register_interrupt_handler(0xac, interrupt_172_asm_entry);
  523. register_interrupt_handler(0xad, interrupt_173_asm_entry);
  524. register_interrupt_handler(0xae, interrupt_174_asm_entry);
  525. register_interrupt_handler(0xaf, interrupt_175_asm_entry);
  526. register_interrupt_handler(0xb0, interrupt_176_asm_entry);
  527. register_interrupt_handler(0xb1, interrupt_177_asm_entry);
  528. register_interrupt_handler(0xb2, interrupt_178_asm_entry);
  529. register_interrupt_handler(0xb3, interrupt_179_asm_entry);
  530. register_interrupt_handler(0xb4, interrupt_180_asm_entry);
  531. register_interrupt_handler(0xb5, interrupt_181_asm_entry);
  532. register_interrupt_handler(0xb6, interrupt_182_asm_entry);
  533. register_interrupt_handler(0xb7, interrupt_183_asm_entry);
  534. register_interrupt_handler(0xb8, interrupt_184_asm_entry);
  535. register_interrupt_handler(0xb9, interrupt_185_asm_entry);
  536. register_interrupt_handler(0xba, interrupt_186_asm_entry);
  537. register_interrupt_handler(0xbb, interrupt_187_asm_entry);
  538. register_interrupt_handler(0xbc, interrupt_188_asm_entry);
  539. register_interrupt_handler(0xbd, interrupt_189_asm_entry);
  540. register_interrupt_handler(0xbe, interrupt_190_asm_entry);
  541. register_interrupt_handler(0xbf, interrupt_191_asm_entry);
  542. register_interrupt_handler(0xc0, interrupt_192_asm_entry);
  543. register_interrupt_handler(0xc1, interrupt_193_asm_entry);
  544. register_interrupt_handler(0xc2, interrupt_194_asm_entry);
  545. register_interrupt_handler(0xc3, interrupt_195_asm_entry);
  546. register_interrupt_handler(0xc4, interrupt_196_asm_entry);
  547. register_interrupt_handler(0xc5, interrupt_197_asm_entry);
  548. register_interrupt_handler(0xc6, interrupt_198_asm_entry);
  549. register_interrupt_handler(0xc7, interrupt_199_asm_entry);
  550. register_interrupt_handler(0xc8, interrupt_200_asm_entry);
  551. register_interrupt_handler(0xc9, interrupt_201_asm_entry);
  552. register_interrupt_handler(0xca, interrupt_202_asm_entry);
  553. register_interrupt_handler(0xcb, interrupt_203_asm_entry);
  554. register_interrupt_handler(0xcc, interrupt_204_asm_entry);
  555. register_interrupt_handler(0xcd, interrupt_205_asm_entry);
  556. register_interrupt_handler(0xce, interrupt_206_asm_entry);
  557. register_interrupt_handler(0xcf, interrupt_207_asm_entry);
  558. register_interrupt_handler(0xd0, interrupt_208_asm_entry);
  559. register_interrupt_handler(0xd1, interrupt_209_asm_entry);
  560. register_interrupt_handler(0xd2, interrupt_210_asm_entry);
  561. register_interrupt_handler(0xd3, interrupt_211_asm_entry);
  562. register_interrupt_handler(0xd4, interrupt_212_asm_entry);
  563. register_interrupt_handler(0xd5, interrupt_213_asm_entry);
  564. register_interrupt_handler(0xd6, interrupt_214_asm_entry);
  565. register_interrupt_handler(0xd7, interrupt_215_asm_entry);
  566. register_interrupt_handler(0xd8, interrupt_216_asm_entry);
  567. register_interrupt_handler(0xd9, interrupt_217_asm_entry);
  568. register_interrupt_handler(0xda, interrupt_218_asm_entry);
  569. register_interrupt_handler(0xdb, interrupt_219_asm_entry);
  570. register_interrupt_handler(0xdc, interrupt_220_asm_entry);
  571. register_interrupt_handler(0xdd, interrupt_221_asm_entry);
  572. register_interrupt_handler(0xde, interrupt_222_asm_entry);
  573. register_interrupt_handler(0xdf, interrupt_223_asm_entry);
  574. register_interrupt_handler(0xe0, interrupt_224_asm_entry);
  575. register_interrupt_handler(0xe1, interrupt_225_asm_entry);
  576. register_interrupt_handler(0xe2, interrupt_226_asm_entry);
  577. register_interrupt_handler(0xe3, interrupt_227_asm_entry);
  578. register_interrupt_handler(0xe4, interrupt_228_asm_entry);
  579. register_interrupt_handler(0xe5, interrupt_229_asm_entry);
  580. register_interrupt_handler(0xe6, interrupt_230_asm_entry);
  581. register_interrupt_handler(0xe7, interrupt_231_asm_entry);
  582. register_interrupt_handler(0xe8, interrupt_232_asm_entry);
  583. register_interrupt_handler(0xe9, interrupt_233_asm_entry);
  584. register_interrupt_handler(0xea, interrupt_234_asm_entry);
  585. register_interrupt_handler(0xeb, interrupt_235_asm_entry);
  586. register_interrupt_handler(0xec, interrupt_236_asm_entry);
  587. register_interrupt_handler(0xed, interrupt_237_asm_entry);
  588. register_interrupt_handler(0xee, interrupt_238_asm_entry);
  589. register_interrupt_handler(0xef, interrupt_239_asm_entry);
  590. register_interrupt_handler(0xf0, interrupt_240_asm_entry);
  591. register_interrupt_handler(0xf1, interrupt_241_asm_entry);
  592. register_interrupt_handler(0xf2, interrupt_242_asm_entry);
  593. register_interrupt_handler(0xf3, interrupt_243_asm_entry);
  594. register_interrupt_handler(0xf4, interrupt_244_asm_entry);
  595. register_interrupt_handler(0xf5, interrupt_245_asm_entry);
  596. register_interrupt_handler(0xf6, interrupt_246_asm_entry);
  597. register_interrupt_handler(0xf7, interrupt_247_asm_entry);
  598. register_interrupt_handler(0xf8, interrupt_248_asm_entry);
  599. register_interrupt_handler(0xf9, interrupt_249_asm_entry);
  600. register_interrupt_handler(0xfa, interrupt_250_asm_entry);
  601. register_interrupt_handler(0xfb, interrupt_251_asm_entry);
  602. register_interrupt_handler(0xfc, interrupt_252_asm_entry);
  603. register_interrupt_handler(0xfd, interrupt_253_asm_entry);
  604. register_interrupt_handler(0xfe, interrupt_254_asm_entry);
  605. register_interrupt_handler(0xff, interrupt_255_asm_entry);
  606. dbg() << "Installing Unhandled Handlers";
  607. for (u8 i = 0; i < GENERIC_INTERRUPT_HANDLERS_COUNT; ++i) {
  608. new UnhandledInterruptHandler(i);
  609. }
  610. flush_idt();
  611. }
  612. void load_task_register(u16 selector)
  613. {
  614. asm("ltr %0" ::"r"(selector));
  615. }
  616. void handle_interrupt(TrapFrame* trap)
  617. {
  618. clac();
  619. auto& regs = *trap->regs;
  620. ASSERT(regs.isr_number >= IRQ_VECTOR_BASE && regs.isr_number <= (IRQ_VECTOR_BASE + GENERIC_INTERRUPT_HANDLERS_COUNT));
  621. u8 irq = (u8)(regs.isr_number - 0x50);
  622. ASSERT(s_interrupt_handler[irq]);
  623. s_interrupt_handler[irq]->handle_interrupt(regs);
  624. s_interrupt_handler[irq]->eoi();
  625. }
  626. void enter_trap_no_irq(TrapFrame* trap)
  627. {
  628. Processor::current().enter_trap(*trap, false);
  629. }
  630. void enter_trap(TrapFrame* trap)
  631. {
  632. Processor::current().enter_trap(*trap, true);
  633. }
  634. void exit_trap(TrapFrame* trap)
  635. {
  636. return Processor::current().exit_trap(*trap);
  637. }
  638. static void sse_init()
  639. {
  640. asm volatile(
  641. "mov %cr0, %eax\n"
  642. "andl $0xfffffffb, %eax\n"
  643. "orl $0x2, %eax\n"
  644. "mov %eax, %cr0\n"
  645. "mov %cr4, %eax\n"
  646. "orl $0x600, %eax\n"
  647. "mov %eax, %cr4\n");
  648. }
  649. u32 read_cr0()
  650. {
  651. u32 cr0;
  652. asm("movl %%cr0, %%eax"
  653. : "=a"(cr0));
  654. return cr0;
  655. }
  656. u32 read_cr3()
  657. {
  658. u32 cr3;
  659. asm("movl %%cr3, %%eax"
  660. : "=a"(cr3));
  661. return cr3;
  662. }
  663. void write_cr3(u32 cr3)
  664. {
  665. asm volatile("movl %%eax, %%cr3" ::"a"(cr3)
  666. : "memory");
  667. }
  668. u32 read_cr4()
  669. {
  670. u32 cr4;
  671. asm("movl %%cr4, %%eax"
  672. : "=a"(cr4));
  673. return cr4;
  674. }
  675. u32 read_dr6()
  676. {
  677. u32 dr6;
  678. asm("movl %%dr6, %%eax"
  679. : "=a"(dr6));
  680. return dr6;
  681. }
  682. FPUState Processor::s_clean_fpu_state;
  683. static Vector<Processor*>* s_processors;
  684. static SpinLock s_processor_lock;
  685. volatile u32 Processor::g_total_processors;
  686. static volatile bool s_smp_enabled;
  687. Vector<Processor*>& Processor::processors()
  688. {
  689. ASSERT(s_processors);
  690. return *s_processors;
  691. }
  692. Processor& Processor::by_id(u32 cpu)
  693. {
  694. // s_processors does not need to be protected by a lock of any kind.
  695. // It is populated early in the boot process, and the BSP is waiting
  696. // for all APs to finish, after which this array never gets modified
  697. // again, so it's safe to not protect access to it here
  698. auto& procs = processors();
  699. ASSERT(procs[cpu] != nullptr);
  700. ASSERT(procs.size() > cpu);
  701. return *procs[cpu];
  702. }
  703. [[noreturn]] static inline void halt_this()
  704. {
  705. for (;;) {
  706. asm volatile("cli; hlt");
  707. }
  708. }
  709. void Processor::cpu_detect()
  710. {
  711. // NOTE: This is called during Processor::early_initialize, we cannot
  712. // safely log at this point because we don't have kmalloc
  713. // initialized yet!
  714. auto set_feature =
  715. [&](CPUFeature f) {
  716. m_features = static_cast<CPUFeature>(static_cast<u32>(m_features) | static_cast<u32>(f));
  717. };
  718. m_features = static_cast<CPUFeature>(0);
  719. CPUID processor_info(0x1);
  720. if (processor_info.edx() & (1 << 6))
  721. set_feature(CPUFeature::PAE);
  722. if (processor_info.edx() & (1 << 13))
  723. set_feature(CPUFeature::PGE);
  724. if (processor_info.edx() & (1 << 25))
  725. set_feature(CPUFeature::SSE);
  726. if (processor_info.edx() & (1 << 4))
  727. set_feature(CPUFeature::TSC);
  728. if (processor_info.ecx() & (1 << 30))
  729. set_feature(CPUFeature::RDRAND);
  730. if (processor_info.edx() & (1 << 11)) {
  731. u32 stepping = processor_info.eax() & 0xf;
  732. u32 model = (processor_info.eax() >> 4) & 0xf;
  733. u32 family = (processor_info.eax() >> 8) & 0xf;
  734. if (!(family == 6 && model < 3 && stepping < 3))
  735. set_feature(CPUFeature::SEP);
  736. }
  737. CPUID extended_processor_info(0x80000001);
  738. if (extended_processor_info.edx() & (1 << 20))
  739. set_feature(CPUFeature::NX);
  740. if (extended_processor_info.edx() & (1 << 11)) {
  741. // Only available in 64 bit mode
  742. set_feature(CPUFeature::SYSCALL);
  743. }
  744. CPUID extended_features(0x7);
  745. if (extended_features.ebx() & (1 << 20))
  746. set_feature(CPUFeature::SMAP);
  747. if (extended_features.ebx() & (1 << 7))
  748. set_feature(CPUFeature::SMEP);
  749. if (extended_features.ecx() & (1 << 2))
  750. set_feature(CPUFeature::UMIP);
  751. if (extended_features.ebx() & (1 << 18))
  752. set_feature(CPUFeature::RDSEED);
  753. }
  754. void Processor::cpu_setup()
  755. {
  756. // NOTE: This is called during Processor::early_initialize, we cannot
  757. // safely log at this point because we don't have kmalloc
  758. // initialized yet!
  759. cpu_detect();
  760. if (has_feature(CPUFeature::SSE))
  761. sse_init();
  762. asm volatile(
  763. "movl %%cr0, %%eax\n"
  764. "orl $0x00010000, %%eax\n"
  765. "movl %%eax, %%cr0\n" ::
  766. : "%eax", "memory");
  767. if (has_feature(CPUFeature::PGE)) {
  768. // Turn on CR4.PGE so the CPU will respect the G bit in page tables.
  769. asm volatile(
  770. "mov %cr4, %eax\n"
  771. "orl $0x80, %eax\n"
  772. "mov %eax, %cr4\n");
  773. }
  774. if (has_feature(CPUFeature::NX)) {
  775. // Turn on IA32_EFER.NXE
  776. asm volatile(
  777. "movl $0xc0000080, %ecx\n"
  778. "rdmsr\n"
  779. "orl $0x800, %eax\n"
  780. "wrmsr\n");
  781. }
  782. if (has_feature(CPUFeature::SMEP)) {
  783. // Turn on CR4.SMEP
  784. asm volatile(
  785. "mov %cr4, %eax\n"
  786. "orl $0x100000, %eax\n"
  787. "mov %eax, %cr4\n");
  788. }
  789. if (has_feature(CPUFeature::SMAP)) {
  790. // Turn on CR4.SMAP
  791. asm volatile(
  792. "mov %cr4, %eax\n"
  793. "orl $0x200000, %eax\n"
  794. "mov %eax, %cr4\n");
  795. }
  796. if (has_feature(CPUFeature::UMIP)) {
  797. asm volatile(
  798. "mov %cr4, %eax\n"
  799. "orl $0x800, %eax\n"
  800. "mov %eax, %cr4\n");
  801. }
  802. if (has_feature(CPUFeature::TSC)) {
  803. asm volatile(
  804. "mov %cr4, %eax\n"
  805. "orl $0x4, %eax\n"
  806. "mov %eax, %cr4\n");
  807. }
  808. }
  809. String Processor::features_string() const
  810. {
  811. StringBuilder builder;
  812. auto feature_to_str =
  813. [](CPUFeature f) -> const char*
  814. {
  815. switch (f) {
  816. case CPUFeature::NX:
  817. return "nx";
  818. case CPUFeature::PAE:
  819. return "pae";
  820. case CPUFeature::PGE:
  821. return "pge";
  822. case CPUFeature::RDRAND:
  823. return "rdrand";
  824. case CPUFeature::RDSEED:
  825. return "rdseed";
  826. case CPUFeature::SMAP:
  827. return "smap";
  828. case CPUFeature::SMEP:
  829. return "smep";
  830. case CPUFeature::SSE:
  831. return "sse";
  832. case CPUFeature::TSC:
  833. return "tsc";
  834. case CPUFeature::UMIP:
  835. return "umip";
  836. case CPUFeature::SEP:
  837. return "sep";
  838. case CPUFeature::SYSCALL:
  839. return "syscall";
  840. // no default statement here intentionally so that we get
  841. // a warning if a new feature is forgotten to be added here
  842. }
  843. // Shouldn't ever happen
  844. return "???";
  845. };
  846. bool first = true;
  847. for (u32 flag = 1; flag < sizeof(m_features) * 8; flag <<= 1) {
  848. if ((static_cast<u32>(m_features) & flag) != 0) {
  849. if (first)
  850. first = false;
  851. else
  852. builder.append(' ');
  853. auto str = feature_to_str(static_cast<CPUFeature>(flag));
  854. builder.append(str, strlen(str));
  855. }
  856. }
  857. return builder.build();
  858. }
  859. void Processor::early_initialize(u32 cpu)
  860. {
  861. m_self = this;
  862. m_cpu = cpu;
  863. m_in_irq = 0;
  864. m_in_critical = 0;
  865. m_invoke_scheduler_async = false;
  866. m_scheduler_initialized = false;
  867. m_message_queue = nullptr;
  868. m_idle_thread = nullptr;
  869. m_current_thread = nullptr;
  870. m_scheduler_data = nullptr;
  871. m_mm_data = nullptr;
  872. m_info = nullptr;
  873. m_halt_requested = false;
  874. if (cpu == 0) {
  875. s_smp_enabled = false;
  876. atomic_store(&g_total_processors, 1u, AK::MemoryOrder::memory_order_release);
  877. } else {
  878. atomic_fetch_add(&g_total_processors, 1u, AK::MemoryOrder::memory_order_acq_rel);
  879. }
  880. cpu_setup();
  881. gdt_init();
  882. ASSERT(&current() == this); // sanity check
  883. }
  884. void Processor::initialize(u32 cpu)
  885. {
  886. ASSERT(m_self == this);
  887. ASSERT(&current() == this); // sanity check
  888. klog() << "CPU[" << id() << "]: Supported features: " << features_string();
  889. if (!has_feature(CPUFeature::RDRAND))
  890. klog() << "CPU[" << id() << "]: No RDRAND support detected, randomness will be poor";
  891. if (cpu == 0)
  892. idt_init();
  893. else
  894. flush_idt();
  895. if (cpu == 0) {
  896. ASSERT((FlatPtr(&s_clean_fpu_state) & 0xF) == 0);
  897. asm volatile("fninit");
  898. asm volatile("fxsave %0"
  899. : "=m"(s_clean_fpu_state));
  900. }
  901. m_info = new ProcessorInfo(*this);
  902. {
  903. ScopedSpinLock lock(s_processor_lock);
  904. // We need to prevent races between APs starting up at the same time
  905. if (!s_processors)
  906. s_processors = new Vector<Processor*>();
  907. if (cpu >= s_processors->size())
  908. s_processors->resize(cpu + 1);
  909. (*s_processors)[cpu] = this;
  910. }
  911. }
  912. void Processor::write_raw_gdt_entry(u16 selector, u32 low, u32 high)
  913. {
  914. u16 i = (selector & 0xfffc) >> 3;
  915. u32 prev_gdt_length = m_gdt_length;
  916. if (i > m_gdt_length) {
  917. m_gdt_length = i + 1;
  918. ASSERT(m_gdt_length <= sizeof(m_gdt) / sizeof(m_gdt[0]));
  919. m_gdtr.limit = (m_gdt_length + 1) * 8 - 1;
  920. }
  921. m_gdt[i].low = low;
  922. m_gdt[i].high = high;
  923. // clear selectors we may have skipped
  924. while (i < prev_gdt_length) {
  925. m_gdt[i].low = 0;
  926. m_gdt[i].high = 0;
  927. i++;
  928. }
  929. }
  930. void Processor::write_gdt_entry(u16 selector, Descriptor& descriptor)
  931. {
  932. write_raw_gdt_entry(selector, descriptor.low, descriptor.high);
  933. }
  934. Descriptor& Processor::get_gdt_entry(u16 selector)
  935. {
  936. u16 i = (selector & 0xfffc) >> 3;
  937. return *(Descriptor*)(&m_gdt[i]);
  938. }
  939. void Processor::flush_gdt()
  940. {
  941. m_gdtr.address = m_gdt;
  942. m_gdtr.limit = (m_gdt_length * 8) - 1;
  943. asm volatile("lgdt %0" ::"m"(m_gdtr)
  944. : "memory");
  945. }
  946. const DescriptorTablePointer& Processor::get_gdtr()
  947. {
  948. return m_gdtr;
  949. }
  950. bool Processor::get_context_frame_ptr(Thread& thread, u32& frame_ptr, u32& eip)
  951. {
  952. ScopedCritical critical;
  953. auto& proc = Processor::current();
  954. if (&thread == proc.current_thread()) {
  955. ASSERT(thread.state() == Thread::Running);
  956. asm volatile("movl %%ebp, %%eax"
  957. : "=g"(frame_ptr));
  958. } else {
  959. // Since the thread may be running on another processor, there
  960. // is a chance a context switch may happen while we're trying
  961. // to get it. It also won't be entirely accurate and merely
  962. // reflect the status at the last context switch.
  963. ScopedSpinLock lock(g_scheduler_lock);
  964. if (thread.state() == Thread::Running) {
  965. ASSERT(thread.cpu() != proc.id());
  966. // TODO: If this is the case, the thread is currently running
  967. // on another processor. We can't trust the kernel stack as
  968. // it may be changing at any time. We need to probably send
  969. // an IPI to that processor, have it walk the stack and wait
  970. // until it returns the data back to us
  971. dbg() << "CPU[" << proc.id() << "] getting stack for "
  972. << thread << " on other CPU# " << thread.cpu() << " not yet implemented!";
  973. frame_ptr = eip = 0; // TODO
  974. return false;
  975. } else {
  976. // We need to retrieve ebp from what was last pushed to the kernel
  977. // stack. Before switching out of that thread, it switch_context
  978. // pushed the callee-saved registers, and the last of them happens
  979. // to be ebp.
  980. auto& tss = thread.tss();
  981. u32* stack_top = reinterpret_cast<u32*>(tss.esp);
  982. frame_ptr = stack_top[0];
  983. eip = tss.eip;
  984. }
  985. }
  986. return true;
  987. }
  988. extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
  989. {
  990. ASSERT(from_thread == to_thread || from_thread->state() != Thread::Running);
  991. ASSERT(to_thread->state() == Thread::Running);
  992. auto& processor = Processor::current();
  993. processor.set_current_thread(*to_thread);
  994. auto& from_tss = from_thread->tss();
  995. auto& to_tss = to_thread->tss();
  996. asm volatile("fxsave %0"
  997. : "=m"(from_thread->fpu_state()));
  998. from_tss.fs = get_fs();
  999. from_tss.gs = get_gs();
  1000. set_fs(to_tss.fs);
  1001. set_gs(to_tss.gs);
  1002. auto& tls_descriptor = processor.get_gdt_entry(GDT_SELECTOR_TLS);
  1003. tls_descriptor.set_base(to_thread->thread_specific_data().as_ptr());
  1004. tls_descriptor.set_limit(to_thread->thread_specific_region_size());
  1005. if (from_tss.cr3 != to_tss.cr3)
  1006. write_cr3(to_tss.cr3);
  1007. to_thread->set_cpu(processor.id());
  1008. asm volatile("fxrstor %0"
  1009. ::"m"(to_thread->fpu_state()));
  1010. // TODO: debug registers
  1011. // TODO: ioperm?
  1012. }
  1013. #define ENTER_THREAD_CONTEXT_ARGS_SIZE (2 * 4) // to_thread, from_thread
  1014. void Processor::switch_context(Thread*& from_thread, Thread*& to_thread)
  1015. {
  1016. ASSERT(!in_irq());
  1017. ASSERT(m_in_critical == 1);
  1018. ASSERT(is_kernel_mode());
  1019. #ifdef CONTEXT_SWITCH_DEBUG
  1020. dbg() << "switch_context --> switching out of: " << VirtualAddress(from_thread) << " " << *from_thread;
  1021. #endif
  1022. // Switch to new thread context, passing from_thread and to_thread
  1023. // through to the new context using registers edx and eax
  1024. asm volatile(
  1025. // NOTE: changing how much we push to the stack affects
  1026. // SWITCH_CONTEXT_TO_STACK_SIZE and thread_context_first_enter()!
  1027. "pushfl \n"
  1028. "pushl %%ebx \n"
  1029. "pushl %%esi \n"
  1030. "pushl %%edi \n"
  1031. "pushl %%ebp \n"
  1032. "movl %%esp, %[from_esp] \n"
  1033. "movl $1f, %[from_eip] \n"
  1034. "movl %[to_esp0], %%ebx \n"
  1035. "movl %%ebx, %[tss_esp0] \n"
  1036. "movl %[to_esp], %%esp \n"
  1037. "pushl %[to_thread] \n"
  1038. "pushl %[from_thread] \n"
  1039. "pushl %[to_eip] \n"
  1040. "cld \n"
  1041. "jmp enter_thread_context \n"
  1042. "1: \n"
  1043. "popl %%edx \n"
  1044. "popl %%eax \n"
  1045. "popl %%ebp \n"
  1046. "popl %%edi \n"
  1047. "popl %%esi \n"
  1048. "popl %%ebx \n"
  1049. "popfl \n"
  1050. : [from_esp] "=m" (from_thread->tss().esp),
  1051. [from_eip] "=m" (from_thread->tss().eip),
  1052. [tss_esp0] "=m" (m_tss.esp0),
  1053. "=d" (from_thread), // needed so that from_thread retains the correct value
  1054. "=a" (to_thread) // needed so that to_thread retains the correct value
  1055. : [to_esp] "g" (to_thread->tss().esp),
  1056. [to_esp0] "g" (to_thread->tss().esp0),
  1057. [to_eip] "c" (to_thread->tss().eip),
  1058. [from_thread] "d" (from_thread),
  1059. [to_thread] "a" (to_thread)
  1060. );
  1061. #ifdef CONTEXT_SWITCH_DEBUG
  1062. dbg() << "switch_context <-- from " << VirtualAddress(from_thread) << " " << *from_thread << " to " << VirtualAddress(to_thread) << " " << *to_thread;
  1063. #endif
  1064. }
  1065. extern "C" void context_first_init(Thread* from_thread, Thread* to_thread, TrapFrame* trap)
  1066. {
  1067. ASSERT(!are_interrupts_enabled());
  1068. ASSERT(is_kernel_mode());
  1069. (void)from_thread;
  1070. (void)to_thread;
  1071. (void)trap;
  1072. #ifdef CONTEXT_SWITCH_DEBUG
  1073. dbg() << "switch_context <-- from " << VirtualAddress(from_thread) << " " << *from_thread << " to " << VirtualAddress(to_thread) << " " << *to_thread << " (context_first_init)";
  1074. #endif
  1075. ASSERT(to_thread == Thread::current());
  1076. Scheduler::enter_current(*from_thread);
  1077. // Since we got here and don't have Scheduler::context_switch in the
  1078. // call stack (because this is the first time we switched into this
  1079. // context), we need to notify the scheduler so that it can release
  1080. // the scheduler lock.
  1081. Scheduler::leave_on_first_switch(trap->regs->eflags);
  1082. }
  1083. extern "C" void thread_context_first_enter(void);
  1084. asm(
  1085. // enter_thread_context returns to here first time a thread is executing
  1086. ".globl thread_context_first_enter \n"
  1087. "thread_context_first_enter: \n"
  1088. // switch_context will have pushed from_thread and to_thread to our new
  1089. // stack prior to thread_context_first_enter() being called, and the
  1090. // pointer to TrapFrame was the top of the stack before that
  1091. " movl 8(%esp), %ebx \n" // save pointer to TrapFrame
  1092. " cld \n"
  1093. " call context_first_init \n"
  1094. " addl $" __STRINGIFY(ENTER_THREAD_CONTEXT_ARGS_SIZE) ", %esp \n"
  1095. " movl %ebx, 0(%esp) \n" // push pointer to TrapFrame
  1096. " jmp common_trap_exit \n"
  1097. );
  1098. u32 Processor::init_context(Thread& thread, bool leave_crit)
  1099. {
  1100. ASSERT(is_kernel_mode());
  1101. ASSERT(g_scheduler_lock.is_locked());
  1102. if (leave_crit) {
  1103. // Leave the critical section we set up in in Process::exec,
  1104. // but because we still have the scheduler lock we should end up with 1
  1105. m_in_critical--; // leave it without triggering anything or restoring flags
  1106. ASSERT(in_critical() == 1);
  1107. }
  1108. const u32 kernel_stack_top = thread.kernel_stack_top();
  1109. u32 stack_top = kernel_stack_top;
  1110. // TODO: handle NT?
  1111. ASSERT((cpu_flags() & 0x24000) == 0); // Assume !(NT | VM)
  1112. auto& tss = thread.tss();
  1113. bool return_to_user = (tss.cs & 3) != 0;
  1114. // make room for an interrupt frame
  1115. if (!return_to_user) {
  1116. // userspace_esp and userspace_ss are not popped off by iret
  1117. // unless we're switching back to user mode
  1118. stack_top -= sizeof(RegisterState) - 2 * sizeof(u32);
  1119. } else {
  1120. stack_top -= sizeof(RegisterState);
  1121. }
  1122. // we want to end up 16-byte aligned, %esp + 4 should be aligned
  1123. stack_top -= sizeof(u32);
  1124. *reinterpret_cast<u32*>(kernel_stack_top - 4) = 0;
  1125. // set up the stack so that after returning from thread_context_first_enter()
  1126. // we will end up either in kernel mode or user mode, depending on how the thread is set up
  1127. // However, the first step is to always start in kernel mode with thread_context_first_enter
  1128. RegisterState& iretframe = *reinterpret_cast<RegisterState*>(stack_top);
  1129. iretframe.ss = tss.ss;
  1130. iretframe.gs = tss.gs;
  1131. iretframe.fs = tss.fs;
  1132. iretframe.es = tss.es;
  1133. iretframe.ds = tss.ds;
  1134. iretframe.edi = tss.edi;
  1135. iretframe.esi = tss.esi;
  1136. iretframe.ebp = tss.ebp;
  1137. iretframe.esp = 0;
  1138. iretframe.ebx = tss.ebx;
  1139. iretframe.edx = tss.edx;
  1140. iretframe.ecx = tss.ecx;
  1141. iretframe.eax = tss.eax;
  1142. iretframe.eflags = tss.eflags;
  1143. iretframe.eip = tss.eip;
  1144. iretframe.cs = tss.cs;
  1145. if (return_to_user) {
  1146. iretframe.userspace_esp = tss.esp;
  1147. iretframe.userspace_ss = tss.ss;
  1148. }
  1149. // make space for a trap frame
  1150. stack_top -= sizeof(TrapFrame);
  1151. TrapFrame& trap = *reinterpret_cast<TrapFrame*>(stack_top);
  1152. trap.regs = &iretframe;
  1153. trap.prev_irq_level = 0;
  1154. stack_top -= sizeof(u32); // pointer to TrapFrame
  1155. *reinterpret_cast<u32*>(stack_top) = stack_top + 4;
  1156. #ifdef CONTEXT_SWITCH_DEBUG
  1157. if (return_to_user)
  1158. dbg() << "init_context " << thread << " (" << VirtualAddress(&thread) << ") set up to execute at eip: " << String::format("%02x:%08x", iretframe.cs, (u32)tss.eip) << " esp: " << VirtualAddress(tss.esp) << " stack top: " << VirtualAddress(stack_top) << " user esp: " << String::format("%02x:%08x", iretframe.userspace_ss, (u32)iretframe.userspace_esp);
  1159. else
  1160. dbg() << "init_context " << thread << " (" << VirtualAddress(&thread) << ") set up to execute at eip: " << String::format("%02x:%08x", iretframe.cs, (u32)tss.eip) << " esp: " << VirtualAddress(tss.esp) << " stack top: " << VirtualAddress(stack_top);
  1161. #endif
  1162. // make switch_context() always first return to thread_context_first_enter()
  1163. // in kernel mode, so set up these values so that we end up popping iretframe
  1164. // off the stack right after the context switch completed, at which point
  1165. // control is transferred to what iretframe is pointing to.
  1166. tss.eip = FlatPtr(&thread_context_first_enter);
  1167. tss.esp0 = kernel_stack_top;
  1168. tss.esp = stack_top;
  1169. tss.cs = GDT_SELECTOR_CODE0;
  1170. tss.ds = GDT_SELECTOR_DATA0;
  1171. tss.es = GDT_SELECTOR_DATA0;
  1172. tss.gs = GDT_SELECTOR_DATA0;
  1173. tss.ss = GDT_SELECTOR_DATA0;
  1174. tss.fs = GDT_SELECTOR_PROC;
  1175. return stack_top;
  1176. }
  1177. extern "C" u32 do_init_context(Thread* thread, u32 flags)
  1178. {
  1179. ASSERT_INTERRUPTS_DISABLED();
  1180. thread->tss().eflags = flags;
  1181. return Processor::current().init_context(*thread, true);
  1182. }
  1183. extern "C" void do_assume_context(Thread* thread, u32 flags);
  1184. asm(
  1185. ".global do_assume_context \n"
  1186. "do_assume_context: \n"
  1187. " movl 4(%esp), %ebx \n"
  1188. " movl 8(%esp), %esi \n"
  1189. // We're going to call Processor::init_context, so just make sure
  1190. // we have enough stack space so we don't stomp over it
  1191. " subl $(" __STRINGIFY(4 + REGISTER_STATE_SIZE + TRAP_FRAME_SIZE + 4) "), %esp \n"
  1192. " pushl %esi \n"
  1193. " pushl %ebx \n"
  1194. " cld \n"
  1195. " call do_init_context \n"
  1196. " addl $8, %esp \n"
  1197. " movl %eax, %esp \n" // move stack pointer to what Processor::init_context set up for us
  1198. " pushl %ebx \n" // push to_thread
  1199. " pushl %ebx \n" // push from_thread
  1200. " pushl $thread_context_first_enter \n" // should be same as tss.eip
  1201. " jmp enter_thread_context \n"
  1202. );
  1203. void Processor::assume_context(Thread& thread, u32 flags)
  1204. {
  1205. #ifdef CONTEXT_SWITCH_DEBUG
  1206. dbg() << "Assume context for thread " << VirtualAddress(&thread) << " " << thread;
  1207. #endif
  1208. ASSERT_INTERRUPTS_DISABLED();
  1209. Scheduler::prepare_after_exec();
  1210. // in_critical() should be 2 here. The critical section in Process::exec
  1211. // and then the scheduler lock
  1212. ASSERT(Processor::current().in_critical() == 2);
  1213. do_assume_context(&thread, flags);
  1214. ASSERT_NOT_REACHED();
  1215. }
  1216. extern "C" void pre_init_finished(void)
  1217. {
  1218. ASSERT(g_scheduler_lock.own_lock());
  1219. // Because init_finished() will wait on the other APs, we need
  1220. // to release the scheduler lock so that the other APs can also get
  1221. // to this point
  1222. // The target flags will get restored upon leaving the trap
  1223. u32 prev_flags = cpu_flags();
  1224. Scheduler::leave_on_first_switch(prev_flags);
  1225. }
  1226. extern "C" void post_init_finished(void)
  1227. {
  1228. // We need to re-acquire the scheduler lock before a context switch
  1229. // transfers control into the idle loop, which needs the lock held
  1230. Scheduler::prepare_for_idle_loop();
  1231. }
  1232. void Processor::initialize_context_switching(Thread& initial_thread)
  1233. {
  1234. ASSERT(initial_thread.process().is_ring0());
  1235. auto& tss = initial_thread.tss();
  1236. m_tss = tss;
  1237. m_tss.esp0 = tss.esp0;
  1238. m_tss.ss0 = GDT_SELECTOR_DATA0;
  1239. // user mode needs to be able to switch to kernel mode:
  1240. m_tss.cs = m_tss.ds = m_tss.es = m_tss.gs = m_tss.ss = GDT_SELECTOR_CODE0 | 3;
  1241. m_tss.fs = GDT_SELECTOR_PROC | 3;
  1242. m_scheduler_initialized = true;
  1243. asm volatile(
  1244. "movl %[new_esp], %%esp \n" // swich to new stack
  1245. "pushl %[from_to_thread] \n" // to_thread
  1246. "pushl %[from_to_thread] \n" // from_thread
  1247. "pushl $" __STRINGIFY(GDT_SELECTOR_CODE0) " \n"
  1248. "pushl %[new_eip] \n" // save the entry eip to the stack
  1249. "movl %%esp, %%ebx \n"
  1250. "addl $20, %%ebx \n" // calculate pointer to TrapFrame
  1251. "pushl %%ebx \n"
  1252. "cld \n"
  1253. "pushl %[cpu] \n" // push argument for init_finished before register is clobbered
  1254. "call pre_init_finished \n"
  1255. "call init_finished \n"
  1256. "addl $4, %%esp \n"
  1257. "call post_init_finished \n"
  1258. "call enter_trap_no_irq \n"
  1259. "addl $4, %%esp \n"
  1260. "lret \n"
  1261. :: [new_esp] "g" (tss.esp),
  1262. [new_eip] "a" (tss.eip),
  1263. [from_to_thread] "b" (&initial_thread),
  1264. [cpu] "c" (id())
  1265. );
  1266. ASSERT_NOT_REACHED();
  1267. }
  1268. void Processor::enter_trap(TrapFrame& trap, bool raise_irq)
  1269. {
  1270. InterruptDisabler disabler;
  1271. trap.prev_irq_level = m_in_irq;
  1272. if (raise_irq)
  1273. m_in_irq++;
  1274. }
  1275. void Processor::exit_trap(TrapFrame& trap)
  1276. {
  1277. InterruptDisabler disabler;
  1278. ASSERT(m_in_irq >= trap.prev_irq_level);
  1279. m_in_irq = trap.prev_irq_level;
  1280. smp_process_pending_messages();
  1281. if (!m_in_irq && !m_in_critical)
  1282. check_invoke_scheduler();
  1283. }
  1284. void Processor::check_invoke_scheduler()
  1285. {
  1286. ASSERT(!m_in_irq);
  1287. ASSERT(!m_in_critical);
  1288. if (m_invoke_scheduler_async && m_scheduler_initialized) {
  1289. m_invoke_scheduler_async = false;
  1290. Scheduler::invoke_async();
  1291. }
  1292. }
  1293. void Processor::flush_tlb_local(VirtualAddress vaddr, size_t page_count)
  1294. {
  1295. auto ptr = vaddr.as_ptr();
  1296. while (page_count > 0) {
  1297. asm volatile("invlpg %0"
  1298. :
  1299. : "m"(*ptr)
  1300. : "memory");
  1301. ptr += PAGE_SIZE;
  1302. page_count--;
  1303. }
  1304. }
  1305. void Processor::flush_tlb(VirtualAddress vaddr, size_t page_count)
  1306. {
  1307. flush_tlb_local(vaddr, page_count);
  1308. if (s_smp_enabled)
  1309. smp_broadcast_flush_tlb(vaddr, page_count);
  1310. }
  1311. static volatile ProcessorMessage* s_message_pool;
  1312. void Processor::smp_return_to_pool(ProcessorMessage& msg)
  1313. {
  1314. ProcessorMessage* next = nullptr;
  1315. do {
  1316. msg.next = next;
  1317. } while (!atomic_compare_exchange_strong(&s_message_pool, next, &msg, AK::MemoryOrder::memory_order_acq_rel));
  1318. }
  1319. ProcessorMessage& Processor::smp_get_from_pool()
  1320. {
  1321. ProcessorMessage* msg;
  1322. // The assumption is that messages are never removed from the pool!
  1323. for (;;) {
  1324. msg = atomic_load(&s_message_pool, AK::MemoryOrder::memory_order_consume);
  1325. if (!msg) {
  1326. if (!Processor::current().smp_process_pending_messages()) {
  1327. // TODO: pause for a bit?
  1328. }
  1329. continue;
  1330. }
  1331. // If another processor were to use this message in the meanwhile,
  1332. // "msg" is still valid (because it never gets freed). We'd detect
  1333. // this because the expected value "msg" and pool would
  1334. // no longer match, and the compare_exchange will fail. But accessing
  1335. // "msg->next" is always safe here.
  1336. if (atomic_compare_exchange_strong(&s_message_pool, msg, msg->next, AK::MemoryOrder::memory_order_acq_rel)) {
  1337. // We successfully "popped" this available message
  1338. break;
  1339. }
  1340. }
  1341. ASSERT(msg != nullptr);
  1342. return *msg;
  1343. }
  1344. void Processor::smp_enable()
  1345. {
  1346. size_t msg_pool_size = Processor::count() * 100u;
  1347. size_t msg_entries_cnt = Processor::count();
  1348. auto msgs = new ProcessorMessage[msg_pool_size];
  1349. auto msg_entries = new ProcessorMessageEntry[msg_pool_size * msg_entries_cnt];
  1350. size_t msg_entry_i = 0;
  1351. for (size_t i = 0; i < msg_pool_size; i++, msg_entry_i += msg_entries_cnt) {
  1352. auto& msg = msgs[i];
  1353. msg.next = i < msg_pool_size - 1 ? &msgs[i + 1] : nullptr;
  1354. msg.per_proc_entries = &msg_entries[msg_entry_i];
  1355. for (size_t k = 0; k < msg_entries_cnt; k++)
  1356. msg_entries[msg_entry_i + k].msg = &msg;
  1357. }
  1358. atomic_store(&s_message_pool, &msgs[0], AK::MemoryOrder::memory_order_release);
  1359. // Start sending IPI messages
  1360. s_smp_enabled = true;
  1361. }
  1362. void Processor::smp_cleanup_message(ProcessorMessage& msg)
  1363. {
  1364. switch (msg.type) {
  1365. case ProcessorMessage::CallbackWithData:
  1366. if (msg.callback_with_data.free)
  1367. msg.callback_with_data.free(msg.callback_with_data.data);
  1368. break;
  1369. default:
  1370. break;
  1371. }
  1372. }
  1373. bool Processor::smp_process_pending_messages()
  1374. {
  1375. bool did_process = false;
  1376. u32 prev_flags;
  1377. enter_critical(prev_flags);
  1378. if (auto pending_msgs = atomic_exchange(&m_message_queue, nullptr, AK::MemoryOrder::memory_order_acq_rel))
  1379. {
  1380. // We pulled the stack of pending messages in LIFO order, so we need to reverse the list first
  1381. auto reverse_list =
  1382. [](ProcessorMessageEntry* list) -> ProcessorMessageEntry*
  1383. {
  1384. ProcessorMessageEntry* rev_list = nullptr;
  1385. while (list) {
  1386. auto next = list->next;
  1387. list->next = rev_list;
  1388. rev_list = list;
  1389. list = next;
  1390. }
  1391. return rev_list;
  1392. };
  1393. pending_msgs = reverse_list(pending_msgs);
  1394. // now process in the right order
  1395. ProcessorMessageEntry* next_msg;
  1396. for (auto cur_msg = pending_msgs; cur_msg; cur_msg = next_msg) {
  1397. next_msg = cur_msg->next;
  1398. auto msg = cur_msg->msg;
  1399. #ifdef SMP_DEBUG
  1400. dbg() << "SMP[" << id() << "]: Processing message " << VirtualAddress(msg);
  1401. #endif
  1402. switch (msg->type) {
  1403. case ProcessorMessage::Callback:
  1404. msg->callback.handler();
  1405. break;
  1406. case ProcessorMessage::CallbackWithData:
  1407. msg->callback_with_data.handler(msg->callback_with_data.data);
  1408. break;
  1409. case ProcessorMessage::FlushTlb:
  1410. flush_tlb_local(VirtualAddress(msg->flush_tlb.ptr), msg->flush_tlb.page_count);
  1411. break;
  1412. }
  1413. bool is_async = msg->async; // Need to cache this value *before* dropping the ref count!
  1414. auto prev_refs = atomic_fetch_sub(&msg->refs, 1u, AK::MemoryOrder::memory_order_acq_rel);
  1415. ASSERT(prev_refs != 0);
  1416. if (prev_refs == 1) {
  1417. // All processors handled this. If this is an async message,
  1418. // we need to clean it up and return it to the pool
  1419. if (is_async) {
  1420. smp_cleanup_message(*msg);
  1421. smp_return_to_pool(*msg);
  1422. }
  1423. }
  1424. if (m_halt_requested)
  1425. halt_this();
  1426. }
  1427. did_process = true;
  1428. } else if (m_halt_requested) {
  1429. halt_this();
  1430. }
  1431. leave_critical(prev_flags);
  1432. return did_process;
  1433. }
  1434. bool Processor::smp_queue_message(ProcessorMessage& msg)
  1435. {
  1436. // Note that it's quite possible that the other processor may pop
  1437. // the queue at any given time. We rely on the fact that the messages
  1438. // are pooled and never get freed!
  1439. auto& msg_entry = msg.per_proc_entries[id()];
  1440. ASSERT(msg_entry.msg == &msg);
  1441. ProcessorMessageEntry* next = nullptr;
  1442. do {
  1443. msg_entry.next = next;
  1444. } while (!atomic_compare_exchange_strong(&m_message_queue, next, &msg_entry, AK::MemoryOrder::memory_order_acq_rel));
  1445. return next == nullptr;
  1446. }
  1447. void Processor::smp_broadcast_message(ProcessorMessage& msg, bool async)
  1448. {
  1449. auto& cur_proc = Processor::current();
  1450. msg.async = async;
  1451. #ifdef SMP_DEBUG
  1452. dbg() << "SMP[" << cur_proc.id() << "]: Broadcast message " << VirtualAddress(&msg) << " to cpus: " << (count()) << " proc: " << VirtualAddress(&cur_proc);
  1453. #endif
  1454. atomic_store(&msg.refs, count() - 1, AK::MemoryOrder::memory_order_release);
  1455. ASSERT(msg.refs > 0);
  1456. for_each(
  1457. [&](Processor& proc) -> IterationDecision
  1458. {
  1459. if (&proc != &cur_proc) {
  1460. if (proc.smp_queue_message(msg)) {
  1461. // TODO: only send IPI to that CPU if we queued the first
  1462. }
  1463. }
  1464. return IterationDecision::Continue;
  1465. });
  1466. // Now trigger an IPI on all other APs
  1467. APIC::the().broadcast_ipi();
  1468. if (!async) {
  1469. // If synchronous then we must cleanup and return the message back
  1470. // to the pool. Otherwise, the last processor to complete it will return it
  1471. while (atomic_load(&msg.refs, AK::MemoryOrder::memory_order_consume) != 0) {
  1472. // TODO: pause for a bit?
  1473. }
  1474. smp_cleanup_message(msg);
  1475. smp_return_to_pool(msg);
  1476. }
  1477. }
  1478. void Processor::smp_broadcast(void (*callback)(void*), void* data, void (*free_data)(void*), bool async)
  1479. {
  1480. auto& msg = smp_get_from_pool();
  1481. msg.type = ProcessorMessage::CallbackWithData;
  1482. msg.callback_with_data.handler = callback;
  1483. msg.callback_with_data.data = data;
  1484. msg.callback_with_data.free = free_data;
  1485. smp_broadcast_message(msg, async);
  1486. }
  1487. void Processor::smp_broadcast(void (*callback)(), bool async)
  1488. {
  1489. auto& msg = smp_get_from_pool();
  1490. msg.type = ProcessorMessage::CallbackWithData;
  1491. msg.callback.handler = callback;
  1492. smp_broadcast_message(msg, async);
  1493. }
  1494. void Processor::smp_broadcast_flush_tlb(VirtualAddress vaddr, size_t page_count)
  1495. {
  1496. auto& msg = smp_get_from_pool();
  1497. msg.type = ProcessorMessage::FlushTlb;
  1498. msg.flush_tlb.ptr = vaddr.as_ptr();
  1499. msg.flush_tlb.page_count = page_count;
  1500. smp_broadcast_message(msg, false);
  1501. }
  1502. void Processor::smp_broadcast_halt()
  1503. {
  1504. // We don't want to use a message, because this could have been triggered
  1505. // by being out of memory and we might not be able to get a message
  1506. for_each(
  1507. [&](Processor& proc) -> IterationDecision
  1508. {
  1509. proc.m_halt_requested = true;
  1510. return IterationDecision::Continue;
  1511. });
  1512. // Now trigger an IPI on all other APs
  1513. APIC::the().broadcast_ipi();
  1514. }
  1515. void Processor::Processor::halt()
  1516. {
  1517. if (s_smp_enabled)
  1518. smp_broadcast_halt();
  1519. halt_this();
  1520. }
  1521. void Processor::gdt_init()
  1522. {
  1523. m_gdt_length = 0;
  1524. m_gdtr.address = nullptr;
  1525. m_gdtr.limit = 0;
  1526. write_raw_gdt_entry(0x0000, 0x00000000, 0x00000000);
  1527. write_raw_gdt_entry(GDT_SELECTOR_CODE0, 0x0000ffff, 0x00cf9a00); // code0
  1528. write_raw_gdt_entry(GDT_SELECTOR_DATA0, 0x0000ffff, 0x00cf9200); // data0
  1529. write_raw_gdt_entry(GDT_SELECTOR_CODE3, 0x0000ffff, 0x00cffa00); // code3
  1530. write_raw_gdt_entry(GDT_SELECTOR_DATA3, 0x0000ffff, 0x00cff200); // data3
  1531. Descriptor tls_descriptor;
  1532. tls_descriptor.low = tls_descriptor.high = 0;
  1533. tls_descriptor.dpl = 3;
  1534. tls_descriptor.segment_present = 1;
  1535. tls_descriptor.granularity = 0;
  1536. tls_descriptor.zero = 0;
  1537. tls_descriptor.operation_size = 1;
  1538. tls_descriptor.descriptor_type = 1;
  1539. tls_descriptor.type = 2;
  1540. write_gdt_entry(GDT_SELECTOR_TLS, tls_descriptor); // tls3
  1541. Descriptor fs_descriptor;
  1542. fs_descriptor.set_base(this);
  1543. fs_descriptor.set_limit(sizeof(Processor));
  1544. fs_descriptor.dpl = 0;
  1545. fs_descriptor.segment_present = 1;
  1546. fs_descriptor.granularity = 0;
  1547. fs_descriptor.zero = 0;
  1548. fs_descriptor.operation_size = 1;
  1549. fs_descriptor.descriptor_type = 1;
  1550. fs_descriptor.type = 2;
  1551. write_gdt_entry(GDT_SELECTOR_PROC, fs_descriptor); // fs0
  1552. Descriptor tss_descriptor;
  1553. tss_descriptor.set_base(&m_tss);
  1554. tss_descriptor.set_limit(sizeof(TSS32));
  1555. tss_descriptor.dpl = 0;
  1556. tss_descriptor.segment_present = 1;
  1557. tss_descriptor.granularity = 0;
  1558. tss_descriptor.zero = 0;
  1559. tss_descriptor.operation_size = 1;
  1560. tss_descriptor.descriptor_type = 0;
  1561. tss_descriptor.type = 9;
  1562. write_gdt_entry(GDT_SELECTOR_TSS, tss_descriptor); // tss
  1563. flush_gdt();
  1564. load_task_register(GDT_SELECTOR_TSS);
  1565. asm volatile(
  1566. "mov %%ax, %%ds\n"
  1567. "mov %%ax, %%es\n"
  1568. "mov %%ax, %%gs\n"
  1569. "mov %%ax, %%ss\n" ::"a"(GDT_SELECTOR_DATA0)
  1570. : "memory");
  1571. set_fs(GDT_SELECTOR_PROC);
  1572. // Make sure CS points to the kernel code descriptor.
  1573. asm volatile(
  1574. "ljmpl $" __STRINGIFY(GDT_SELECTOR_CODE0) ", $sanity\n"
  1575. "sanity:\n");
  1576. }
  1577. void Processor::set_thread_specific(u8* data, size_t len)
  1578. {
  1579. auto& descriptor = get_gdt_entry(GDT_SELECTOR_TLS);
  1580. descriptor.set_base(data);
  1581. descriptor.set_limit(len);
  1582. }
  1583. }
  1584. #ifdef DEBUG
  1585. void __assertion_failed(const char* msg, const char* file, unsigned line, const char* func)
  1586. {
  1587. asm volatile("cli");
  1588. klog() << "ASSERTION FAILED: " << msg << "\n"
  1589. << file << ":" << line << " in " << func;
  1590. // Switch back to the current process's page tables if there are any.
  1591. // Otherwise stack walking will be a disaster.
  1592. auto process = Process::current();
  1593. if (process)
  1594. MM.enter_process_paging_scope(*process);
  1595. Kernel::dump_backtrace();
  1596. asm volatile("hlt");
  1597. for (;;)
  1598. ;
  1599. }
  1600. #endif
  1601. NonMaskableInterruptDisabler::NonMaskableInterruptDisabler()
  1602. {
  1603. IO::out8(0x70, IO::in8(0x70) | 0x80);
  1604. }
  1605. NonMaskableInterruptDisabler::~NonMaskableInterruptDisabler()
  1606. {
  1607. IO::out8(0x70, IO::in8(0x70) & 0x7F);
  1608. }