APIC.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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 AK::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::Read | Memory::Region::Access::Write);
  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 vmobject = Memory::AnonymousVMObject::try_create_for_physical_range(paddr, size);
  232. VERIFY(vmobject);
  233. auto region = MM.allocate_kernel_region_with_vmobject(
  234. Memory::VirtualRange { VirtualAddress { static_cast<FlatPtr>(paddr.get()) }, size },
  235. vmobject.release_nonnull(),
  236. {},
  237. Memory::Region::Access::Read | Memory::Region::Access::Write | Memory::Region::Access::Execute);
  238. VERIFY(region);
  239. return region.release_nonnull();
  240. }
  241. UNMAP_AFTER_INIT void APIC::do_boot_aps()
  242. {
  243. VERIFY(m_processor_enabled_cnt > 1);
  244. u32 aps_to_enable = m_processor_enabled_cnt - 1;
  245. // Copy the APIC startup code and variables to P0x00008000
  246. // Also account for the data appended to:
  247. // * aps_to_enable u32 values for ap_cpu_init_stacks
  248. // * aps_to_enable u32 values for ap_cpu_init_processor_info_array
  249. auto apic_startup_region = create_identity_mapped_region(PhysicalAddress(0x8000), Memory::page_round_up(apic_ap_start_size + (2 * aps_to_enable * sizeof(u32))));
  250. memcpy(apic_startup_region->vaddr().as_ptr(), reinterpret_cast<const void*>(apic_ap_start), apic_ap_start_size);
  251. // Allocate enough stacks for all APs
  252. Vector<OwnPtr<Memory::Region>> apic_ap_stacks;
  253. for (u32 i = 0; i < aps_to_enable; i++) {
  254. auto stack_region = MM.allocate_kernel_region(Thread::default_kernel_stack_size, {}, Memory::Region::Access::Read | Memory::Region::Access::Write, AllocationStrategy::AllocateNow);
  255. if (!stack_region) {
  256. dbgln("APIC: Failed to allocate stack for AP #{}", i);
  257. return;
  258. }
  259. stack_region->set_stack(true);
  260. apic_ap_stacks.append(move(stack_region));
  261. }
  262. // Store pointers to all stacks for the APs to use
  263. auto ap_stack_array = APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_stacks);
  264. VERIFY(aps_to_enable == apic_ap_stacks.size());
  265. for (size_t i = 0; i < aps_to_enable; i++) {
  266. ap_stack_array[i] = apic_ap_stacks[i]->vaddr().get() + Thread::default_kernel_stack_size;
  267. dbgln_if(APIC_DEBUG, "APIC: CPU[{}] stack at {}", i + 1, VirtualAddress { ap_stack_array[i] });
  268. }
  269. // Allocate Processor structures for all APs and store the pointer to the data
  270. m_ap_processor_info.resize(aps_to_enable);
  271. for (size_t i = 0; i < aps_to_enable; i++)
  272. m_ap_processor_info[i] = make<Processor>();
  273. auto ap_processor_info_array = &ap_stack_array[aps_to_enable];
  274. for (size_t i = 0; i < aps_to_enable; i++) {
  275. ap_processor_info_array[i] = FlatPtr(m_ap_processor_info[i].ptr());
  276. dbgln_if(APIC_DEBUG, "APIC: CPU[{}] processor at {}", i + 1, VirtualAddress { ap_processor_info_array[i] });
  277. }
  278. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_processor_info_array) = FlatPtr(&ap_processor_info_array[0]);
  279. // Store the BSP's CR3 value for the APs to use
  280. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_cr3) = MM.kernel_page_directory().cr3();
  281. // Store the BSP's GDT and IDT for the APs to use
  282. const auto& gdtr = Processor::current().get_gdtr();
  283. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_gdtr) = FlatPtr(&gdtr);
  284. const auto& idtr = get_idtr();
  285. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_idtr) = FlatPtr(&idtr);
  286. // Store the BSP's CR0 and CR4 values for the APs to use
  287. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_cr0) = read_cr0();
  288. *APIC_INIT_VAR_PTR(u32, apic_startup_region->vaddr().as_ptr(), ap_cpu_init_cr4) = read_cr4();
  289. // Create an idle thread for each processor. We have to do this here
  290. // because we won't be able to send FlushTLB messages, so we have to
  291. // have all memory set up for the threads so that when the APs are
  292. // starting up, they can access all the memory properly
  293. m_ap_idle_threads.resize(aps_to_enable);
  294. for (u32 i = 0; i < aps_to_enable; i++)
  295. m_ap_idle_threads[i] = Scheduler::create_ap_idle_thread(i + 1);
  296. dbgln_if(APIC_DEBUG, "APIC: Starting {} AP(s)", aps_to_enable);
  297. // INIT
  298. write_icr(ICRReg(0, ICRReg::INIT, ICRReg::Physical, ICRReg::Assert, ICRReg::TriggerMode::Edge, ICRReg::AllExcludingSelf));
  299. IO::delay(10 * 1000);
  300. for (int i = 0; i < 2; i++) {
  301. // SIPI
  302. write_icr(ICRReg(0x08, ICRReg::StartUp, ICRReg::Physical, ICRReg::Assert, ICRReg::TriggerMode::Edge, ICRReg::AllExcludingSelf)); // start execution at P8000
  303. IO::delay(200);
  304. }
  305. // 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
  306. if (m_apic_ap_count.load(AK::MemoryOrder::memory_order_consume) != aps_to_enable) {
  307. dbgln_if(APIC_DEBUG, "APIC: Waiting for {} AP(s) to finish initialization...", aps_to_enable);
  308. do {
  309. // Wait a little bit
  310. IO::delay(200);
  311. } while (m_apic_ap_count.load(AK::MemoryOrder::memory_order_consume) != aps_to_enable);
  312. }
  313. dbgln_if(APIC_DEBUG, "APIC: {} processors are initialized and running", m_processor_enabled_cnt);
  314. // NOTE: Since this region is identity-mapped, we have to unmap it manually to prevent the virtual
  315. // address range from leaking into the general virtual range allocator.
  316. apic_startup_region->unmap(Memory::Region::ShouldDeallocateVirtualRange::No);
  317. }
  318. UNMAP_AFTER_INIT void APIC::boot_aps()
  319. {
  320. if (m_processor_enabled_cnt <= 1)
  321. return;
  322. // We split this into another call because do_boot_aps() will cause
  323. // MM calls upon exit, and we don't want to call smp_enable before that
  324. do_boot_aps();
  325. // Enable SMP, which means IPIs may now be sent
  326. Processor::smp_enable();
  327. dbgln_if(APIC_DEBUG, "All processors initialized and waiting, trigger all to continue");
  328. // Now trigger all APs to continue execution (need to do this after
  329. // the regions have been freed so that we don't trigger IPIs
  330. m_apic_ap_continue.store(1, AK::MemoryOrder::memory_order_release);
  331. }
  332. UNMAP_AFTER_INIT void APIC::enable(u32 cpu)
  333. {
  334. if (cpu >= 8) {
  335. // TODO: x2apic support?
  336. PANIC("SMP support is currently limited to 8 CPUs!");
  337. }
  338. // Use the CPU# as logical apic id
  339. VERIFY(cpu <= 0xff);
  340. write_register(APIC_REG_LD, (read_register(APIC_REG_LD) & 0x00ffffff) | (cpu << 24)); // TODO: only if not in x2apic mode
  341. // read it back to make sure it's actually set
  342. auto apic_id = read_register(APIC_REG_LD) >> 24;
  343. Processor::current().info().set_apic_id(apic_id);
  344. dbgln_if(APIC_DEBUG, "Enabling local APIC for CPU #{}, logical APIC ID: {}", cpu, apic_id);
  345. if (cpu == 0) {
  346. SpuriousInterruptHandler::initialize(IRQ_APIC_SPURIOUS);
  347. // set error interrupt vector
  348. set_lvt(APIC_REG_LVT_ERR, IRQ_APIC_ERR);
  349. APICErrInterruptHandler::initialize(IRQ_APIC_ERR);
  350. // register IPI interrupt vector
  351. APICIPIInterruptHandler::initialize(IRQ_APIC_IPI);
  352. }
  353. // set spurious interrupt vector
  354. set_siv(APIC_REG_SIV, IRQ_APIC_SPURIOUS);
  355. // local destination mode (flat mode)
  356. write_register(APIC_REG_DF, 0xf0000000);
  357. write_register(APIC_REG_LVT_TIMER, APIC_LVT(0, 0) | APIC_LVT_MASKED);
  358. write_register(APIC_REG_LVT_THERMAL, APIC_LVT(0, 0) | APIC_LVT_MASKED);
  359. write_register(APIC_REG_LVT_PERFORMANCE_COUNTER, APIC_LVT(0, 0) | APIC_LVT_MASKED);
  360. write_register(APIC_REG_LVT_LINT0, APIC_LVT(0, 7) | APIC_LVT_MASKED);
  361. write_register(APIC_REG_LVT_LINT1, APIC_LVT(0, 0) | APIC_LVT_TRIGGER_LEVEL);
  362. write_register(APIC_REG_TPR, 0);
  363. }
  364. Thread* APIC::get_idle_thread(u32 cpu) const
  365. {
  366. VERIFY(cpu > 0);
  367. return m_ap_idle_threads[cpu - 1];
  368. }
  369. UNMAP_AFTER_INIT void APIC::init_finished(u32 cpu)
  370. {
  371. // This method is called once the boot stack is no longer needed
  372. VERIFY(cpu > 0);
  373. VERIFY(cpu < m_processor_enabled_cnt);
  374. // Since we're waiting on other APs here, we shouldn't have the
  375. // scheduler lock
  376. VERIFY(!g_scheduler_lock.own_lock());
  377. // Notify the BSP that we are done initializing. It will unmap the startup data at P8000
  378. m_apic_ap_count.fetch_add(1, AK::MemoryOrder::memory_order_acq_rel);
  379. dbgln_if(APIC_DEBUG, "APIC: CPU #{} initialized, waiting for all others", cpu);
  380. // The reason we're making all APs wait until the BSP signals them is that
  381. // we don't want APs to trigger IPIs (e.g. through MM) while the BSP
  382. // is unable to process them
  383. while (!m_apic_ap_continue.load(AK::MemoryOrder::memory_order_consume)) {
  384. IO::delay(200);
  385. }
  386. dbgln_if(APIC_DEBUG, "APIC: CPU #{} continues, all others are initialized", cpu);
  387. // do_boot_aps() freed memory, so we need to update our tlb
  388. Processor::flush_entire_tlb_local();
  389. // Now enable all the interrupts
  390. APIC::the().enable(cpu);
  391. }
  392. void APIC::broadcast_ipi()
  393. {
  394. dbgln_if(APIC_SMP_DEBUG, "SMP: Broadcast IPI from CPU #{}", Processor::id());
  395. wait_for_pending_icr();
  396. write_icr(ICRReg(IRQ_APIC_IPI + IRQ_VECTOR_BASE, ICRReg::Fixed, ICRReg::Logical, ICRReg::Assert, ICRReg::TriggerMode::Edge, ICRReg::AllExcludingSelf));
  397. }
  398. void APIC::send_ipi(u32 cpu)
  399. {
  400. dbgln_if(APIC_SMP_DEBUG, "SMP: Send IPI from CPU #{} to CPU #{}", Processor::id(), cpu);
  401. VERIFY(cpu != Processor::id());
  402. VERIFY(cpu < 8);
  403. wait_for_pending_icr();
  404. write_icr(ICRReg(IRQ_APIC_IPI + IRQ_VECTOR_BASE, ICRReg::Fixed, ICRReg::Logical, ICRReg::Assert, ICRReg::TriggerMode::Edge, ICRReg::NoShorthand, cpu));
  405. }
  406. UNMAP_AFTER_INIT APICTimer* APIC::initialize_timers(HardwareTimerBase& calibration_timer)
  407. {
  408. if (!m_apic_base)
  409. return nullptr;
  410. // We should only initialize and calibrate the APIC timer once on the BSP!
  411. VERIFY(Processor::is_bootstrap_processor());
  412. VERIFY(!m_apic_timer);
  413. m_apic_timer = APICTimer::initialize(IRQ_APIC_TIMER, calibration_timer);
  414. return m_apic_timer;
  415. }
  416. void APIC::setup_local_timer(u32 ticks, TimerMode timer_mode, bool enable)
  417. {
  418. u32 flags = 0;
  419. switch (timer_mode) {
  420. case TimerMode::OneShot:
  421. flags |= APIC_LVT_TIMER_ONESHOT;
  422. break;
  423. case TimerMode::Periodic:
  424. flags |= APIC_LVT_TIMER_PERIODIC;
  425. break;
  426. case TimerMode::TSCDeadline:
  427. flags |= APIC_LVT_TIMER_TSCDEADLINE;
  428. break;
  429. }
  430. if (!enable)
  431. flags |= APIC_LVT_MASKED;
  432. write_register(APIC_REG_LVT_TIMER, APIC_LVT(IRQ_APIC_TIMER + IRQ_VECTOR_BASE, 0) | flags);
  433. u32 config = read_register(APIC_REG_TIMER_CONFIGURATION);
  434. config &= ~0xf; // clear divisor (bits 0-3)
  435. switch (get_timer_divisor()) {
  436. case 1:
  437. config |= (1 << 3) | 3;
  438. break;
  439. case 2:
  440. break;
  441. case 4:
  442. config |= 1;
  443. break;
  444. case 8:
  445. config |= 2;
  446. break;
  447. case 16:
  448. config |= 3;
  449. break;
  450. case 32:
  451. config |= (1 << 3);
  452. break;
  453. case 64:
  454. config |= (1 << 3) | 1;
  455. break;
  456. case 128:
  457. config |= (1 << 3) | 2;
  458. break;
  459. default:
  460. VERIFY_NOT_REACHED();
  461. }
  462. write_register(APIC_REG_TIMER_CONFIGURATION, config);
  463. if (timer_mode == TimerMode::Periodic)
  464. write_register(APIC_REG_TIMER_INITIAL_COUNT, ticks / get_timer_divisor());
  465. }
  466. u32 APIC::get_timer_current_count()
  467. {
  468. return read_register(APIC_REG_TIMER_CURRENT_COUNT);
  469. }
  470. u32 APIC::get_timer_divisor()
  471. {
  472. return 16;
  473. }
  474. bool APICIPIInterruptHandler::handle_interrupt(const RegisterState&)
  475. {
  476. dbgln_if(APIC_SMP_DEBUG, "APIC IPI on CPU #{}", Processor::id());
  477. return true;
  478. }
  479. bool APICIPIInterruptHandler::eoi()
  480. {
  481. dbgln_if(APIC_SMP_DEBUG, "SMP: IPI EOI");
  482. APIC::the().eoi();
  483. return true;
  484. }
  485. bool APICErrInterruptHandler::handle_interrupt(const RegisterState&)
  486. {
  487. dbgln("APIC: SMP error on CPU #{}", Processor::id());
  488. return true;
  489. }
  490. bool APICErrInterruptHandler::eoi()
  491. {
  492. APIC::the().eoi();
  493. return true;
  494. }
  495. bool HardwareTimer<GenericInterruptHandler>::eoi()
  496. {
  497. APIC::the().eoi();
  498. return true;
  499. }
  500. }