TimeManagement.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. * Copyright (c) 2020, Liav A. <liavalb@hotmail.co.il>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Singleton.h>
  27. #include <AK/StdLibExtras.h>
  28. #include <AK/Time.h>
  29. #include <Kernel/ACPI/Parser.h>
  30. #include <Kernel/CommandLine.h>
  31. #include <Kernel/Interrupts/APIC.h>
  32. #include <Kernel/Scheduler.h>
  33. #include <Kernel/Time/APICTimer.h>
  34. #include <Kernel/Time/HPET.h>
  35. #include <Kernel/Time/HPETComparator.h>
  36. #include <Kernel/Time/HardwareTimer.h>
  37. #include <Kernel/Time/PIT.h>
  38. #include <Kernel/Time/RTC.h>
  39. #include <Kernel/Time/TimeManagement.h>
  40. #include <Kernel/TimerQueue.h>
  41. #include <Kernel/VM/MemoryManager.h>
  42. //#define TIME_DEBUG
  43. namespace Kernel {
  44. static AK::Singleton<TimeManagement> s_the;
  45. TimeManagement& TimeManagement::the()
  46. {
  47. return *s_the;
  48. }
  49. bool TimeManagement::is_valid_clock_id(clockid_t clock_id)
  50. {
  51. switch (clock_id) {
  52. case CLOCK_MONOTONIC:
  53. case CLOCK_MONOTONIC_COARSE:
  54. case CLOCK_MONOTONIC_RAW:
  55. case CLOCK_REALTIME:
  56. case CLOCK_REALTIME_COARSE:
  57. return true;
  58. default:
  59. return false;
  60. };
  61. }
  62. KResultOr<timespec> TimeManagement::current_time(clockid_t clock_id) const
  63. {
  64. switch (clock_id) {
  65. case CLOCK_MONOTONIC:
  66. return monotonic_time(TimePrecision::Precise);
  67. case CLOCK_MONOTONIC_COARSE:
  68. return monotonic_time(TimePrecision::Coarse);
  69. case CLOCK_MONOTONIC_RAW:
  70. return monotonic_time_raw();
  71. case CLOCK_REALTIME:
  72. return epoch_time(TimePrecision::Precise);
  73. case CLOCK_REALTIME_COARSE:
  74. return epoch_time(TimePrecision::Coarse);
  75. default:
  76. return KResult(EINVAL);
  77. }
  78. }
  79. bool TimeManagement::is_system_timer(const HardwareTimerBase& timer) const
  80. {
  81. return &timer == m_system_timer.ptr();
  82. }
  83. void TimeManagement::set_epoch_time(timespec ts)
  84. {
  85. InterruptDisabler disabler;
  86. m_epoch_time = ts;
  87. m_remaining_epoch_time_adjustment = { 0, 0 };
  88. }
  89. timespec TimeManagement::monotonic_time(TimePrecision precision) const
  90. {
  91. // This is the time when last updated by an interrupt.
  92. u64 seconds;
  93. u32 ticks;
  94. bool do_query = precision == TimePrecision::Precise && m_can_query_precise_time;
  95. u32 update_iteration;
  96. do {
  97. update_iteration = m_update1.load(AK::MemoryOrder::memory_order_acquire);
  98. seconds = m_seconds_since_boot;
  99. ticks = m_ticks_this_second;
  100. if (do_query) {
  101. // We may have to do this over again if the timer interrupt fires
  102. // while we're trying to query the information. In that case, our
  103. // seconds and ticks became invalid, producing an incorrect time.
  104. // Be sure to not modify m_seconds_since_boot and m_ticks_this_second
  105. // because this may only be modified by the interrupt handler
  106. HPET::the().update_time(seconds, ticks, true);
  107. }
  108. } while (update_iteration != m_update2.load(AK::MemoryOrder::memory_order_acquire));
  109. ASSERT(m_time_ticks_per_second > 0);
  110. ASSERT(ticks < m_time_ticks_per_second);
  111. u64 ns = ((u64)ticks * 1000000000ull) / m_time_ticks_per_second;
  112. ASSERT(ns < 1000000000ull);
  113. return { (long)seconds, (long)ns };
  114. }
  115. timespec TimeManagement::epoch_time(TimePrecision) const
  116. {
  117. // TODO: Take into account precision
  118. timespec ts;
  119. u32 update_iteration;
  120. do {
  121. update_iteration = m_update1.load(AK::MemoryOrder::memory_order_acquire);
  122. ts = m_epoch_time;
  123. } while (update_iteration != m_update2.load(AK::MemoryOrder::memory_order_acquire));
  124. return ts;
  125. }
  126. u64 TimeManagement::uptime_ms() const
  127. {
  128. auto mtime = monotonic_time();
  129. u64 ms = mtime.tv_sec * 1000ull;
  130. ms += mtime.tv_nsec / 1000000;
  131. return ms;
  132. }
  133. void TimeManagement::initialize(u32 cpu)
  134. {
  135. if (cpu == 0) {
  136. ASSERT(!s_the.is_initialized());
  137. s_the.ensure_instance();
  138. // Initialize the APIC timers after the other timers as the
  139. // initialization needs to briefly enable interrupts, which then
  140. // would trigger a deadlock trying to get the s_the instance while
  141. // creating it.
  142. if (auto* apic_timer = APIC::the().initialize_timers(*s_the->m_system_timer)) {
  143. klog() << "Time: Using APIC timer as system timer";
  144. s_the->set_system_timer(*apic_timer);
  145. }
  146. } else {
  147. ASSERT(s_the.is_initialized());
  148. if (auto* apic_timer = APIC::the().get_timer()) {
  149. klog() << "Time: Enable APIC timer on CPU #" << cpu;
  150. apic_timer->enable_local_timer();
  151. }
  152. }
  153. }
  154. void TimeManagement::set_system_timer(HardwareTimerBase& timer)
  155. {
  156. ASSERT(Processor::current().id() == 0); // This should only be called on the BSP!
  157. auto original_callback = m_system_timer->set_callback(nullptr);
  158. m_system_timer->disable();
  159. timer.set_callback(move(original_callback));
  160. m_system_timer = timer;
  161. }
  162. time_t TimeManagement::ticks_per_second() const
  163. {
  164. return m_time_keeper_timer->ticks_per_second();
  165. }
  166. time_t TimeManagement::boot_time() const
  167. {
  168. return RTC::boot_time();
  169. }
  170. TimeManagement::TimeManagement()
  171. {
  172. bool probe_non_legacy_hardware_timers = !(kernel_command_line().lookup("time").value_or("modern") == "legacy");
  173. if (ACPI::is_enabled()) {
  174. if (!ACPI::Parser::the()->x86_specific_flags().cmos_rtc_not_present) {
  175. RTC::initialize();
  176. m_epoch_time.tv_sec += boot_time();
  177. } else {
  178. klog() << "ACPI: RTC CMOS Not present";
  179. }
  180. } else {
  181. // We just assume that we can access RTC CMOS, if ACPI isn't usable.
  182. RTC::initialize();
  183. m_epoch_time.tv_sec += boot_time();
  184. }
  185. if (probe_non_legacy_hardware_timers) {
  186. if (!probe_and_set_non_legacy_hardware_timers())
  187. if (!probe_and_set_legacy_hardware_timers())
  188. ASSERT_NOT_REACHED();
  189. } else if (!probe_and_set_legacy_hardware_timers()) {
  190. ASSERT_NOT_REACHED();
  191. }
  192. }
  193. timeval TimeManagement::now_as_timeval()
  194. {
  195. timespec ts = s_the.ptr()->epoch_time();
  196. timeval tv;
  197. timespec_to_timeval(ts, tv);
  198. return tv;
  199. }
  200. Vector<HardwareTimerBase*> TimeManagement::scan_and_initialize_periodic_timers()
  201. {
  202. bool should_enable = is_hpet_periodic_mode_allowed();
  203. dbg() << "Time: Scanning for 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. if (should_enable)
  209. hardware_timer.set_periodic();
  210. }
  211. }
  212. return timers;
  213. }
  214. Vector<HardwareTimerBase*> TimeManagement::scan_for_non_periodic_timers()
  215. {
  216. dbg() << "Time: Scanning for non-periodic timers";
  217. Vector<HardwareTimerBase*> timers;
  218. for (auto& hardware_timer : m_hardware_timers) {
  219. if (!hardware_timer.is_periodic_capable())
  220. timers.append(&hardware_timer);
  221. }
  222. return timers;
  223. }
  224. bool TimeManagement::is_hpet_periodic_mode_allowed()
  225. {
  226. auto hpet_mode = kernel_command_line().lookup("hpet").value_or("periodic");
  227. if (hpet_mode == "periodic")
  228. return true;
  229. if (hpet_mode == "nonperiodic")
  230. return false;
  231. ASSERT_NOT_REACHED();
  232. }
  233. bool TimeManagement::probe_and_set_non_legacy_hardware_timers()
  234. {
  235. if (!ACPI::is_enabled())
  236. return false;
  237. if (!HPET::test_and_initialize())
  238. return false;
  239. if (!HPET::the().comparators().size()) {
  240. dbg() << "HPET initialization aborted.";
  241. return false;
  242. }
  243. dbg() << "HPET: Setting appropriate functions to timers.";
  244. for (auto& hpet_comparator : HPET::the().comparators())
  245. m_hardware_timers.append(hpet_comparator);
  246. auto periodic_timers = scan_and_initialize_periodic_timers();
  247. auto non_periodic_timers = scan_for_non_periodic_timers();
  248. if (is_hpet_periodic_mode_allowed())
  249. ASSERT(!periodic_timers.is_empty());
  250. ASSERT(periodic_timers.size() + non_periodic_timers.size() > 0);
  251. if (periodic_timers.size() > 0)
  252. m_system_timer = periodic_timers[0];
  253. else
  254. m_system_timer = non_periodic_timers[0];
  255. m_system_timer->set_callback([this](const RegisterState& regs) {
  256. // Update the time. We don't really care too much about the
  257. // frequency of the interrupt because we'll query the main
  258. // counter to get an accurate time.
  259. if (Processor::current().id() == 0) {
  260. // TODO: Have the other CPUs call system_timer_tick directly
  261. increment_time_since_boot_hpet();
  262. }
  263. system_timer_tick(regs);
  264. });
  265. // Use the HPET main counter frequency for time purposes. This is likely
  266. // a much higher frequency than the interrupt itself and allows us to
  267. // keep a more accurate time
  268. m_can_query_precise_time = true;
  269. m_time_ticks_per_second = HPET::the().frequency();
  270. m_system_timer->try_to_set_frequency(m_system_timer->calculate_nearest_possible_frequency(OPTIMAL_TICKS_PER_SECOND_RATE));
  271. // We don't need an interrupt for time keeping purposes because we
  272. // can query the timer.
  273. m_time_keeper_timer = m_system_timer;
  274. return true;
  275. }
  276. bool TimeManagement::probe_and_set_legacy_hardware_timers()
  277. {
  278. if (ACPI::is_enabled()) {
  279. if (ACPI::Parser::the()->x86_specific_flags().cmos_rtc_not_present) {
  280. dbg() << "ACPI: CMOS RTC Not Present";
  281. return false;
  282. } else {
  283. dbg() << "ACPI: CMOS RTC Present";
  284. }
  285. }
  286. m_hardware_timers.append(PIT::initialize(TimeManagement::update_time));
  287. m_hardware_timers.append(RealTimeClock::create(TimeManagement::system_timer_tick));
  288. m_time_keeper_timer = m_hardware_timers[0];
  289. m_system_timer = m_hardware_timers[1];
  290. // The timer is only as accurate as the interrupts...
  291. m_time_ticks_per_second = m_time_keeper_timer->ticks_per_second();
  292. return true;
  293. }
  294. void TimeManagement::update_time(const RegisterState&)
  295. {
  296. TimeManagement::the().increment_time_since_boot();
  297. }
  298. void TimeManagement::increment_time_since_boot_hpet()
  299. {
  300. ASSERT(!m_time_keeper_timer.is_null());
  301. ASSERT(m_time_keeper_timer->timer_type() == HardwareTimerType::HighPrecisionEventTimer);
  302. // NOTE: m_seconds_since_boot and m_ticks_this_second are only ever
  303. // updated here! So we can safely read that information, query the clock,
  304. // and when we're all done we can update the information. This reduces
  305. // contention when other processors attempt to read the clock.
  306. auto seconds_since_boot = m_seconds_since_boot;
  307. auto ticks_this_second = m_ticks_this_second;
  308. auto delta_ns = HPET::the().update_time(seconds_since_boot, ticks_this_second, false);
  309. // Now that we have a precise time, go update it as quickly as we can
  310. u32 update_iteration = m_update1.fetch_add(1, AK::MemoryOrder::memory_order_acquire);
  311. m_seconds_since_boot = seconds_since_boot;
  312. m_ticks_this_second = ticks_this_second;
  313. // TODO: Apply m_remaining_epoch_time_adjustment
  314. timespec_add(m_epoch_time, { (time_t)(delta_ns / 1000000000), (long)(delta_ns % 1000000000) }, m_epoch_time);
  315. m_update2.store(update_iteration + 1, AK::MemoryOrder::memory_order_release);
  316. }
  317. void TimeManagement::increment_time_since_boot()
  318. {
  319. ASSERT(!m_time_keeper_timer.is_null());
  320. // Compute time adjustment for adjtime. Let the clock run up to 1% fast or slow.
  321. // That way, adjtime can adjust up to 36 seconds per hour, without time getting very jumpy.
  322. // Once we have a smarter NTP service that also adjusts the frequency instead of just slewing time, maybe we can lower this.
  323. long NanosPerTick = 1'000'000'000 / m_time_keeper_timer->frequency();
  324. time_t MaxSlewNanos = NanosPerTick / 100;
  325. u32 update_iteration = m_update1.fetch_add(1, AK::MemoryOrder::memory_order_acquire);
  326. // Clamp twice, to make sure intermediate fits into a long.
  327. 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);
  328. timespec slew_nanos_ts;
  329. timespec_sub({ 0, slew_nanos }, { 0, 0 }, slew_nanos_ts); // Normalize tv_nsec to be positive.
  330. timespec_sub(m_remaining_epoch_time_adjustment, slew_nanos_ts, m_remaining_epoch_time_adjustment);
  331. timespec epoch_tick = { .tv_sec = 0, .tv_nsec = NanosPerTick };
  332. epoch_tick.tv_nsec += slew_nanos; // No need for timespec_add(), guaranteed to be in range.
  333. timespec_add(m_epoch_time, epoch_tick, m_epoch_time);
  334. if (++m_ticks_this_second >= m_time_keeper_timer->ticks_per_second()) {
  335. // FIXME: Synchronize with other clock somehow to prevent drifting apart.
  336. ++m_seconds_since_boot;
  337. m_ticks_this_second = 0;
  338. }
  339. m_update2.store(update_iteration + 1, AK::MemoryOrder::memory_order_release);
  340. }
  341. void TimeManagement::system_timer_tick(const RegisterState& regs)
  342. {
  343. if (Processor::current().in_irq() <= 1) {
  344. // Don't expire timers while handling IRQs
  345. TimerQueue::the().fire();
  346. }
  347. Scheduler::timer_tick(regs);
  348. }
  349. }