TimeManagement.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /*
  2. * Copyright (c) 2020, Liav A. <liavalb@hotmail.co.il>
  3. * Copyright (c) 2022, Timon Kruiper <timonkruiper@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Singleton.h>
  8. #include <AK/StdLibExtras.h>
  9. #include <AK/Time.h>
  10. #if ARCH(I386) || ARCH(X86_64)
  11. # include <Kernel/Arch/x86/Time/APICTimer.h>
  12. # include <Kernel/Arch/x86/Time/HPET.h>
  13. # include <Kernel/Arch/x86/Time/HPETComparator.h>
  14. # include <Kernel/Arch/x86/Time/PIT.h>
  15. # include <Kernel/Arch/x86/Time/RTC.h>
  16. # include <Kernel/Arch/x86/common/Interrupts/APIC.h>
  17. # include <Kernel/Arch/x86/common/RTC.h>
  18. #elif ARCH(AARCH64)
  19. # include <Kernel/Arch/aarch64/RPi/Timer.h>
  20. #else
  21. # error Unknown architecture
  22. #endif
  23. #include <Kernel/Arch/CurrentTime.h>
  24. #include <Kernel/CommandLine.h>
  25. #include <Kernel/Firmware/ACPI/Parser.h>
  26. #include <Kernel/InterruptDisabler.h>
  27. #include <Kernel/PerformanceManager.h>
  28. #include <Kernel/Scheduler.h>
  29. #include <Kernel/Sections.h>
  30. #include <Kernel/Time/HardwareTimer.h>
  31. #include <Kernel/Time/TimeManagement.h>
  32. #include <Kernel/TimerQueue.h>
  33. namespace Kernel {
  34. static Singleton<TimeManagement> s_the;
  35. bool TimeManagement::is_initialized()
  36. {
  37. return s_the.is_initialized();
  38. }
  39. TimeManagement& TimeManagement::the()
  40. {
  41. return *s_the;
  42. }
  43. // The s_scheduler_specific_current_time function provides a current time for scheduling purposes,
  44. // which may not necessarily relate to wall time
  45. static u64 (*s_scheduler_current_time)();
  46. static u64 current_time_monotonic()
  47. {
  48. // We always need a precise timestamp here, we cannot rely on a coarse timestamp
  49. return (u64)TimeManagement::the().monotonic_time(TimePrecision::Precise).to_nanoseconds();
  50. }
  51. u64 TimeManagement::scheduler_current_time()
  52. {
  53. VERIFY(s_scheduler_current_time);
  54. return s_scheduler_current_time();
  55. }
  56. ErrorOr<void> TimeManagement::validate_clock_id(clockid_t clock_id)
  57. {
  58. switch (clock_id) {
  59. case CLOCK_MONOTONIC:
  60. case CLOCK_MONOTONIC_COARSE:
  61. case CLOCK_MONOTONIC_RAW:
  62. case CLOCK_REALTIME:
  63. case CLOCK_REALTIME_COARSE:
  64. return {};
  65. default:
  66. return EINVAL;
  67. };
  68. }
  69. Time TimeManagement::current_time(clockid_t clock_id) const
  70. {
  71. switch (clock_id) {
  72. case CLOCK_MONOTONIC:
  73. return monotonic_time(TimePrecision::Precise);
  74. case CLOCK_MONOTONIC_COARSE:
  75. return monotonic_time(TimePrecision::Coarse);
  76. case CLOCK_MONOTONIC_RAW:
  77. return monotonic_time_raw();
  78. case CLOCK_REALTIME:
  79. return epoch_time(TimePrecision::Precise);
  80. case CLOCK_REALTIME_COARSE:
  81. return epoch_time(TimePrecision::Coarse);
  82. default:
  83. // Syscall entrypoint is missing a is_valid_clock_id(..) check?
  84. VERIFY_NOT_REACHED();
  85. }
  86. }
  87. bool TimeManagement::is_system_timer(HardwareTimerBase const& timer) const
  88. {
  89. return &timer == m_system_timer.ptr();
  90. }
  91. void TimeManagement::set_epoch_time(Time ts)
  92. {
  93. InterruptDisabler disabler;
  94. // FIXME: Should use AK::Time internally
  95. m_epoch_time = ts.to_timespec();
  96. m_remaining_epoch_time_adjustment = { 0, 0 };
  97. }
  98. Time TimeManagement::monotonic_time(TimePrecision precision) const
  99. {
  100. // This is the time when last updated by an interrupt.
  101. u64 seconds;
  102. u32 ticks;
  103. bool do_query = precision == TimePrecision::Precise && m_can_query_precise_time;
  104. u32 update_iteration;
  105. do {
  106. update_iteration = m_update1.load(AK::MemoryOrder::memory_order_acquire);
  107. seconds = m_seconds_since_boot;
  108. ticks = m_ticks_this_second;
  109. if (do_query) {
  110. #if ARCH(I386) || ARCH(X86_64)
  111. // We may have to do this over again if the timer interrupt fires
  112. // while we're trying to query the information. In that case, our
  113. // seconds and ticks became invalid, producing an incorrect time.
  114. // Be sure to not modify m_seconds_since_boot and m_ticks_this_second
  115. // because this may only be modified by the interrupt handler
  116. HPET::the().update_time(seconds, ticks, true);
  117. #elif ARCH(AARCH64)
  118. // FIXME: Get rid of these horrible casts
  119. const_cast<RPi::Timer*>(static_cast<RPi::Timer const*>(m_system_timer.ptr()))->update_time(seconds, ticks, true);
  120. #else
  121. # error Unknown architecture
  122. #endif
  123. }
  124. } while (update_iteration != m_update2.load(AK::MemoryOrder::memory_order_acquire));
  125. VERIFY(m_time_ticks_per_second > 0);
  126. VERIFY(ticks < m_time_ticks_per_second);
  127. u64 ns = ((u64)ticks * 1000000000ull) / m_time_ticks_per_second;
  128. VERIFY(ns < 1000000000ull);
  129. return Time::from_timespec({ (i64)seconds, (i32)ns });
  130. }
  131. Time TimeManagement::epoch_time(TimePrecision) const
  132. {
  133. // TODO: Take into account precision
  134. timespec ts;
  135. u32 update_iteration;
  136. do {
  137. update_iteration = m_update1.load(AK::MemoryOrder::memory_order_acquire);
  138. ts = m_epoch_time;
  139. } while (update_iteration != m_update2.load(AK::MemoryOrder::memory_order_acquire));
  140. return Time::from_timespec(ts);
  141. }
  142. u64 TimeManagement::uptime_ms() const
  143. {
  144. auto mtime = monotonic_time().to_timespec();
  145. // This overflows after 292 million years of uptime.
  146. // Since this is only used for performance timestamps and sys$times, that's probably enough.
  147. u64 ms = mtime.tv_sec * 1000ull;
  148. ms += mtime.tv_nsec / 1000000;
  149. return ms;
  150. }
  151. UNMAP_AFTER_INIT void TimeManagement::initialize([[maybe_unused]] u32 cpu)
  152. {
  153. // Note: We must disable interrupts, because the timers interrupt might fire before
  154. // the TimeManagement class is completely initialized.
  155. InterruptDisabler disabler;
  156. #if ARCH(I386) || ARCH(X86_64)
  157. if (cpu == 0) {
  158. VERIFY(!s_the.is_initialized());
  159. s_the.ensure_instance();
  160. if (APIC::initialized()) {
  161. // Initialize the APIC timers after the other timers as the
  162. // initialization needs to briefly enable interrupts, which then
  163. // would trigger a deadlock trying to get the s_the instance while
  164. // creating it.
  165. if (auto* apic_timer = APIC::the().initialize_timers(*s_the->m_system_timer)) {
  166. dmesgln("Time: Using APIC timer as system timer");
  167. s_the->set_system_timer(*apic_timer);
  168. }
  169. }
  170. } else {
  171. VERIFY(s_the.is_initialized());
  172. if (auto* apic_timer = APIC::the().get_timer()) {
  173. dmesgln("Time: Enable APIC timer on CPU #{}", cpu);
  174. apic_timer->enable_local_timer();
  175. }
  176. }
  177. #elif ARCH(AARCH64)
  178. if (cpu == 0) {
  179. VERIFY(!s_the.is_initialized());
  180. s_the.ensure_instance();
  181. }
  182. #else
  183. # error Unknown architecture
  184. #endif
  185. auto* possible_arch_specific_current_time_function = optional_current_time();
  186. if (possible_arch_specific_current_time_function)
  187. s_scheduler_current_time = possible_arch_specific_current_time_function;
  188. else
  189. s_scheduler_current_time = current_time_monotonic;
  190. }
  191. void TimeManagement::set_system_timer(HardwareTimerBase& timer)
  192. {
  193. VERIFY(Processor::is_bootstrap_processor()); // This should only be called on the BSP!
  194. auto original_callback = m_system_timer->set_callback(nullptr);
  195. m_system_timer->disable();
  196. timer.set_callback(move(original_callback));
  197. m_system_timer = timer;
  198. }
  199. time_t TimeManagement::ticks_per_second() const
  200. {
  201. return m_time_keeper_timer->ticks_per_second();
  202. }
  203. time_t TimeManagement::boot_time()
  204. {
  205. #if ARCH(I386) || ARCH(X86_64)
  206. return RTC::boot_time();
  207. #elif ARCH(AARCH64)
  208. TODO_AARCH64();
  209. #else
  210. # error Unknown architecture
  211. #endif
  212. }
  213. UNMAP_AFTER_INIT TimeManagement::TimeManagement()
  214. : m_time_page_region(MM.allocate_kernel_region(PAGE_SIZE, "Time page"sv, Memory::Region::Access::ReadWrite, AllocationStrategy::AllocateNow).release_value_but_fixme_should_propagate_errors())
  215. {
  216. #if ARCH(I386) || ARCH(X86_64)
  217. bool probe_non_legacy_hardware_timers = !(kernel_command_line().is_legacy_time_enabled());
  218. if (ACPI::is_enabled()) {
  219. if (!ACPI::Parser::the()->x86_specific_flags().cmos_rtc_not_present) {
  220. RTC::initialize();
  221. m_epoch_time.tv_sec += boot_time();
  222. } else {
  223. dmesgln("ACPI: RTC CMOS Not present");
  224. }
  225. } else {
  226. // We just assume that we can access RTC CMOS, if ACPI isn't usable.
  227. RTC::initialize();
  228. m_epoch_time.tv_sec += boot_time();
  229. }
  230. if (probe_non_legacy_hardware_timers) {
  231. if (!probe_and_set_x86_non_legacy_hardware_timers())
  232. if (!probe_and_set_x86_legacy_hardware_timers())
  233. VERIFY_NOT_REACHED();
  234. } else if (!probe_and_set_x86_legacy_hardware_timers()) {
  235. VERIFY_NOT_REACHED();
  236. }
  237. #elif ARCH(AARCH64)
  238. probe_and_set_aarch64_hardware_timers();
  239. #else
  240. # error Unknown architecture
  241. #endif
  242. }
  243. Time TimeManagement::now()
  244. {
  245. return s_the.ptr()->epoch_time();
  246. }
  247. UNMAP_AFTER_INIT Vector<HardwareTimerBase*> TimeManagement::scan_and_initialize_periodic_timers()
  248. {
  249. bool should_enable = is_hpet_periodic_mode_allowed();
  250. dbgln("Time: Scanning for periodic timers");
  251. Vector<HardwareTimerBase*> timers;
  252. for (auto& hardware_timer : m_hardware_timers) {
  253. if (hardware_timer.is_periodic_capable()) {
  254. timers.append(&hardware_timer);
  255. if (should_enable)
  256. hardware_timer.set_periodic();
  257. }
  258. }
  259. return timers;
  260. }
  261. UNMAP_AFTER_INIT Vector<HardwareTimerBase*> TimeManagement::scan_for_non_periodic_timers()
  262. {
  263. dbgln("Time: Scanning for non-periodic timers");
  264. Vector<HardwareTimerBase*> timers;
  265. for (auto& hardware_timer : m_hardware_timers) {
  266. if (!hardware_timer.is_periodic_capable())
  267. timers.append(&hardware_timer);
  268. }
  269. return timers;
  270. }
  271. bool TimeManagement::is_hpet_periodic_mode_allowed()
  272. {
  273. switch (kernel_command_line().hpet_mode()) {
  274. case HPETMode::Periodic:
  275. return true;
  276. case HPETMode::NonPeriodic:
  277. return false;
  278. default:
  279. VERIFY_NOT_REACHED();
  280. }
  281. }
  282. #if ARCH(I386) || ARCH(X86_64)
  283. UNMAP_AFTER_INIT bool TimeManagement::probe_and_set_x86_non_legacy_hardware_timers()
  284. {
  285. if (!ACPI::is_enabled())
  286. return false;
  287. if (!HPET::test_and_initialize())
  288. return false;
  289. if (!HPET::the().comparators().size()) {
  290. dbgln("HPET initialization aborted.");
  291. return false;
  292. }
  293. dbgln("HPET: Setting appropriate functions to timers.");
  294. for (auto& hpet_comparator : HPET::the().comparators())
  295. m_hardware_timers.append(hpet_comparator);
  296. auto periodic_timers = scan_and_initialize_periodic_timers();
  297. auto non_periodic_timers = scan_for_non_periodic_timers();
  298. if (is_hpet_periodic_mode_allowed())
  299. VERIFY(!periodic_timers.is_empty());
  300. VERIFY(periodic_timers.size() + non_periodic_timers.size() > 0);
  301. size_t taken_periodic_timers_count = 0;
  302. size_t taken_non_periodic_timers_count = 0;
  303. if (periodic_timers.size() > taken_periodic_timers_count) {
  304. m_system_timer = periodic_timers[taken_periodic_timers_count];
  305. taken_periodic_timers_count += 1;
  306. } else if (non_periodic_timers.size() > taken_non_periodic_timers_count) {
  307. m_system_timer = non_periodic_timers[taken_non_periodic_timers_count];
  308. taken_non_periodic_timers_count += 1;
  309. }
  310. m_system_timer->set_callback([this](RegisterState const& regs) {
  311. // Update the time. We don't really care too much about the
  312. // frequency of the interrupt because we'll query the main
  313. // counter to get an accurate time.
  314. if (Processor::is_bootstrap_processor()) {
  315. // TODO: Have the other CPUs call system_timer_tick directly
  316. increment_time_since_boot_hpet();
  317. }
  318. system_timer_tick(regs);
  319. });
  320. // Use the HPET main counter frequency for time purposes. This is likely
  321. // a much higher frequency than the interrupt itself and allows us to
  322. // keep a more accurate time
  323. m_can_query_precise_time = true;
  324. m_time_ticks_per_second = HPET::the().frequency();
  325. m_system_timer->try_to_set_frequency(m_system_timer->calculate_nearest_possible_frequency(OPTIMAL_TICKS_PER_SECOND_RATE));
  326. // We don't need an interrupt for time keeping purposes because we
  327. // can query the timer.
  328. m_time_keeper_timer = m_system_timer;
  329. if (periodic_timers.size() > taken_periodic_timers_count) {
  330. m_profile_timer = periodic_timers[taken_periodic_timers_count];
  331. taken_periodic_timers_count += 1;
  332. } else if (non_periodic_timers.size() > taken_non_periodic_timers_count) {
  333. m_profile_timer = non_periodic_timers[taken_non_periodic_timers_count];
  334. taken_non_periodic_timers_count += 1;
  335. }
  336. if (m_profile_timer) {
  337. m_profile_timer->set_callback(PerformanceManager::timer_tick);
  338. m_profile_timer->try_to_set_frequency(m_profile_timer->calculate_nearest_possible_frequency(1));
  339. }
  340. return true;
  341. }
  342. UNMAP_AFTER_INIT bool TimeManagement::probe_and_set_x86_legacy_hardware_timers()
  343. {
  344. if (ACPI::is_enabled()) {
  345. if (ACPI::Parser::the()->x86_specific_flags().cmos_rtc_not_present) {
  346. dbgln("ACPI: CMOS RTC Not Present");
  347. return false;
  348. } else {
  349. dbgln("ACPI: CMOS RTC Present");
  350. }
  351. }
  352. m_hardware_timers.append(PIT::initialize(TimeManagement::update_time));
  353. m_hardware_timers.append(RealTimeClock::create(TimeManagement::system_timer_tick));
  354. m_time_keeper_timer = m_hardware_timers[0];
  355. m_system_timer = m_hardware_timers[1];
  356. // The timer is only as accurate as the interrupts...
  357. m_time_ticks_per_second = m_time_keeper_timer->ticks_per_second();
  358. return true;
  359. }
  360. void TimeManagement::update_time(RegisterState const&)
  361. {
  362. TimeManagement::the().increment_time_since_boot();
  363. }
  364. void TimeManagement::increment_time_since_boot_hpet()
  365. {
  366. VERIFY(!m_time_keeper_timer.is_null());
  367. VERIFY(m_time_keeper_timer->timer_type() == HardwareTimerType::HighPrecisionEventTimer);
  368. // NOTE: m_seconds_since_boot and m_ticks_this_second are only ever
  369. // updated here! So we can safely read that information, query the clock,
  370. // and when we're all done we can update the information. This reduces
  371. // contention when other processors attempt to read the clock.
  372. auto seconds_since_boot = m_seconds_since_boot;
  373. auto ticks_this_second = m_ticks_this_second;
  374. auto delta_ns = HPET::the().update_time(seconds_since_boot, ticks_this_second, false);
  375. // Now that we have a precise time, go update it as quickly as we can
  376. u32 update_iteration = m_update2.fetch_add(1, AK::MemoryOrder::memory_order_acquire);
  377. m_seconds_since_boot = seconds_since_boot;
  378. m_ticks_this_second = ticks_this_second;
  379. // TODO: Apply m_remaining_epoch_time_adjustment
  380. timespec_add(m_epoch_time, { (time_t)(delta_ns / 1000000000), (long)(delta_ns % 1000000000) }, m_epoch_time);
  381. m_update1.store(update_iteration + 1, AK::MemoryOrder::memory_order_release);
  382. update_time_page();
  383. }
  384. #elif ARCH(AARCH64)
  385. UNMAP_AFTER_INIT bool TimeManagement::probe_and_set_aarch64_hardware_timers()
  386. {
  387. m_hardware_timers.append(RPi::Timer::initialize());
  388. m_system_timer = m_hardware_timers[0];
  389. m_time_ticks_per_second = m_system_timer->frequency();
  390. m_system_timer->set_callback([this](RegisterState const& regs) {
  391. auto seconds_since_boot = m_seconds_since_boot;
  392. auto ticks_this_second = m_ticks_this_second;
  393. auto delta_ns = static_cast<RPi::Timer*>(m_system_timer.ptr())->update_time(seconds_since_boot, ticks_this_second, false);
  394. u32 update_iteration = m_update2.fetch_add(1, AK::MemoryOrder::memory_order_acquire);
  395. m_seconds_since_boot = seconds_since_boot;
  396. m_ticks_this_second = ticks_this_second;
  397. timespec_add(m_epoch_time, { (time_t)(delta_ns / 1000000000), (long)(delta_ns % 1000000000) }, m_epoch_time);
  398. m_update1.store(update_iteration + 1, AK::MemoryOrder::memory_order_release);
  399. update_time_page();
  400. system_timer_tick(regs);
  401. });
  402. m_time_keeper_timer = m_system_timer;
  403. return true;
  404. }
  405. #else
  406. # error Unknown architecture
  407. #endif
  408. void TimeManagement::increment_time_since_boot()
  409. {
  410. VERIFY(!m_time_keeper_timer.is_null());
  411. // Compute time adjustment for adjtime. Let the clock run up to 1% fast or slow.
  412. // That way, adjtime can adjust up to 36 seconds per hour, without time getting very jumpy.
  413. // Once we have a smarter NTP service that also adjusts the frequency instead of just slewing time, maybe we can lower this.
  414. long NanosPerTick = 1'000'000'000 / m_time_keeper_timer->frequency();
  415. time_t MaxSlewNanos = NanosPerTick / 100;
  416. u32 update_iteration = m_update2.fetch_add(1, AK::MemoryOrder::memory_order_acquire);
  417. // Clamp twice, to make sure intermediate fits into a long.
  418. long slew_nanos = clamp(clamp(m_remaining_epoch_time_adjustment.tv_sec, (time_t)-1, (time_t)1) * 1'000'000'000 + m_remaining_epoch_time_adjustment.tv_nsec, -MaxSlewNanos, MaxSlewNanos);
  419. timespec slew_nanos_ts;
  420. timespec_sub({ 0, slew_nanos }, { 0, 0 }, slew_nanos_ts); // Normalize tv_nsec to be positive.
  421. timespec_sub(m_remaining_epoch_time_adjustment, slew_nanos_ts, m_remaining_epoch_time_adjustment);
  422. timespec epoch_tick = { .tv_sec = 0, .tv_nsec = NanosPerTick };
  423. epoch_tick.tv_nsec += slew_nanos; // No need for timespec_add(), guaranteed to be in range.
  424. timespec_add(m_epoch_time, epoch_tick, m_epoch_time);
  425. if (++m_ticks_this_second >= m_time_keeper_timer->ticks_per_second()) {
  426. // FIXME: Synchronize with other clock somehow to prevent drifting apart.
  427. ++m_seconds_since_boot;
  428. m_ticks_this_second = 0;
  429. }
  430. m_update1.store(update_iteration + 1, AK::MemoryOrder::memory_order_release);
  431. update_time_page();
  432. }
  433. void TimeManagement::system_timer_tick(RegisterState const& regs)
  434. {
  435. if (Processor::current_in_irq() <= 1) {
  436. // Don't expire timers while handling IRQs
  437. TimerQueue::the().fire();
  438. }
  439. Scheduler::timer_tick(regs);
  440. }
  441. bool TimeManagement::enable_profile_timer()
  442. {
  443. if (!m_profile_timer)
  444. return false;
  445. if (m_profile_enable_count.fetch_add(1) == 0)
  446. return m_profile_timer->try_to_set_frequency(m_profile_timer->calculate_nearest_possible_frequency(OPTIMAL_PROFILE_TICKS_PER_SECOND_RATE));
  447. return true;
  448. }
  449. bool TimeManagement::disable_profile_timer()
  450. {
  451. if (!m_profile_timer)
  452. return false;
  453. if (m_profile_enable_count.fetch_sub(1) == 1)
  454. return m_profile_timer->try_to_set_frequency(m_profile_timer->calculate_nearest_possible_frequency(1));
  455. return true;
  456. }
  457. void TimeManagement::update_time_page()
  458. {
  459. auto& page = time_page();
  460. u32 update_iteration = AK::atomic_fetch_add(&page.update2, 1u, AK::MemoryOrder::memory_order_acquire);
  461. page.clocks[CLOCK_REALTIME_COARSE] = m_epoch_time;
  462. page.clocks[CLOCK_MONOTONIC_COARSE] = monotonic_time(TimePrecision::Coarse).to_timespec();
  463. AK::atomic_store(&page.update1, update_iteration + 1u, AK::MemoryOrder::memory_order_release);
  464. }
  465. TimePage& TimeManagement::time_page()
  466. {
  467. return *static_cast<TimePage*>((void*)m_time_page_region->vaddr().as_ptr());
  468. }
  469. Memory::VMObject& TimeManagement::time_page_vmobject()
  470. {
  471. return m_time_page_region->vmobject();
  472. }
  473. }