CPU.cpp 75 KB

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