CPU.cpp 86 KB

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