TimerQueue.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Singleton.h>
  7. #include <AK/Time.h>
  8. #include <Kernel/Scheduler.h>
  9. #include <Kernel/Sections.h>
  10. #include <Kernel/Time/TimeManagement.h>
  11. #include <Kernel/TimerQueue.h>
  12. namespace Kernel {
  13. static Singleton<TimerQueue> s_the;
  14. static Spinlock g_timerqueue_lock { LockRank::None };
  15. Time Timer::remaining() const
  16. {
  17. return m_remaining;
  18. }
  19. Time Timer::now(bool is_firing) const
  20. {
  21. // NOTE: If is_firing is true then TimePrecision::Precise isn't really useful here.
  22. // We already have a quite precise time stamp because we just updated the time in the
  23. // interrupt handler. In those cases, just use coarse timestamps.
  24. auto clock_id = m_clock_id;
  25. if (is_firing) {
  26. switch (clock_id) {
  27. case CLOCK_MONOTONIC:
  28. clock_id = CLOCK_MONOTONIC_COARSE;
  29. break;
  30. case CLOCK_MONOTONIC_RAW:
  31. // TODO: use a special CLOCK_MONOTONIC_RAW_COARSE like mechanism here
  32. break;
  33. case CLOCK_REALTIME:
  34. clock_id = CLOCK_REALTIME_COARSE;
  35. break;
  36. default:
  37. break;
  38. }
  39. }
  40. return TimeManagement::the().current_time(clock_id);
  41. }
  42. TimerQueue& TimerQueue::the()
  43. {
  44. return *s_the;
  45. }
  46. UNMAP_AFTER_INIT TimerQueue::TimerQueue()
  47. {
  48. m_ticks_per_second = TimeManagement::the().ticks_per_second();
  49. }
  50. bool TimerQueue::add_timer_without_id(NonnullRefPtr<Timer> timer, clockid_t clock_id, Time const& deadline, Function<void()>&& callback)
  51. {
  52. if (deadline <= TimeManagement::the().current_time(clock_id))
  53. return false;
  54. // Because timer handlers can execute on any processor and there is
  55. // a race between executing a timer handler and cancel_timer() this
  56. // *must* be a RefPtr<Timer>. Otherwise, calling cancel_timer() could
  57. // inadvertently cancel another timer that has been created between
  58. // returning from the timer handler and a call to cancel_timer().
  59. timer->setup(clock_id, deadline, move(callback));
  60. SpinlockLocker lock(g_timerqueue_lock);
  61. timer->m_id = 0; // Don't generate a timer id
  62. add_timer_locked(move(timer));
  63. return true;
  64. }
  65. TimerId TimerQueue::add_timer(NonnullRefPtr<Timer>&& timer)
  66. {
  67. SpinlockLocker lock(g_timerqueue_lock);
  68. timer->m_id = ++m_timer_id_count;
  69. VERIFY(timer->m_id != 0); // wrapped
  70. auto id = timer->m_id;
  71. add_timer_locked(move(timer));
  72. return id;
  73. }
  74. void TimerQueue::add_timer_locked(NonnullRefPtr<Timer> timer)
  75. {
  76. Time timer_expiration = timer->m_expires;
  77. timer->clear_cancelled();
  78. timer->clear_callback_finished();
  79. timer->set_in_use();
  80. auto& queue = queue_for_timer(*timer);
  81. if (queue.list.is_empty()) {
  82. queue.list.append(timer.leak_ref());
  83. queue.next_timer_due = timer_expiration;
  84. } else {
  85. Timer* following_timer = nullptr;
  86. for (auto& t : queue.list) {
  87. if (t.m_expires > timer_expiration) {
  88. following_timer = &t;
  89. break;
  90. }
  91. }
  92. if (following_timer) {
  93. bool next_timer_needs_update = queue.list.first() == following_timer;
  94. queue.list.insert_before(*following_timer, timer.leak_ref());
  95. if (next_timer_needs_update)
  96. queue.next_timer_due = timer_expiration;
  97. } else {
  98. queue.list.append(timer.leak_ref());
  99. }
  100. }
  101. }
  102. bool TimerQueue::cancel_timer(Timer& timer, bool* was_in_use)
  103. {
  104. bool in_use = timer.is_in_use();
  105. if (was_in_use)
  106. *was_in_use = in_use;
  107. // If the timer isn't in use, the cancellation is a no-op.
  108. if (!in_use) {
  109. VERIFY(!timer.m_list_node.is_in_list());
  110. return false;
  111. }
  112. bool did_already_run = timer.set_cancelled();
  113. auto& timer_queue = queue_for_timer(timer);
  114. if (!did_already_run) {
  115. timer.clear_in_use();
  116. SpinlockLocker lock(g_timerqueue_lock);
  117. if (timer_queue.list.contains(timer)) {
  118. // The timer has not fired, remove it
  119. VERIFY(timer.ref_count() > 1);
  120. remove_timer_locked(timer_queue, timer);
  121. return true;
  122. }
  123. // The timer was queued to execute but hasn't had a chance
  124. // to run. In this case, it should still be in m_timers_executing
  125. // and we don't need to spin. It still holds a reference
  126. // that will be dropped when it does get a chance to run,
  127. // but since we called set_cancelled it will only drop its reference
  128. VERIFY(m_timers_executing.contains(timer));
  129. m_timers_executing.remove(timer);
  130. return true;
  131. }
  132. // At this point the deferred call is queued and is being executed
  133. // on another processor. We need to wait until it's complete!
  134. while (!timer.is_callback_finished())
  135. Processor::wait_check();
  136. return false;
  137. }
  138. void TimerQueue::remove_timer_locked(Queue& queue, Timer& timer)
  139. {
  140. bool was_next_timer = (queue.list.first() == &timer);
  141. queue.list.remove(timer);
  142. auto now = timer.now(false);
  143. if (timer.m_expires > now)
  144. timer.m_remaining = timer.m_expires - now;
  145. if (was_next_timer)
  146. update_next_timer_due(queue);
  147. // Whenever we remove a timer that was still queued (but hasn't been
  148. // fired) we added a reference to it. So, when removing it from the
  149. // queue we need to drop that reference.
  150. timer.unref();
  151. }
  152. void TimerQueue::fire()
  153. {
  154. SpinlockLocker lock(g_timerqueue_lock);
  155. auto fire_timers = [&](Queue& queue) {
  156. auto* timer = queue.list.first();
  157. VERIFY(timer);
  158. VERIFY(queue.next_timer_due == timer->m_expires);
  159. while (timer && timer->now(true) > timer->m_expires) {
  160. queue.list.remove(*timer);
  161. m_timers_executing.append(*timer);
  162. update_next_timer_due(queue);
  163. lock.unlock();
  164. // Defer executing the timer outside of the irq handler
  165. Processor::deferred_call_queue([this, timer]() {
  166. // Check if we were cancelled in between being triggered
  167. // by the timer irq handler and now. If so, just drop
  168. // our reference and don't execute the callback.
  169. if (!timer->set_cancelled()) {
  170. timer->m_callback();
  171. SpinlockLocker lock(g_timerqueue_lock);
  172. m_timers_executing.remove(*timer);
  173. }
  174. timer->clear_in_use();
  175. timer->set_callback_finished();
  176. // Drop the reference we added when queueing the timer
  177. timer->unref();
  178. });
  179. lock.lock();
  180. timer = queue.list.first();
  181. }
  182. };
  183. if (!m_timer_queue_monotonic.list.is_empty())
  184. fire_timers(m_timer_queue_monotonic);
  185. if (!m_timer_queue_realtime.list.is_empty())
  186. fire_timers(m_timer_queue_realtime);
  187. }
  188. void TimerQueue::update_next_timer_due(Queue& queue)
  189. {
  190. VERIFY(g_timerqueue_lock.is_locked());
  191. if (auto* next_timer = queue.list.first())
  192. queue.next_timer_due = next_timer->m_expires;
  193. else
  194. queue.next_timer_due = {};
  195. }
  196. }