2 * Copyright (C) 2017 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #include "PerformanceMonitor.h"
30 #include "ChromeClient.h"
31 #include "DiagnosticLoggingClient.h"
32 #include "DiagnosticLoggingKeys.h"
34 #include "MainFrame.h"
36 #include "PerformanceLogging.h"
37 #include "PublicSuffix.h"
42 #define RELEASE_LOG_IF_ALLOWED(channel, fmt, ...) RELEASE_LOG_IF(m_page.isAlwaysOnLoggingAllowed(), channel, "%p - PerformanceMonitor::" fmt, this, ##__VA_ARGS__)
44 static const Seconds cpuUsageMeasurementDelay { 5_s };
45 static const Seconds postLoadCPUUsageMeasurementDuration { 10_s };
46 static const Seconds backgroundCPUUsageMeasurementDuration { 5_min };
47 static const Seconds cpuUsageSamplingInterval { 10_min };
49 static const Seconds memoryUsageMeasurementDelay { 10_s };
51 static const Seconds delayBeforeProcessMayBecomeInactive { 8_min };
53 static const double postPageLoadCPUUsageDomainReportingThreshold { 20.0 }; // Reporting pages using over 20% CPU is roughly equivalent to reporting the 10% worst pages.
55 static const uint64_t postPageLoadMemoryUsageDomainReportingThreshold { 2048 * MB };
58 static inline ActivityStateForCPUSampling activityStateForCPUSampling(ActivityState::Flags state)
60 if (!(state & ActivityState::IsVisible))
61 return ActivityStateForCPUSampling::NonVisible;
62 if (state & ActivityState::WindowIsActive)
63 return ActivityStateForCPUSampling::VisibleAndActive;
64 return ActivityStateForCPUSampling::VisibleNonActive;
67 PerformanceMonitor::PerformanceMonitor(Page& page)
69 , m_postPageLoadCPUUsageTimer(*this, &PerformanceMonitor::measurePostLoadCPUUsage)
70 , m_postBackgroundingCPUUsageTimer(*this, &PerformanceMonitor::measurePostBackgroundingCPUUsage)
71 , m_perActivityStateCPUUsageTimer(*this, &PerformanceMonitor::measurePerActivityStateCPUUsage)
72 , m_postPageLoadMemoryUsageTimer(*this, &PerformanceMonitor::measurePostLoadMemoryUsage)
73 , m_postBackgroundingMemoryUsageTimer(*this, &PerformanceMonitor::measurePostBackgroundingMemoryUsage)
74 , m_processMayBecomeInactiveTimer(*this, &PerformanceMonitor::processMayBecomeInactiveTimerFired)
76 ASSERT(!page.isUtilityPage());
78 if (Settings::isPerActivityStateCPUUsageMeasurementEnabled()) {
79 m_perActivityStateCPUTime = getCPUTime();
80 m_perActivityStateCPUUsageTimer.startRepeating(cpuUsageSamplingInterval);
84 void PerformanceMonitor::didStartProvisionalLoad()
86 m_postLoadCPUTime = std::nullopt;
87 m_postPageLoadCPUUsageTimer.stop();
88 m_postPageLoadMemoryUsageTimer.stop();
91 void PerformanceMonitor::didFinishLoad()
93 // Only do post-load CPU usage measurement if there is a single Page in the process in order to reduce noise.
94 if (Settings::isPostLoadCPUUsageMeasurementEnabled() && m_page.isOnlyNonUtilityPage()) {
95 m_postLoadCPUTime = std::nullopt;
96 m_postPageLoadCPUUsageTimer.startOneShot(cpuUsageMeasurementDelay);
99 // Likewise for post-load memory usage measurement.
100 if (Settings::isPostLoadMemoryUsageMeasurementEnabled() && m_page.isOnlyNonUtilityPage())
101 m_postPageLoadMemoryUsageTimer.startOneShot(memoryUsageMeasurementDelay);
104 void PerformanceMonitor::activityStateChanged(ActivityState::Flags oldState, ActivityState::Flags newState)
106 ActivityState::Flags changed = oldState ^ newState;
107 bool visibilityChanged = changed & ActivityState::IsVisible;
109 // Measure CPU usage of pages when they are no longer visible.
110 if (Settings::isPostBackgroundingCPUUsageMeasurementEnabled() && visibilityChanged) {
111 m_postBackgroundingCPUTime = std::nullopt;
112 if (newState & ActivityState::IsVisible)
113 m_postBackgroundingCPUUsageTimer.stop();
114 else if (m_page.isOnlyNonUtilityPage())
115 m_postBackgroundingCPUUsageTimer.startOneShot(cpuUsageMeasurementDelay);
118 if (Settings::isPerActivityStateCPUUsageMeasurementEnabled()) {
119 // If visibility changed then report CPU usage right away because CPU usage is connected to visibility state.
120 auto oldActivityStateForCPUSampling = activityStateForCPUSampling(oldState);
121 if (oldActivityStateForCPUSampling != activityStateForCPUSampling(newState)) {
122 measureCPUUsageInActivityState(oldActivityStateForCPUSampling);
123 m_perActivityStateCPUUsageTimer.startRepeating(cpuUsageSamplingInterval);
127 if (Settings::isPostBackgroundingMemoryUsageMeasurementEnabled() && visibilityChanged) {
128 if (newState & ActivityState::IsVisible)
129 m_postBackgroundingMemoryUsageTimer.stop();
130 else if (m_page.isOnlyNonUtilityPage())
131 m_postBackgroundingMemoryUsageTimer.startOneShot(memoryUsageMeasurementDelay);
134 if (newState & ActivityState::IsVisible && newState & ActivityState::WindowIsActive) {
135 m_processMayBecomeInactive = false;
136 m_processMayBecomeInactiveTimer.stop();
137 } else if (!m_processMayBecomeInactive && !m_processMayBecomeInactiveTimer.isActive())
138 m_processMayBecomeInactiveTimer.startOneShot(delayBeforeProcessMayBecomeInactive);
140 updateProcessStateForMemoryPressure();
143 enum class ReportingReason { HighCPUUsage, HighMemoryUsage };
144 static void reportPageOverPostLoadResourceThreshold(Page& page, ReportingReason reason)
146 #if ENABLE(PUBLIC_SUFFIX_LIST)
147 auto* document = page.mainFrame().document();
151 String domain = topPrivatelyControlledDomain(document->url().host());
152 if (domain.isEmpty())
156 case ReportingReason::HighCPUUsage:
157 page.diagnosticLoggingClient().logDiagnosticMessageWithEnhancedPrivacy(DiagnosticLoggingKeys::domainCausingEnergyDrainKey(), domain, ShouldSample::No);
159 case ReportingReason::HighMemoryUsage:
160 page.diagnosticLoggingClient().logDiagnosticMessageWithEnhancedPrivacy(DiagnosticLoggingKeys::domainCausingJetsamKey(), domain, ShouldSample::No);
165 UNUSED_PARAM(reason);
169 void PerformanceMonitor::measurePostLoadCPUUsage()
171 if (!m_page.isOnlyNonUtilityPage()) {
172 m_postLoadCPUTime = std::nullopt;
176 if (!m_postLoadCPUTime) {
177 m_postLoadCPUTime = getCPUTime();
178 if (m_postLoadCPUTime)
179 m_postPageLoadCPUUsageTimer.startOneShot(postLoadCPUUsageMeasurementDuration);
182 std::optional<CPUTime> cpuTime = getCPUTime();
186 double cpuUsage = cpuTime.value().percentageCPUUsageSince(*m_postLoadCPUTime);
187 RELEASE_LOG_IF_ALLOWED(PerformanceLogging, "measurePostLoadCPUUsage: Process was using %.1f%% CPU after the page load.", cpuUsage);
188 m_page.diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::postPageLoadCPUUsageKey(), DiagnosticLoggingKeys::foregroundCPUUsageToDiagnosticLoggingKey(cpuUsage), ShouldSample::No);
190 if (cpuUsage > postPageLoadCPUUsageDomainReportingThreshold)
191 reportPageOverPostLoadResourceThreshold(m_page, ReportingReason::HighCPUUsage);
194 void PerformanceMonitor::measurePostLoadMemoryUsage()
196 if (!m_page.isOnlyNonUtilityPage())
199 std::optional<uint64_t> memoryUsage = PerformanceLogging::physicalFootprint();
203 RELEASE_LOG_IF_ALLOWED(PerformanceLogging, "measurePostLoadMemoryUsage: Process was using %llu bytes of memory after the page load.", memoryUsage.value());
204 m_page.diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::postPageLoadMemoryUsageKey(), DiagnosticLoggingKeys::memoryUsageToDiagnosticLoggingKey(memoryUsage.value()), ShouldSample::No);
206 // On iOS, we report actual Jetsams instead.
208 if (memoryUsage.value() > postPageLoadMemoryUsageDomainReportingThreshold)
209 reportPageOverPostLoadResourceThreshold(m_page, ReportingReason::HighMemoryUsage);
213 void PerformanceMonitor::measurePostBackgroundingMemoryUsage()
215 if (!m_page.isOnlyNonUtilityPage())
218 std::optional<uint64_t> memoryUsage = PerformanceLogging::physicalFootprint();
222 RELEASE_LOG_IF_ALLOWED(PerformanceLogging, "measurePostBackgroundingMemoryUsage: Process was using %llu bytes of memory after becoming non visible.", memoryUsage.value());
223 m_page.diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::postPageBackgroundingMemoryUsageKey(), DiagnosticLoggingKeys::memoryUsageToDiagnosticLoggingKey(memoryUsage.value()), ShouldSample::No);
226 void PerformanceMonitor::measurePostBackgroundingCPUUsage()
228 if (!m_page.isOnlyNonUtilityPage()) {
229 m_postBackgroundingCPUTime = std::nullopt;
233 if (!m_postBackgroundingCPUTime) {
234 m_postBackgroundingCPUTime = getCPUTime();
235 if (m_postBackgroundingCPUTime)
236 m_postBackgroundingCPUUsageTimer.startOneShot(backgroundCPUUsageMeasurementDuration);
239 std::optional<CPUTime> cpuTime = getCPUTime();
243 double cpuUsage = cpuTime.value().percentageCPUUsageSince(*m_postBackgroundingCPUTime);
244 RELEASE_LOG_IF_ALLOWED(PerformanceLogging, "measurePostBackgroundingCPUUsage: Process was using %.1f%% CPU after becoming non visible.", cpuUsage);
245 m_page.diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::postPageBackgroundingCPUUsageKey(), DiagnosticLoggingKeys::backgroundCPUUsageToDiagnosticLoggingKey(cpuUsage), ShouldSample::No);
248 void PerformanceMonitor::measurePerActivityStateCPUUsage()
250 measureCPUUsageInActivityState(activityStateForCPUSampling(m_page.activityState()));
253 #if !RELEASE_LOG_DISABLED
255 static inline const char* stringForCPUSamplingActivityState(ActivityStateForCPUSampling activityState)
257 switch (activityState) {
258 case ActivityStateForCPUSampling::NonVisible:
260 case ActivityStateForCPUSampling::VisibleNonActive:
261 return "VisibleNonActive";
262 case ActivityStateForCPUSampling::VisibleAndActive:
263 return "VisibleAndActive";
269 void PerformanceMonitor::measureCPUUsageInActivityState(ActivityStateForCPUSampling activityState)
271 if (!m_page.isOnlyNonUtilityPage()) {
272 m_perActivityStateCPUTime = std::nullopt;
276 if (!m_perActivityStateCPUTime) {
277 m_perActivityStateCPUTime = getCPUTime();
281 std::optional<CPUTime> cpuTime = getCPUTime();
283 m_perActivityStateCPUTime = std::nullopt;
287 #if !RELEASE_LOG_DISABLED
288 double cpuUsage = cpuTime.value().percentageCPUUsageSince(*m_perActivityStateCPUTime);
289 RELEASE_LOG_IF_ALLOWED(PerformanceLogging, "measureCPUUsageInActivityState: Process is using %.1f%% CPU in state: %s", cpuUsage, stringForCPUSamplingActivityState(activityState));
291 m_page.chrome().client().reportProcessCPUTime((cpuTime.value().systemTime + cpuTime.value().userTime) - (m_perActivityStateCPUTime.value().systemTime + m_perActivityStateCPUTime.value().userTime), activityState);
293 m_perActivityStateCPUTime = WTFMove(cpuTime);
296 void PerformanceMonitor::processMayBecomeInactiveTimerFired()
298 m_processMayBecomeInactive = true;
299 updateProcessStateForMemoryPressure();
302 void PerformanceMonitor::updateProcessStateForMemoryPressure()
304 bool hasAudiblePages = false;
305 bool hasCapturingPages = false;
306 bool mayBecomeInactive = true;
308 Page::forEachPage([&] (Page& page) {
309 if (!page.performanceMonitor())
311 if (!page.performanceMonitor()->m_processMayBecomeInactive)
312 mayBecomeInactive = false;
313 if (page.activityState() & ActivityState::IsAudible)
314 hasAudiblePages = true;
315 if (page.activityState() & ActivityState::IsCapturingMedia)
316 hasCapturingPages = true;
319 bool isActiveProcess = !mayBecomeInactive || hasAudiblePages || hasCapturingPages;
320 MemoryPressureHandler::singleton().setProcessState(isActiveProcess ? WebsamProcessState::Active : WebsamProcessState::Inactive);
323 } // namespace WebCore