TimeManagement.cpp 15 KB

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