APIC.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/Memory.h>
  8. #include <AK/Singleton.h>
  9. #include <AK/Types.h>
  10. #include <Kernel/ACPI/Parser.h>
  11. #include <Kernel/Arch/x86/MSR.h>
  12. #include <Kernel/Arch/x86/ProcessorInfo.h>
  13. #include <Kernel/Debug.h>
  14. #include <Kernel/IO.h>
  15. #include <Kernel/Interrupts/APIC.h>
  16. #include <Kernel/Interrupts/SpuriousInterruptHandler.h>
  17. #include <Kernel/Memory/AnonymousVMObject.h>
  18. #include <Kernel/Memory/MemoryManager.h>
  19. #include <Kernel/Memory/PageDirectory.h>
  20. #include <Kernel/Memory/TypedMapping.h>
  21. #include <Kernel/Panic.h>
  22. #include <Kernel/Sections.h>
  23. #include <Kernel/Thread.h>
  24. #include <Kernel/Time/APICTimer.h>
  25. #define IRQ_APIC_TIMER (0xfc - IRQ_VECTOR_BASE)
  26. #define IRQ_APIC_IPI (0xfd - IRQ_VECTOR_BASE)
  27. #define IRQ_APIC_ERR (0xfe - IRQ_VECTOR_BASE)
  28. #define IRQ_APIC_SPURIOUS (0xff - IRQ_VECTOR_BASE)
  29. #define APIC_ICR_DELIVERY_PENDING (1 << 12)
  30. #define APIC_ENABLED (1 << 8)
  31. #define APIC_BASE_MSR 0x1b
  32. #define APIC_REG_EOI 0xb0
  33. #define APIC_REG_LD 0xd0
  34. #define APIC_REG_DF 0xe0
  35. #define APIC_REG_SIV 0xf0
  36. #define APIC_REG_TPR 0x80
  37. #define APIC_REG_ICR_LOW 0x300
  38. #define APIC_REG_ICR_HIGH 0x310
  39. #define APIC_REG_LVT_TIMER 0x320
  40. #define APIC_REG_LVT_THERMAL 0x330
  41. #define APIC_REG_LVT_PERFORMANCE_COUNTER 0x340
  42. #define APIC_REG_LVT_LINT0 0x350
  43. #define APIC_REG_LVT_LINT1 0x360
  44. #define APIC_REG_LVT_ERR 0x370
  45. #define APIC_REG_TIMER_INITIAL_COUNT 0x380
  46. #define APIC_REG_TIMER_CURRENT_COUNT 0x390
  47. #define APIC_REG_TIMER_CONFIGURATION 0x3e0
  48. namespace Kernel {
  49. static Singleton<APIC> s_apic;
  50. class APICIPIInterruptHandler final : public GenericInterruptHandler {
  51. public:
  52. explicit APICIPIInterruptHandler(u8 interrupt_vector)
  53. : GenericInterruptHandler(interrupt_vector, true)
  54. {
  55. }
  56. virtual ~APICIPIInterruptHandler()
  57. {
  58. }
  59. static void initialize(u8 interrupt_number)
  60. {
  61. auto* handler = new APICIPIInterruptHandler(interrupt_number);
  62. handler->register_interrupt_handler();
  63. }
  64. virtual bool handle_interrupt(const RegisterState&) override;
  65. virtual bool eoi() override;
  66. virtual HandlerType type() const override { return HandlerType::IRQHandler; }
  67. virtual StringView purpose() const override { return "IPI Handler"; }
  68. virtual StringView controller() const override { return nullptr; }
  69. virtual size_t sharing_devices_count() const override { return 0; }
  70. virtual bool is_shared_handler() const override { return false; }
  71. virtual bool is_sharing_with_others() const override { return false; }
  72. private:
  73. };
  74. class APICErrInterruptHandler final : public GenericInterruptHandler {
  75. public:
  76. explicit APICErrInterruptHandler(u8 interrupt_vector)
  77. : GenericInterruptHandler(interrupt_vector, true)
  78. {
  79. }
  80. virtual ~APICErrInterruptHandler()
  81. {
  82. }
  83. static void initialize(u8 interrupt_number)
  84. {
  85. auto* handler = new APICErrInterruptHandler(interrupt_number);
  86. handler->register_interrupt_handler();
  87. }
  88. virtual bool handle_interrupt(const RegisterState&) override;
  89. virtual bool eoi() override;
  90. virtual HandlerType type() const override { return HandlerType::IRQHandler; }
  91. virtual StringView purpose() const override { return "SMP Error Handler"; }
  92. virtual StringView controller() const override { return nullptr; }
  93. virtual size_t sharing_devices_count() const override { return 0; }
  94. virtual bool is_shared_handler() const override { return false; }
  95. virtual bool is_sharing_with_others() const override { return false; }
  96. private:
  97. };
  98. bool APIC::initialized()
  99. {
  100. return s_apic.is_initialized();
  101. }
  102. APIC& APIC::the()
  103. {
  104. VERIFY(APIC::initialized());
  105. return *s_apic;
  106. }
  107. UNMAP_AFTER_INIT void APIC::initialize()
  108. {
  109. VERIFY(!APIC::initialized());
  110. s_apic.ensure_instance();
  111. }
  112. PhysicalAddress APIC::get_base()
  113. {
  114. MSR msr(APIC_BASE_MSR);
  115. auto base = msr.get();
  116. return PhysicalAddress(base & 0xfffff000);
  117. }
  118. void APIC::set_base(const PhysicalAddress& base)
  119. {
  120. MSR msr(APIC_BASE_MSR);
  121. msr.set(base.get() | 0x800);
  122. }
  123. void APIC::write_register(u32 offset, u32 value)
  124. {
  125. *reinterpret_cast<volatile u32*>(m_apic_base->vaddr().offset(offset).as_ptr()) = value;
  126. }
  127. u32 APIC::read_register(u32 offset)
  128. {
  129. return *reinterpret_cast<volatile u32*>(m_apic_base->vaddr().offset(offset).as_ptr());
  130. }
  131. void APIC::set_lvt(u32 offset, u8 interrupt)
  132. {
  133. write_register(offset, (read_register(offset) & 0xffffffff) | interrupt);
  134. }
  135. void APIC::set_siv(u32 offset, u8 interrupt)
  136. {
  137. write_register(offset, (read_register(offset) & 0xffffffff) | interrupt | APIC_ENABLED);
  138. }
  139. void APIC::wait_for_pending_icr()
  140. {
  141. while ((read_register(APIC_REG_ICR_LOW) & APIC_ICR_DELIVERY_PENDING) != 0) {
  142. IO::delay(200);
  143. }
  144. }
  145. void APIC::write_icr(const ICRReg& icr)
  146. {
  147. write_register(APIC_REG_ICR_HIGH, icr.high());
  148. write_register(APIC_REG_ICR_LOW, icr.low());
  149. }
  150. #define APIC_LVT_TIMER_ONESHOT 0
  151. #define APIC_LVT_TIMER_PERIODIC (1 << 17)
  152. #define APIC_LVT_TIMER_TSCDEADLINE (1 << 18)
  153. #define APIC_LVT_MASKED (1 << 16)
  154. #define APIC_LVT_TRIGGER_LEVEL (1 << 14)
  155. #define APIC_LVT(iv, dm) (((iv)&0xff) | (((dm)&0x7) << 8))
  156. extern "C" void apic_ap_start(void);
  157. extern "C" u16 apic_ap_start_size;
  158. extern "C" u32 ap_cpu_init_stacks;
  159. extern "C" u32 ap_cpu_init_processor_info_array;
  160. extern "C" u32 ap_cpu_init_cr0;
  161. extern "C" u32 ap_cpu_init_cr3;
  162. extern "C" u32 ap_cpu_init_cr4;
  163. extern "C" u32 ap_cpu_gdtr;
  164. extern "C" u32 ap_cpu_idtr;
  165. void APIC::eoi()
  166. {
  167. write_register(APIC_REG_EOI, 0x0);
  168. }
  169. u8 APIC::spurious_interrupt_vector()
  170. {
  171. return IRQ_APIC_SPURIOUS;
  172. }
  173. #define APIC_INIT_VAR_PTR(tpe, vaddr, varname) \
  174. reinterpret_cast<volatile tpe*>(reinterpret_cast<ptrdiff_t>(vaddr) \
  175. + reinterpret_cast<ptrdiff_t>(&varname) \
  176. - reinterpret_cast<ptrdiff_t>(&apic_ap_start))
  177. UNMAP_AFTER_INIT bool APIC::init_bsp()
  178. {
  179. // FIXME: Use the ACPI MADT table
  180. if (!MSR::have())
  181. return false;
  182. // check if we support local apic
  183. CPUID id(1);
  184. if ((id.edx() & (1 << 9)) == 0)
  185. return false;
  186. PhysicalAddress apic_base = get_base();
  187. dbgln_if(APIC_DEBUG, "Initializing APIC, base: {}", apic_base);
  188. set_base(apic_base);
  189. m_apic_base = MM.allocate_kernel_region(apic_base.page_base(), PAGE_SIZE, {}, Memory::Region::Access::ReadWrite);
  190. if (!m_apic_base) {
  191. dbgln("APIC: Failed to allocate memory for APIC base");
  192. return false;
  193. }
  194. auto rsdp = ACPI::StaticParsing::find_rsdp();
  195. if (!rsdp.has_value()) {
  196. dbgln("APIC: RSDP not found");
  197. return false;
  198. }
  199. auto madt_address = ACPI::StaticParsing::find_table(rsdp.value(), "APIC");
  200. if (madt_address.is_null()) {
  201. dbgln("APIC: MADT table not found");
  202. return false;
  203. }
  204. auto madt = Memory::map_typed<ACPI::Structures::MADT>(madt_address);
  205. size_t entry_index = 0;
  206. size_t entries_length = madt->h.length - sizeof(ACPI::Structures::MADT);
  207. auto* madt_entry = madt->entries;
  208. while (entries_length > 0) {
  209. size_t entry_length = madt_entry->length;
  210. if (madt_entry->type == (u8)ACPI::Structures::MADTEntryType::LocalAPIC) {
  211. auto* plapic_entry = (const ACPI::Structures::MADTEntries::ProcessorLocalAPIC*)madt_entry;
  212. dbgln_if(APIC_DEBUG, "APIC: AP found @ MADT entry {}, processor ID: {}, APIC ID: {}, flags: {:#08x}", entry_index, plapic_entry->acpi_processor_id, plapic_entry->apic_id, plapic_entry->flags);
  213. m_processor_cnt++;
  214. if ((plapic_entry->flags & 0x1) != 0)
  215. m_processor_enabled_cnt++;
  216. }
  217. madt_entry = (ACPI::Structures::MADTEntryHeader*)(VirtualAddress(madt_entry).offset(entry_length).get());
  218. entries_length -= entry_length;
  219. entry_index++;
  220. }
  221. if (m_processor_enabled_cnt < 1)
  222. m_processor_enabled_cnt = 1;
  223. if (m_processor_cnt < 1)
  224. m_processor_cnt = 1;
  225. dbgln("APIC processors found: {}, enabled: {}", m_processor_cnt, m_processor_enabled_cnt);
  226. enable(0);
  227. return true;
  228. }
  229. UNMAP_AFTER_INIT static NonnullOwnPtr<Memory::Region> create_identity_mapped_region(PhysicalAddress paddr, size_t size)
  230. {
  231. auto maybe_vmobject = Memory::AnonymousVMObject::try_create_for_physical_range(paddr, size);
  232. // FIXME: Would be nice to be able to return a KResultOr from here.
  233. VERIFY(!maybe_vmobject.is_error());
  234. auto region = MM.allocate_kernel_region_with_vmobject(
  235. Memory::VirtualRange { VirtualAddress { static_cast<FlatPtr>(paddr.get()) }, size },
  236. maybe_vmobject.release_value(),
  237. {},
  238. Memory::Region::Access::ReadWriteExecute);
  239. VERIFY(region);
  240. return region.release_nonnull();
  241. }
  242. UNMAP_AFTER_INIT void APIC::do_boot_aps()
  243. {
  244. VERIFY(m_processor_enabled_cnt > 1);
  245. u32 aps_to_enable = m_processor_enabled_cnt - 1;
  246. // Copy the APIC startup code and variables to P0x00008000
  247. // Also account for the data appended to:
  248. // * aps_to_enable u32 values for ap_cpu_init_stacks
  249. // * aps_to_enable u32 values for ap_cpu_init_processor_info_array
  250. auto apic_startup_region = create_identity_mapped_region(PhysicalAddress(0x8000), Memory::page_round_up(apic_ap_start_size + (2 * aps_to_enable * sizeof(u32))));
  251. memcpy(apic_startup_region->vaddr().as_ptr(), reinterpret_cast<const void*>(apic_ap_start), apic_ap_start_size);
  252. // Allocate enough stacks for all APs
  253. Vector<OwnPtr<Memory::Region>> apic_ap_stacks;
  254. for (u32 i = 0; i < aps_to_enable; i++) {
  255. auto stack_region = MM.allocate_kernel_region(Thread::default_kernel_stack_size, {}, Memory::Region::Access::ReadWrite, AllocationStrategy::AllocateNow);
  256. if (!stack_region) {
  257. dbgln("APIC: Failed to allocate stack for AP #{}", i);
  258. return;
  259. }
  260. stack_region->set_stack(true);
  261. apic_ap_stacks.append(move(stack_region));
  262. }
  263. // Store pointers to all stacks for the APs to use
  264. auto ap_stack_array = APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_stacks);
  265. VERIFY(aps_to_enable == apic_ap_stacks.size());
  266. for (size_t i = 0; i < aps_to_enable; i++) {
  267. ap_stack_array[i] = apic_ap_stacks[i]->vaddr().get() + Thread::default_kernel_stack_size;
  268. dbgln_if(APIC_DEBUG, "APIC: CPU[{}] stack at {}", i + 1, VirtualAddress { ap_stack_array[i] });
  269. }
  270. // Allocate Processor structures for all APs and store the pointer to the data
  271. m_ap_processor_info.resize(aps_to_enable);
  272. for (size_t i = 0; i < aps_to_enable; i++)
  273. m_ap_processor_info[i] = make<Processor>();
  274. auto ap_processor_info_array = &ap_stack_array[aps_to_enable];
  275. for (size_t i = 0; i < aps_to_enable; i++) {
  276. ap_processor_info_array[i] = FlatPtr(m_ap_processor_info[i].ptr());
  277. dbgln_if(APIC_DEBUG, "APIC: CPU[{}] processor at {}", i + 1, VirtualAddress { ap_processor_info_array[i] });
  278. }
  279. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_processor_info_array) = FlatPtr(&ap_processor_info_array[0]);
  280. // Store the BSP's CR3 value for the APs to use
  281. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_cr3) = MM.kernel_page_directory().cr3();
  282. // Store the BSP's GDT and IDT for the APs to use
  283. const auto& gdtr = Processor::current().get_gdtr();
  284. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_gdtr) = FlatPtr(&gdtr);
  285. const auto& idtr = get_idtr();
  286. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_idtr) = FlatPtr(&idtr);
  287. // Store the BSP's CR0 and CR4 values for the APs to use
  288. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_cr0) = read_cr0();
  289. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_cr4) = read_cr4();
  290. // Create an idle thread for each processor. We have to do this here
  291. // because we won't be able to send FlushTLB messages, so we have to
  292. // have all memory set up for the threads so that when the APs are
  293. // starting up, they can access all the memory properly
  294. m_ap_idle_threads.resize(aps_to_enable);
  295. for (u32 i = 0; i < aps_to_enable; i++)
  296. m_ap_idle_threads[i] = Scheduler::create_ap_idle_thread(i + 1);
  297. dbgln_if(APIC_DEBUG, "APIC: Starting {} AP(s)", aps_to_enable);
  298. // INIT
  299. write_icr(ICRReg(0, ICRReg::INIT, ICRReg::Physical, ICRReg::Assert, ICRReg::TriggerMode::Edge, ICRReg::AllExcludingSelf));
  300. IO::delay(10 * 1000);
  301. for (int i = 0; i < 2; i++) {
  302. // SIPI
  303. write_icr(ICRReg(0x08, ICRReg::StartUp, ICRReg::Physical, ICRReg::Assert, ICRReg::TriggerMode::Edge, ICRReg::AllExcludingSelf)); // start execution at P8000
  304. IO::delay(200);
  305. }
  306. // Now wait until the ap_cpu_init_pending variable dropped to 0, which means all APs are initialized and no longer need these special mappings
  307. if (m_apic_ap_count.load(AK::MemoryOrder::memory_order_consume) != aps_to_enable) {
  308. dbgln_if(APIC_DEBUG, "APIC: Waiting for {} AP(s) to finish initialization...", aps_to_enable);
  309. do {
  310. // Wait a little bit
  311. IO::delay(200);
  312. } while (m_apic_ap_count.load(AK::MemoryOrder::memory_order_consume) != aps_to_enable);
  313. }
  314. dbgln_if(APIC_DEBUG, "APIC: {} processors are initialized and running", m_processor_enabled_cnt);
  315. // NOTE: Since this region is identity-mapped, we have to unmap it manually to prevent the virtual
  316. // address range from leaking into the general virtual range allocator.
  317. apic_startup_region->unmap(Memory::Region::ShouldDeallocateVirtualRange::No);
  318. }
  319. UNMAP_AFTER_INIT void APIC::boot_aps()
  320. {
  321. if (m_processor_enabled_cnt <= 1)
  322. return;
  323. // We split this into another call because do_boot_aps() will cause
  324. // MM calls upon exit, and we don't want to call smp_enable before that
  325. do_boot_aps();
  326. // Enable SMP, which means IPIs may now be sent
  327. Processor::smp_enable();
  328. dbgln_if(APIC_DEBUG, "All processors initialized and waiting, trigger all to continue");
  329. // Now trigger all APs to continue execution (need to do this after
  330. // the regions have been freed so that we don't trigger IPIs
  331. m_apic_ap_continue.store(1, AK::MemoryOrder::memory_order_release);
  332. }
  333. UNMAP_AFTER_INIT void APIC::enable(u32 cpu)
  334. {
  335. if (cpu >= 8) {
  336. // TODO: x2apic support?
  337. PANIC("SMP support is currently limited to 8 CPUs!");
  338. }
  339. // Use the CPU# as logical apic id
  340. VERIFY(cpu <= 0xff);
  341. write_register(APIC_REG_LD, (read_register(APIC_REG_LD) & 0x00ffffff) | (cpu << 24)); // TODO: only if not in x2apic mode
  342. // read it back to make sure it's actually set
  343. auto apic_id = read_register(APIC_REG_LD) >> 24;
  344. Processor::current().info().set_apic_id(apic_id);
  345. dbgln_if(APIC_DEBUG, "Enabling local APIC for CPU #{}, logical APIC ID: {}", cpu, apic_id);
  346. if (cpu == 0) {
  347. SpuriousInterruptHandler::initialize(IRQ_APIC_SPURIOUS);
  348. // set error interrupt vector
  349. set_lvt(APIC_REG_LVT_ERR, IRQ_APIC_ERR);
  350. APICErrInterruptHandler::initialize(IRQ_APIC_ERR);
  351. // register IPI interrupt vector
  352. APICIPIInterruptHandler::initialize(IRQ_APIC_IPI);
  353. }
  354. // set spurious interrupt vector
  355. set_siv(APIC_REG_SIV, IRQ_APIC_SPURIOUS);
  356. // local destination mode (flat mode)
  357. write_register(APIC_REG_DF, 0xf0000000);
  358. write_register(APIC_REG_LVT_TIMER, APIC_LVT(0, 0) | APIC_LVT_MASKED);
  359. write_register(APIC_REG_LVT_THERMAL, APIC_LVT(0, 0) | APIC_LVT_MASKED);
  360. write_register(APIC_REG_LVT_PERFORMANCE_COUNTER, APIC_LVT(0, 0) | APIC_LVT_MASKED);
  361. write_register(APIC_REG_LVT_LINT0, APIC_LVT(0, 7) | APIC_LVT_MASKED);
  362. write_register(APIC_REG_LVT_LINT1, APIC_LVT(0, 0) | APIC_LVT_TRIGGER_LEVEL);
  363. write_register(APIC_REG_TPR, 0);
  364. }
  365. Thread* APIC::get_idle_thread(u32 cpu) const
  366. {
  367. VERIFY(cpu > 0);
  368. return m_ap_idle_threads[cpu - 1];
  369. }
  370. UNMAP_AFTER_INIT void APIC::init_finished(u32 cpu)
  371. {
  372. // This method is called once the boot stack is no longer needed
  373. VERIFY(cpu > 0);
  374. VERIFY(cpu < m_processor_enabled_cnt);
  375. // Since we're waiting on other APs here, we shouldn't have the
  376. // scheduler lock
  377. VERIFY(!g_scheduler_lock.own_lock());
  378. // Notify the BSP that we are done initializing. It will unmap the startup data at P8000
  379. m_apic_ap_count.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  380. dbgln_if(APIC_DEBUG, "APIC: CPU #{} initialized, waiting for all others", cpu);
  381. // The reason we're making all APs wait until the BSP signals them is that
  382. // we don't want APs to trigger IPIs (e.g. through MM) while the BSP
  383. // is unable to process them
  384. while (!m_apic_ap_continue.load(AK::MemoryOrder::memory_order_consume)) {
  385. IO::delay(200);
  386. }
  387. dbgln_if(APIC_DEBUG, "APIC: CPU #{} continues, all others are initialized", cpu);
  388. // do_boot_aps() freed memory, so we need to update our tlb
  389. Processor::flush_entire_tlb_local();
  390. // Now enable all the interrupts
  391. APIC::the().enable(cpu);
  392. }
  393. void APIC::broadcast_ipi()
  394. {
  395. dbgln_if(APIC_SMP_DEBUG, "SMP: Broadcast IPI from CPU #{}", Processor::id());
  396. wait_for_pending_icr();
  397. write_icr(ICRReg(IRQ_APIC_IPI + IRQ_VECTOR_BASE, ICRReg::Fixed, ICRReg::Logical, ICRReg::Assert, ICRReg::TriggerMode::Edge, ICRReg::AllExcludingSelf));
  398. }
  399. void APIC::send_ipi(u32 cpu)
  400. {
  401. dbgln_if(APIC_SMP_DEBUG, "SMP: Send IPI from CPU #{} to CPU #{}", Processor::id(), cpu);
  402. VERIFY(cpu != Processor::id());
  403. VERIFY(cpu < 8);
  404. wait_for_pending_icr();
  405. write_icr(ICRReg(IRQ_APIC_IPI + IRQ_VECTOR_BASE, ICRReg::Fixed, ICRReg::Logical, ICRReg::Assert, ICRReg::TriggerMode::Edge, ICRReg::NoShorthand, cpu));
  406. }
  407. UNMAP_AFTER_INIT APICTimer* APIC::initialize_timers(HardwareTimerBase& calibration_timer)
  408. {
  409. if (!m_apic_base)
  410. return nullptr;
  411. // We should only initialize and calibrate the APIC timer once on the BSP!
  412. VERIFY(Processor::is_bootstrap_processor());
  413. VERIFY(!m_apic_timer);
  414. m_apic_timer = APICTimer::initialize(IRQ_APIC_TIMER, calibration_timer);
  415. return m_apic_timer;
  416. }
  417. void APIC::setup_local_timer(u32 ticks, TimerMode timer_mode, bool enable)
  418. {
  419. u32 flags = 0;
  420. switch (timer_mode) {
  421. case TimerMode::OneShot:
  422. flags |= APIC_LVT_TIMER_ONESHOT;
  423. break;
  424. case TimerMode::Periodic:
  425. flags |= APIC_LVT_TIMER_PERIODIC;
  426. break;
  427. case TimerMode::TSCDeadline:
  428. flags |= APIC_LVT_TIMER_TSCDEADLINE;
  429. break;
  430. }
  431. if (!enable)
  432. flags |= APIC_LVT_MASKED;
  433. write_register(APIC_REG_LVT_TIMER, APIC_LVT(IRQ_APIC_TIMER + IRQ_VECTOR_BASE, 0) | flags);
  434. u32 config = read_register(APIC_REG_TIMER_CONFIGURATION);
  435. config &= ~0xf; // clear divisor (bits 0-3)
  436. switch (get_timer_divisor()) {
  437. case 1:
  438. config |= (1 << 3) | 3;
  439. break;
  440. case 2:
  441. break;
  442. case 4:
  443. config |= 1;
  444. break;
  445. case 8:
  446. config |= 2;
  447. break;
  448. case 16:
  449. config |= 3;
  450. break;
  451. case 32:
  452. config |= (1 << 3);
  453. break;
  454. case 64:
  455. config |= (1 << 3) | 1;
  456. break;
  457. case 128:
  458. config |= (1 << 3) | 2;
  459. break;
  460. default:
  461. VERIFY_NOT_REACHED();
  462. }
  463. write_register(APIC_REG_TIMER_CONFIGURATION, config);
  464. if (timer_mode == TimerMode::Periodic)
  465. write_register(APIC_REG_TIMER_INITIAL_COUNT, ticks / get_timer_divisor());
  466. }
  467. u32 APIC::get_timer_current_count()
  468. {
  469. return read_register(APIC_REG_TIMER_CURRENT_COUNT);
  470. }
  471. u32 APIC::get_timer_divisor()
  472. {
  473. return 16;
  474. }
  475. bool APICIPIInterruptHandler::handle_interrupt(const RegisterState&)
  476. {
  477. dbgln_if(APIC_SMP_DEBUG, "APIC IPI on CPU #{}", Processor::id());
  478. return true;
  479. }
  480. bool APICIPIInterruptHandler::eoi()
  481. {
  482. dbgln_if(APIC_SMP_DEBUG, "SMP: IPI EOI");
  483. APIC::the().eoi();
  484. return true;
  485. }
  486. bool APICErrInterruptHandler::handle_interrupt(const RegisterState&)
  487. {
  488. dbgln("APIC: SMP error on CPU #{}", Processor::id());
  489. return true;
  490. }
  491. bool APICErrInterruptHandler::eoi()
  492. {
  493. APIC::the().eoi();
  494. return true;
  495. }
  496. bool HardwareTimer<GenericInterruptHandler>::eoi()
  497. {
  498. APIC::the().eoi();
  499. return true;
  500. }
  501. }