TimerQueue.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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<u8> g_timerqueue_lock;
  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, const Time& 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. TimerId TimerQueue::add_timer(clockid_t clock_id, const Time& deadline, Function<void()>&& callback)
  103. {
  104. auto expires = TimeManagement::the().current_time(clock_id);
  105. expires = expires + deadline;
  106. auto timer = new Timer();
  107. VERIFY(timer);
  108. timer->setup(clock_id, expires, move(callback));
  109. return add_timer(adopt_ref(*timer));
  110. }
  111. bool TimerQueue::cancel_timer(TimerId id)
  112. {
  113. Timer* found_timer = nullptr;
  114. Queue* timer_queue = nullptr;
  115. SpinlockLocker lock(g_timerqueue_lock);
  116. for (auto& timer : m_timer_queue_monotonic.list) {
  117. if (timer.m_id == id) {
  118. found_timer = &timer;
  119. timer_queue = &m_timer_queue_monotonic;
  120. break;
  121. }
  122. }
  123. if (found_timer == nullptr) {
  124. for (auto& timer : m_timer_queue_realtime.list) {
  125. if (timer.m_id == id) {
  126. found_timer = &timer;
  127. timer_queue = &m_timer_queue_realtime;
  128. break;
  129. }
  130. };
  131. }
  132. if (found_timer) {
  133. VERIFY(timer_queue);
  134. remove_timer_locked(*timer_queue, *found_timer);
  135. return true;
  136. }
  137. // The timer may be executing right now, if it is then it should
  138. // be in m_timers_executing. This is the case when the deferred
  139. // call has been queued but not yet executed.
  140. for (auto& timer : m_timers_executing) {
  141. if (timer.m_id == id) {
  142. found_timer = &timer;
  143. break;
  144. }
  145. }
  146. if (!found_timer)
  147. return false;
  148. // Keep a reference while we unlock
  149. NonnullRefPtr<Timer> executing_timer(*found_timer);
  150. lock.unlock();
  151. if (!found_timer->set_cancelled()) {
  152. // We cancelled it even though the deferred call has been queued already.
  153. // We do not unref the timer here because the deferred call is still going
  154. // too need it!
  155. lock.lock();
  156. VERIFY(m_timers_executing.contains(*found_timer));
  157. m_timers_executing.remove(*found_timer);
  158. return true;
  159. }
  160. // At this point the deferred call is queued and is being executed
  161. // on another processor. We need to wait until it's complete!
  162. while (!found_timer->is_callback_finished())
  163. Processor::wait_check();
  164. return true;
  165. }
  166. bool TimerQueue::cancel_timer(Timer& timer, bool* was_in_use)
  167. {
  168. bool in_use = timer.is_in_use();
  169. if (was_in_use)
  170. *was_in_use = in_use;
  171. // If the timer isn't in use, the cancellation is a no-op.
  172. if (!in_use) {
  173. VERIFY(!timer.m_list_node.is_in_list());
  174. return false;
  175. }
  176. bool did_already_run = timer.set_cancelled();
  177. auto& timer_queue = queue_for_timer(timer);
  178. if (!did_already_run) {
  179. timer.clear_in_use();
  180. SpinlockLocker lock(g_timerqueue_lock);
  181. if (timer_queue.list.contains(timer)) {
  182. // The timer has not fired, remove it
  183. VERIFY(timer.ref_count() > 1);
  184. remove_timer_locked(timer_queue, timer);
  185. return true;
  186. }
  187. // The timer was queued to execute but hasn't had a chance
  188. // to run. In this case, it should still be in m_timers_executing
  189. // and we don't need to spin. It still holds a reference
  190. // that will be dropped when it does get a chance to run,
  191. // but since we called set_cancelled it will only drop its reference
  192. VERIFY(m_timers_executing.contains(timer));
  193. m_timers_executing.remove(timer);
  194. return true;
  195. }
  196. // At this point the deferred call is queued and is being executed
  197. // on another processor. We need to wait until it's complete!
  198. while (!timer.is_callback_finished())
  199. Processor::wait_check();
  200. return false;
  201. }
  202. void TimerQueue::remove_timer_locked(Queue& queue, Timer& timer)
  203. {
  204. bool was_next_timer = (queue.list.first() == &timer);
  205. queue.list.remove(timer);
  206. auto now = timer.now(false);
  207. if (timer.m_expires > now)
  208. timer.m_remaining = timer.m_expires - now;
  209. if (was_next_timer)
  210. update_next_timer_due(queue);
  211. // Whenever we remove a timer that was still queued (but hasn't been
  212. // fired) we added a reference to it. So, when removing it from the
  213. // queue we need to drop that reference.
  214. timer.unref();
  215. }
  216. void TimerQueue::fire()
  217. {
  218. SpinlockLocker lock(g_timerqueue_lock);
  219. auto fire_timers = [&](Queue& queue) {
  220. auto* timer = queue.list.first();
  221. VERIFY(timer);
  222. VERIFY(queue.next_timer_due == timer->m_expires);
  223. while (timer && timer->now(true) > timer->m_expires) {
  224. queue.list.remove(*timer);
  225. m_timers_executing.append(*timer);
  226. update_next_timer_due(queue);
  227. lock.unlock();
  228. // Defer executing the timer outside of the irq handler
  229. Processor::deferred_call_queue([this, timer]() {
  230. // Check if we were cancelled in between being triggered
  231. // by the timer irq handler and now. If so, just drop
  232. // our reference and don't execute the callback.
  233. if (!timer->set_cancelled()) {
  234. timer->m_callback();
  235. SpinlockLocker lock(g_timerqueue_lock);
  236. m_timers_executing.remove(*timer);
  237. }
  238. timer->clear_in_use();
  239. timer->set_callback_finished();
  240. // Drop the reference we added when queueing the timer
  241. timer->unref();
  242. });
  243. lock.lock();
  244. timer = queue.list.first();
  245. }
  246. };
  247. if (!m_timer_queue_monotonic.list.is_empty())
  248. fire_timers(m_timer_queue_monotonic);
  249. if (!m_timer_queue_realtime.list.is_empty())
  250. fire_timers(m_timer_queue_realtime);
  251. }
  252. void TimerQueue::update_next_timer_due(Queue& queue)
  253. {
  254. VERIFY(g_timerqueue_lock.is_locked());
  255. if (auto* next_timer = queue.list.first())
  256. queue.next_timer_due = next_timer->m_expires;
  257. else
  258. queue.next_timer_due = {};
  259. }
  260. }