TimeManagement.cpp 15 KB

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