File: MemoryPressureHandler.h

package info (click to toggle)
webkit2gtk 2.48.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 429,620 kB
  • sloc: cpp: 3,696,936; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,276; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (287 lines) | stat: -rw-r--r-- 9,699 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
 * Copyright (C) 2011-2017 Apple Inc. All Rights Reserved.
 * Copyright (C) 2014 Raspberry Pi Foundation. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

#include <atomic>
#include <ctime>
#include <wtf/FastMalloc.h>
#include <wtf/Forward.h>
#include <wtf/Function.h>
#include <wtf/RunLoop.h>

#if OS(WINDOWS)
#include <wtf/win/Win32Handle.h>
#endif

#if PLATFORM(COCOA)
#include <wtf/OSObjectPtr.h>
#endif

namespace WTF {

enum class SystemMemoryPressureStatus : uint8_t {
    Normal,
    Warning,
    Critical,
};

enum class ProcessMemoryLimit : uint8_t {
    Warning,
    Critical,
};

enum class MemoryUsagePolicy : uint8_t {
    Unrestricted, // Allocate as much as you want
    Conservative, // Maybe you don't cache every single thing
    Strict, // Time to start pinching pennies for real
};

enum class WebsamProcessState : uint8_t {
    Active,
    Inactive,
};

enum class Critical : bool { No, Yes };
enum class Synchronous : bool { No, Yes };

typedef WTF::Function<void(Critical, Synchronous)> LowMemoryHandler;

struct MemoryPressureHandlerConfiguration {
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
    WTF_EXPORT_PRIVATE MemoryPressureHandlerConfiguration();
    WTF_EXPORT_PRIVATE MemoryPressureHandlerConfiguration(size_t, double, double, std::optional<double>, Seconds);

    size_t baseThreshold;
    double conservativeThresholdFraction;
    double strictThresholdFraction;
    std::optional<double> killThresholdFraction;
    Seconds pollInterval;
};

class MemoryPressureHandler {
    WTF_MAKE_FAST_ALLOCATED;
    friend class WTF::LazyNeverDestroyed<MemoryPressureHandler>;
public:
    WTF_EXPORT_PRIVATE static MemoryPressureHandler& singleton();

    // Do nothing since this is a singleton.
    void ref() const { }
    void deref() const { }

    WTF_EXPORT_PRIVATE void install();

    WTF_EXPORT_PRIVATE void setMemoryFootprintPollIntervalForTesting(Seconds);
    WTF_EXPORT_PRIVATE void setShouldUsePeriodicMemoryMonitor(bool);

#if OS(LINUX) || OS(FREEBSD) || OS(QNX)
    WTF_EXPORT_PRIVATE void triggerMemoryPressureEvent(bool isCritical);
#endif

    void setMemoryKillCallback(WTF::Function<void()>&& function) { m_memoryKillCallback = WTFMove(function); }
    void setMemoryPressureStatusChangedCallback(WTF::Function<void()>&& function) { m_memoryPressureStatusChangedCallback = WTFMove(function); }
    void setDidExceedProcessMemoryLimitCallback(WTF::Function<void(ProcessMemoryLimit)>&& function) { m_didExceedProcessMemoryLimitCallback = WTFMove(function); }

    void setLowMemoryHandler(LowMemoryHandler&& handler)
    {
        m_lowMemoryHandler = WTFMove(handler);
    }

    bool isUnderMemoryWarning() const
    {
        return m_memoryPressureStatus == SystemMemoryPressureStatus::Warning
#if PLATFORM(MAC)
            || m_memoryUsagePolicy == MemoryUsagePolicy::Conservative
#endif
            || m_isSimulatingMemoryWarning;
    }

    bool isUnderMemoryPressure() const
    {
        return m_memoryPressureStatus == SystemMemoryPressureStatus::Critical
#if PLATFORM(MAC)
            || m_memoryUsagePolicy >= MemoryUsagePolicy::Strict
#endif
            || m_isSimulatingMemoryPressure;
    }

    bool isSimulatingMemoryWarning() const { return m_isSimulatingMemoryWarning; }
    bool isSimulatingMemoryPressure() const { return m_isSimulatingMemoryPressure; }

    void setMemoryPressureStatus(SystemMemoryPressureStatus);
    SystemMemoryPressureStatus memoryPressureStatus() const { return m_memoryPressureStatus; }

    WTF_EXPORT_PRIVATE MemoryUsagePolicy currentMemoryUsagePolicy();

#if PLATFORM(COCOA)
    void setDispatchQueue(OSObjectPtr<dispatch_queue_t>&& queue)
    {
        RELEASE_ASSERT(!m_installed);
        m_dispatchQueue = WTFMove(queue);
    }
#endif

    class ReliefLogger {
        WTF_MAKE_FAST_ALLOCATED;
    public:
        explicit ReliefLogger(const char *log)
            : m_logString(log)
            , m_initialMemory(loggingEnabled() ? platformMemoryUsage() : MemoryUsage { })
        {
        }

