CPU.cpp 75 KB

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