1/*
2 * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
3 * Copyright (C) 2009 Google Inc. 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
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (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
27#include "config.h"
28#include "ThreadTimers.h"
29
30#include "MainThreadSharedTimer.h"
31#include "SharedTimer.h"
32#include "ThreadGlobalData.h"
33#include "Timer.h"
34#include <wtf/MainThread.h>
35
36#if PLATFORM(IOS_FAMILY)
37#include "WebCoreThread.h"
38#endif
39
40namespace WebCore {
41
42// Fire timers for this length of time, and then quit to let the run loop process user input events.
43// 100ms is about a perceptable delay in UI, so use a half of that as a threshold.
44// This is to prevent UI freeze when there are too many timers or machine performance is low.
45static const Seconds maxDurationOfFiringTimers { 50_ms };
46
47// Timers are created, started and fired on the same thread, and each thread has its own ThreadTimers
48// copy to keep the heap and a set of currently firing timers.
49
50ThreadTimers::ThreadTimers()
51{
52 if (isUIThread())
53 setSharedTimer(&MainThreadSharedTimer::singleton());
54}
55
56// A worker thread may initialize SharedTimer after some timers are created.
57// Also, SharedTimer can be replaced with nullptr before all timers are destroyed.
58void ThreadTimers::setSharedTimer(SharedTimer* sharedTimer)
59{
60 if (m_sharedTimer) {
61 m_sharedTimer->setFiredFunction(nullptr);
62 m_sharedTimer->stop();
63 m_pendingSharedTimerFireTime = MonotonicTime { };
64 }
65
66 m_sharedTimer = sharedTimer;
67
68 if (sharedTimer) {
69 m_sharedTimer->setFiredFunction([] { threadGlobalData().threadTimers().sharedTimerFiredInternal(); });
70 updateSharedTimer();
71 }
72}
73
74void ThreadTimers::updateSharedTimer()
75{
76 if (!m_sharedTimer)
77 return;
78
79 while (!m_timerHeap.isEmpty() && !m_timerHeap.first()->hasTimer()) {
80 ASSERT_NOT_REACHED();
81 TimerBase::heapDeleteNullMin(m_timerHeap);
82 }
83 ASSERT(m_timerHeap.isEmpty() || m_timerHeap.first()->hasTimer());
84
85 if (m_firingTimers || m_timerHeap.isEmpty()) {
86 m_pendingSharedTimerFireTime = MonotonicTime { };
87 m_sharedTimer->stop();
88 } else {
89 MonotonicTime nextFireTime = m_timerHeap.first()->time;
90 MonotonicTime currentMonotonicTime = MonotonicTime::now();
91 if (m_pendingSharedTimerFireTime) {
92 // No need to restart the timer if both the pending fire time and the new fire time are in the past.
93 if (m_pendingSharedTimerFireTime <= currentMonotonicTime && nextFireTime <= currentMonotonicTime)
94 return;
95 }
96 m_pendingSharedTimerFireTime = nextFireTime;
97 m_sharedTimer->setFireInterval(std::max(nextFireTime - currentMonotonicTime, 0_s));
98 }
99}
100
101void ThreadTimers::sharedTimerFiredInternal()
102{
103 ASSERT(isMainThread() || (!isWebThread() && !isUIThread()));
104 // Do a re-entrancy check.
105 if (m_firingTimers)
106 return;
107 m_firingTimers = true;
108 m_pendingSharedTimerFireTime = MonotonicTime { };
109
110 MonotonicTime fireTime = MonotonicTime::now();
111 MonotonicTime timeToQuit = fireTime + maxDurationOfFiringTimers;
112
113 while (!m_timerHeap.isEmpty()) {
114 Ref<ThreadTimerHeapItem> item = *m_timerHeap.first();
115 ASSERT(item->hasTimer());
116 if (!item->hasTimer()) {
117 TimerBase::heapDeleteNullMin(m_timerHeap);
118 continue;
119 }
120
121 if (item->time > fireTime)
122 break;
123
124 auto& timer = item->timer();
125 Seconds interval = timer.repeatInterval();
126 timer.setNextFireTime(interval ? fireTime + interval : MonotonicTime { });
127
128 // Once the timer has been fired, it may be deleted, so do nothing else with it after this point.
129 item->timer().fired();
130
131 // Catch the case where the timer asked timers to fire in a nested event loop, or we are over time limit.
132 if (!m_firingTimers || timeToQuit < MonotonicTime::now())
133 break;
134 }
135
136 m_firingTimers = false;
137
138 updateSharedTimer();
139}
140
141void ThreadTimers::fireTimersInNestedEventLoop()
142{
143 // Reset the reentrancy guard so the timers can fire again.
144 m_firingTimers = false;
145
146 if (m_sharedTimer) {
147 m_sharedTimer->invalidate();
148 m_pendingSharedTimerFireTime = MonotonicTime { };
149 }
150
151 updateSharedTimer();
152}
153
154} // namespace WebCore
155
156