        ~ReliefLogger()
        {
            if (loggingEnabled())
                logMemoryUsageChange();
        }


        const char* logString() const { return m_logString; }
        static void setLoggingEnabled(bool enabled) { s_loggingEnabled = enabled; }
        static bool loggingEnabled()
        {
#if RELEASE_LOG_DISABLED
            return s_loggingEnabled;
#else
            return true;
#endif
        }

    private:
        struct MemoryUsage {
            WTF_MAKE_STRUCT_FAST_ALLOCATED;
            MemoryUsage() = default;
            MemoryUsage(size_t resident, size_t physical)
                : resident(resident)
                , physical(physical)
            {
            }
            size_t resident { 0 };
            size_t physical { 0 };
        };
        std::optional<MemoryUsage> platformMemoryUsage();
        void logMemoryUsageChange();

        const char* m_logString;
        std::optional<MemoryUsage> m_initialMemory;

        WTF_EXPORT_PRIVATE static bool s_loggingEnabled;
    };

    using Configuration = MemoryPressureHandlerConfiguration;

    void setConfiguration(Configuration&& configuration) { m_configuration = WTFMove(configuration); }
    void setConfiguration(const Configuration& configuration) { m_configuration = configuration; }

    WTF_EXPORT_PRIVATE void releaseMemory(Critical, Synchronous = Synchronous::No);

    WTF_EXPORT_PRIVATE void beginSimulatedMemoryWarning();
    WTF_EXPORT_PRIVATE void endSimulatedMemoryWarning();
    WTF_EXPORT_PRIVATE void beginSimulatedMemoryPressure();
    WTF_EXPORT_PRIVATE void endSimulatedMemoryPressure();

    WTF_EXPORT_PRIVATE void setProcessState(WebsamProcessState);
    WebsamProcessState processState() const { return m_processState; }

    WTF_EXPORT_PRIVATE static ASCIILiteral processStateDescription();

    WTF_EXPORT_PRIVATE static void setPageCount(unsigned);

    void setShouldLogMemoryMemoryPressureEvents(bool shouldLog) { m_shouldLogMemoryMemoryPressureEvents = shouldLog; }

    // Runs the provided callback the first time that this process's footprint exceeds any of the given thresholds.
    // Only works in processes that use PeriodicMemoryMonitor.
    WTF_EXPORT_PRIVATE void setMemoryFootprintNotificationThresholds(Vector<size_t>&& thresholds, WTF::Function<void(size_t)>&&);

private:
    std::optional<size_t> thresholdForMemoryKill();
    size_t thresholdForPolicy(MemoryUsagePolicy);
    MemoryUsagePolicy policyForFootprint(size_t);

    void memoryPressureStatusChanged();

    void uninstall();

    void holdOff(Seconds);

    MemoryPressureHandler();
    ~MemoryPressureHandler() = delete;

    void didExceedProcessMemoryLimit(ProcessMemoryLimit);
    void respondToMemoryPressure(Critical, Synchronous = Synchronous::No);
    void platformReleaseMemory(Critical);
    void platformInitialize();

    void measurementTimerFired();
    void shrinkOrDie(size_t killThreshold);
    void setMemoryUsagePolicyBasedOnFootprint(size_t);

    unsigned m_pageCount { 0 };

    std::atomic<SystemMemoryPressureStatus> m_memoryPressureStatus { SystemMemoryPressureStatus::Normal };
    bool m_installed { false };
    bool m_isSimulatingMemoryWarning { false };
    bool m_isSimulatingMemoryPressure { false };
    bool m_shouldLogMemoryMemoryPressureEvents { true };

    WebsamProcessState m_processState { WebsamProcessState::Inactive };
    
    MemoryUsagePolicy m_memoryUsagePolicy { MemoryUsagePolicy::Unrestricted };

    std::unique_ptr<RunLoop::Timer>m_measurementTimer;
    WTF::Function<void()> m_memoryKillCallback;
    WTF::Function<void()> m_memoryPressureStatusChangedCallback;
    WTF::Function<void(ProcessMemoryLimit)> m_didExceedProcessMemoryLimitCallback;
    LowMemoryHandler m_lowMemoryHandler;
    Vector<size_t> m_memoryFootprintNotificationThresholds;
    WTF::Function<void(size_t)> m_memoryFootprintNotificationHandler;

    Configuration m_configuration;

#if OS(WINDOWS)
    void windowsMeasurementTimerFired();
    RunLoop::Timer m_windowsMeasurementTimer;
    Win32Handle m_lowMemoryHandle;
#endif

#if OS(LINUX) || OS(FREEBSD) || OS(HAIKU) || OS(QNX)
    RunLoop::Timer m_holdOffTimer;
    void holdOffTimerFired();
#endif

#if PLATFORM(COCOA)
    OSObjectPtr<dispatch_queue_t> m_dispatchQueue;
#endif
};

} // namespace WTF

using WTF::Critical;
using WTF::MemoryPressureHandler;
using WTF::Synchronous;
using WTF::SystemMemoryPressureStatus;
using WTF::WebsamProcessState;