1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef COMPONENTS_SCHEDULER_RENDERER_RENDERER_SCHEDULER_IMPL_H_
6 #define COMPONENTS_SCHEDULER_RENDERER_RENDERER_SCHEDULER_IMPL_H_
8 #include "base/atomicops.h"
9 #include "base/synchronization/lock.h"
10 #include "components/scheduler/child/idle_helper.h"
11 #include "components/scheduler/child/pollable_thread_safe_flag.h"
12 #include "components/scheduler/child/scheduler_helper.h"
13 #include "components/scheduler/renderer/deadline_task_runner.h"
14 #include "components/scheduler/renderer/renderer_scheduler.h"
15 #include "components/scheduler/scheduler_export.h"
18 namespace trace_event
{
19 class ConvertableToTraceFormat
;
25 class SCHEDULER_EXPORT RendererSchedulerImpl
: public RendererScheduler
,
26 public IdleHelper::Delegate
{
28 RendererSchedulerImpl(
29 scoped_refptr
<NestableSingleThreadTaskRunner
> main_task_runner
);
30 ~RendererSchedulerImpl() override
;
32 // RendererScheduler implementation:
33 scoped_refptr
<base::SingleThreadTaskRunner
> DefaultTaskRunner() override
;
34 scoped_refptr
<SingleThreadIdleTaskRunner
> IdleTaskRunner() override
;
35 scoped_refptr
<base::SingleThreadTaskRunner
> CompositorTaskRunner() override
;
36 scoped_refptr
<base::SingleThreadTaskRunner
> LoadingTaskRunner() override
;
37 scoped_refptr
<base::SingleThreadTaskRunner
> TimerTaskRunner() override
;
38 void WillBeginFrame(const cc::BeginFrameArgs
& args
) override
;
39 void BeginFrameNotExpectedSoon() override
;
40 void DidCommitFrameToCompositor() override
;
41 void DidHandleInputEventOnCompositorThread(
42 const blink::WebInputEvent
& web_input_event
,
43 InputEventState event_state
) override
;
44 void DidHandleInputEventOnMainThread(
45 const blink::WebInputEvent
& web_input_event
) override
;
46 void DidAnimateForInputOnCompositorThread() override
;
47 void OnRendererHidden() override
;
48 void OnRendererVisible() override
;
49 void OnPageLoadStarted() override
;
50 bool IsHighPriorityWorkAnticipated() override
;
51 bool ShouldYieldForHighPriorityWork() override
;
52 bool CanExceedIdleDeadlineIfRequired() const override
;
53 void AddTaskObserver(base::MessageLoop::TaskObserver
* task_observer
) override
;
54 void RemoveTaskObserver(
55 base::MessageLoop::TaskObserver
* task_observer
) override
;
56 void Shutdown() override
;
57 void SuspendTimerQueue() override
;
58 void ResumeTimerQueue() override
;
60 SchedulerHelper
* GetSchedulerHelperForTesting();
61 base::TimeTicks
CurrentIdleTaskDeadlineForTesting() const;
64 friend class RendererSchedulerImplTest
;
65 friend class RendererSchedulerImplForTest
;
67 // Keep RendererSchedulerImpl::TaskQueueIdToString in sync with this enum.
69 IDLE_TASK_QUEUE
= SchedulerHelper::TASK_QUEUE_COUNT
,
70 COMPOSITOR_TASK_QUEUE
,
73 // Must be the last entry.
75 FIRST_QUEUE_ID
= SchedulerHelper::FIRST_QUEUE_ID
,
78 // Keep RendererSchedulerImpl::PolicyToString in sync with this enum.
82 COMPOSITOR_CRITICAL_PATH_PRIORITY
,
85 // Must be the last entry.
87 FIRST_POLICY
= NORMAL
,
90 class PollableNeedsUpdateFlag
{
92 PollableNeedsUpdateFlag(base::Lock
* write_lock
);
93 ~PollableNeedsUpdateFlag();
95 // Set the flag. May only be called if |write_lock| is held.
96 void SetWhileLocked(bool value
);
98 // Returns true iff the flag is set to true.
102 base::subtle::Atomic32 flag_
;
103 base::Lock
* write_lock_
; // Not owned.
105 DISALLOW_COPY_AND_ASSIGN(PollableNeedsUpdateFlag
);
108 // IdleHelper::Delegate implementation:
109 bool CanEnterLongIdlePeriod(
111 base::TimeDelta
* next_long_idle_period_delay_out
) override
;
112 void IsNotQuiescent() override
{}
113 void OnIdlePeriodStarted() override
;
114 void OnIdlePeriodEnded() override
;
116 void EndIdlePeriod();
118 // Returns the serialized scheduler state for tracing.
119 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
> AsValue(
120 base::TimeTicks optional_now
) const;
121 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
> AsValueLocked(
122 base::TimeTicks optional_now
) const;
123 static const char* TaskQueueIdToString(QueueId queue_id
);
124 static const char* PolicyToString(Policy policy
);
126 static bool ShouldPrioritizeInputEvent(
127 const blink::WebInputEvent
& web_input_event
);
129 // The time we should stay in a priority-escalated mode after an input event.
130 static const int kPriorityEscalationAfterInputMillis
= 100;
132 // The amount of time which idle periods can continue being scheduled when the
133 // renderer has been hidden, before going to sleep for good.
134 static const int kEndIdleWhenHiddenDelayMillis
= 10000;
136 // The amount of time for which loading tasks will be prioritized over
137 // other tasks during the initial page load.
138 static const int kRailsInitialLoadingPrioritizationMillis
= 1000;
140 // For the purposes of deciding whether or not it's safe to turn timers and
141 // loading tasks on only in idle periods, we regard the system as being as
142 // being "idle period" starved if there hasn't been an idle period in the last
143 // 10 seconds. This was chosen to be long enough to cover most anticipated
145 static const int kIdlePeriodStarvationThresholdMillis
= 10000;
147 // Schedules an immediate PolicyUpdate, if there isn't one already pending and
148 // sets |policy_may_need_update_|. Note |any_thread_lock_| must be
150 void EnsureUrgentPolicyUpdatePostedOnMainThread(
151 const tracked_objects::Location
& from_here
);
153 // Update the policy if a new signal has arrived. Must be called from the main
155 void MaybeUpdatePolicy();
157 // Locks |any_thread_lock_| and updates the scheduler policy. May early
158 // out if the policy is unchanged. Must be called from the main thread.
161 // Like UpdatePolicy, except it doesn't early out.
162 void ForceUpdatePolicy();
164 enum class UpdateType
{
165 MAY_EARLY_OUT_IF_POLICY_UNCHANGED
,
169 // The implelemtation of UpdatePolicy & ForceUpdatePolicy. It is allowed to
170 // early out if |update_type| is MAY_EARLY_OUT_IF_POLICY_UNCHANGED.
171 virtual void UpdatePolicyLocked(UpdateType update_type
);
173 // Returns the amount of time left in the current input escalated priority
174 // policy. Can be called from any thread.
175 base::TimeDelta
TimeLeftInInputEscalatedPolicy(base::TimeTicks now
) const;
177 // Helper for computing the new policy. |new_policy_duration| will be filled
178 // with the amount of time after which the policy should be updated again. If
179 // the duration is zero, a new policy update will not be scheduled. Must be
180 // called with |any_thread_lock_| held. Can be called from any thread.
181 Policy
ComputeNewPolicy(base::TimeTicks now
,
182 base::TimeDelta
* new_policy_duration
) const;
184 // Works out if compositor tasks would be prioritized based on the current
185 // input signals. Can be called from any thread.
186 bool InputSignalsSuggestCompositorPriority(base::TimeTicks now
) const;
188 // An input event of some sort happened, the policy may need updating.
189 void UpdateForInputEventOnCompositorThread(blink::WebInputEvent::Type type
,
190 InputEventState input_event_state
);
192 // Returns true if there has been at least one idle period in the last
193 // |kIdlePeriodStarvationThresholdMillis|.
194 bool HadAnIdlePeriodRecently(base::TimeTicks now
) const;
196 SchedulerHelper helper_
;
197 IdleHelper idle_helper_
;
199 const scoped_refptr
<base::SingleThreadTaskRunner
> control_task_runner_
;
200 const scoped_refptr
<base::SingleThreadTaskRunner
> compositor_task_runner_
;
201 const scoped_refptr
<base::SingleThreadTaskRunner
> loading_task_runner_
;
202 const scoped_refptr
<base::SingleThreadTaskRunner
> timer_task_runner_
;
204 base::Closure update_policy_closure_
;
205 DeadlineTaskRunner delayed_update_policy_runner_
;
206 CancelableClosureHolder end_renderer_hidden_idle_period_closure_
;
208 // We have decided to improve thread safety at the cost of some boilerplate
209 // (the accessors) for the following data members.
211 struct MainThreadOnly
{
214 Policy current_policy_
;
215 base::TimeTicks current_policy_expiration_time_
;
216 base::TimeTicks estimated_next_frame_begin_
;
217 int timer_queue_suspend_count_
; // TIMER_TASK_QUEUE suspended if non-zero.
218 bool renderer_hidden_
;
225 base::TimeTicks last_input_signal_time_
;
226 base::TimeTicks last_idle_period_end_time_
;
227 base::TimeTicks rails_loading_priority_deadline_
;
228 int pending_main_thread_input_event_count_
;
229 bool awaiting_touch_start_response_
;
230 bool in_idle_period_
;
231 bool begin_main_frame_on_critical_path_
;
234 struct CompositorThreadOnly
{
235 CompositorThreadOnly();
236 ~CompositorThreadOnly();
238 blink::WebInputEvent::Type last_input_type_
;
239 scoped_ptr
<base::ThreadChecker
> compositor_thread_checker_
;
241 void CheckOnValidThread() {
243 // We don't actually care which thread this called from, just so long as
245 if (!compositor_thread_checker_
)
246 compositor_thread_checker_
.reset(new base::ThreadChecker());
247 DCHECK(compositor_thread_checker_
->CalledOnValidThread());
252 // Don't access main_thread_only_, instead use MainThreadOnly().
253 MainThreadOnly main_thread_only_
;
254 MainThreadOnly
& MainThreadOnly() {
255 helper_
.CheckOnValidThread();
256 return main_thread_only_
;
258 const struct MainThreadOnly
& MainThreadOnly() const {
259 helper_
.CheckOnValidThread();
260 return main_thread_only_
;
263 mutable base::Lock any_thread_lock_
;
264 // Don't access any_thread_, instead use AnyThread().
265 AnyThread any_thread_
;
266 AnyThread
& AnyThread() {
267 any_thread_lock_
.AssertAcquired();
270 const struct AnyThread
& AnyThread() const {
271 any_thread_lock_
.AssertAcquired();
275 // Don't access compositor_thread_only_, instead use CompositorThreadOnly().
276 CompositorThreadOnly compositor_thread_only_
;
277 CompositorThreadOnly
& CompositorThreadOnly() {
278 compositor_thread_only_
.CheckOnValidThread();
279 return compositor_thread_only_
;
282 PollableThreadSafeFlag policy_may_need_update_
;
283 base::WeakPtrFactory
<RendererSchedulerImpl
> weak_factory_
;
285 DISALLOW_COPY_AND_ASSIGN(RendererSchedulerImpl
);
288 } // namespace scheduler
290 #endif // COMPONENTS_SCHEDULER_RENDERER_RENDERER_SCHEDULER_IMPL_H_