2 * Copyright (C) 2011-2015 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. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #import "MemoryPressureHandler.h"
29 #import "DispatchSPI.h"
30 #import "IOSurfacePool.h"
31 #import "GCController.h"
32 #import "JSDOMWindow.h"
33 #import "JSDOMWindowBase.h"
36 #import "WebCoreSystemInterface.h"
38 #import <mach/task_info.h>
39 #import <malloc/malloc.h>
41 #import <wtf/CurrentTime.h>
44 #import "SystemMemory.h"
45 #import "WebCoreThread.h"
48 extern "C" void cache_simulate_memory_warning_event(uint64_t);
49 extern "C" void _sqlite3_purgeEligiblePagerCacheMemory(void);
53 void MemoryPressureHandler::platformReleaseMemory(Critical critical)
56 ReliefLogger log("Purging SQLite caches");
57 _sqlite3_purgeEligiblePagerCacheMemory();
61 ReliefLogger log("Drain LayerPools");
62 for (auto& pool : LayerPool::allLayerPools())
67 ReliefLogger log("Drain IOSurfacePool");
68 IOSurfacePool::sharedPool().discardAllSurfaces();
72 #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
73 if (critical == Critical::Yes && !isUnderMemoryPressure()) {
74 // libcache listens to OS memory notifications, but for process suspension
75 // or memory pressure simulation, we need to prod it manually:
76 ReliefLogger log("Purging libcache caches");
77 cache_simulate_memory_warning_event(DISPATCH_MEMORYPRESSURE_CRITICAL);
80 UNUSED_PARAM(critical);
84 static dispatch_source_t _cache_event_source = 0;
85 static dispatch_source_t _timer_event_source = 0;
86 static int _notifyToken;
88 // Disable memory event reception for a minimum of s_minimumHoldOffTime
89 // seconds after receiving an event. Don't let events fire any sooner than
90 // s_holdOffMultiplier times the last cleanup processing time. Effectively
91 // this is 1 / s_holdOffMultiplier percent of the time.
92 // These value seems reasonable and testing verifies that it throttles frequent
93 // low memory events, greatly reducing CPU usage.
94 static const unsigned s_minimumHoldOffTime = 5;
96 static const unsigned s_holdOffMultiplier = 20;
99 void MemoryPressureHandler::install()
101 if (m_installed || _timer_event_source)
104 dispatch_async(dispatch_get_main_queue(), ^{
105 #if PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000
106 _cache_event_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYSTATUS, 0, DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL | DISPATCH_MEMORYSTATUS_PRESSURE_WARN | DISPATCH_MEMORYSTATUS_PRESSURE_CRITICAL, dispatch_get_main_queue());
108 _cache_event_source = wkCreateMemoryStatusPressureCriticalDispatchOnMainQueue();
110 _cache_event_source = wkCreateVMPressureDispatchOnMainQueue();
112 if (_cache_event_source) {
113 dispatch_set_context(_cache_event_source, this);
114 dispatch_source_set_event_handler(_cache_event_source, ^{
115 bool critical = true;
116 #if PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000
117 unsigned long status = dispatch_source_get_data(_cache_event_source);
118 critical = status == DISPATCH_MEMORYPRESSURE_CRITICAL;
119 auto& memoryPressureHandler = MemoryPressureHandler::singleton();
120 bool wasCritical = memoryPressureHandler.isUnderMemoryPressure();
121 memoryPressureHandler.setUnderMemoryPressure(critical);
122 if (status == DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL) {
123 if (ReliefLogger::loggingEnabled())
124 NSLog(@"System is no longer under (%s) memory pressure.", wasCritical ? "critical" : "non-critical");
128 if (ReliefLogger::loggingEnabled())
129 NSLog(@"Got memory pressure notification (%s)", critical ? "critical" : "non-critical");
131 MemoryPressureHandler::singleton().respondToMemoryPressure(critical ? Critical::Yes : Critical::No);
133 dispatch_resume(_cache_event_source);
137 // Allow simulation of memory pressure with "notifyutil -p org.WebKit.lowMemory"
138 notify_register_dispatch("org.WebKit.lowMemory", &_notifyToken, dispatch_get_main_queue(), ^(int) {
139 MemoryPressureHandler::singleton().respondToMemoryPressure(Critical::Yes, Synchronous::Yes);
141 WTF::releaseFastMallocFreeMemory();
143 malloc_zone_pressure_relief(nullptr, 0);
149 void MemoryPressureHandler::uninstall()
154 dispatch_async(dispatch_get_main_queue(), ^{
155 if (_cache_event_source) {
156 dispatch_source_cancel(_cache_event_source);
157 dispatch_release(_cache_event_source);
158 _cache_event_source = 0;
161 if (_timer_event_source) {
162 dispatch_source_cancel(_timer_event_source);
163 dispatch_release(_timer_event_source);
164 _timer_event_source = 0;
170 notify_cancel(_notifyToken);
173 void MemoryPressureHandler::holdOff(unsigned seconds)
175 dispatch_async(dispatch_get_main_queue(), ^{
176 _timer_event_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
177 if (_timer_event_source) {
178 dispatch_set_context(_timer_event_source, this);
179 dispatch_source_set_timer(_timer_event_source, dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC), DISPATCH_TIME_FOREVER, 1 * s_minimumHoldOffTime);
180 dispatch_source_set_event_handler(_timer_event_source, ^{
181 if (_timer_event_source) {
182 dispatch_source_cancel(_timer_event_source);
183 dispatch_release(_timer_event_source);
184 _timer_event_source = 0;
186 MemoryPressureHandler::singleton().install();
188 dispatch_resume(_timer_event_source);
193 void MemoryPressureHandler::respondToMemoryPressure(Critical critical, Synchronous synchronous)
197 double startTime = monotonicallyIncreasingTime();
200 m_lowMemoryHandler(critical, synchronous);
203 unsigned holdOffTime = (monotonicallyIncreasingTime() - startTime) * s_holdOffMultiplier;
204 holdOff(std::max(holdOffTime, s_minimumHoldOffTime));
208 size_t MemoryPressureHandler::ReliefLogger::platformMemoryUsage()
210 // Flush free memory back to the OS before every measurement.
211 // Note that this code only runs when detailed pressure relief logging is enabled.
212 WTF::releaseFastMallocFreeMemory();
213 malloc_zone_pressure_relief(nullptr, 0);
215 task_vm_info_data_t vmInfo;
216 mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
217 kern_return_t err = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &vmInfo, &count);
218 if (err != KERN_SUCCESS)
219 return static_cast<size_t>(-1);
221 return static_cast<size_t>(vmInfo.internal);
224 void MemoryPressureHandler::ReliefLogger::platformLog()
226 size_t currentMemory = platformMemoryUsage();
227 if (currentMemory == static_cast<size_t>(-1) || m_initialMemory == static_cast<size_t>(-1)) {
228 NSLog(@"%s (Unable to get dirty memory information for process)\n", m_logString);
232 ssize_t memoryDiff = currentMemory - m_initialMemory;
234 NSLog(@"Pressure relief: %s: -dirty %ld bytes (from %ld to %ld)\n", m_logString, (memoryDiff * -1), m_initialMemory, currentMemory);
235 else if (memoryDiff > 0)
236 NSLog(@"Pressure relief: %s: +dirty %ld bytes (from %ld to %ld)\n", m_logString, memoryDiff, m_initialMemory, currentMemory);
238 NSLog(@"Pressure relief: %s: =dirty (at %ld bytes)\n", m_logString, currentMemory);
242 static void respondToMemoryPressureCallback(CFRunLoopObserverRef observer, CFRunLoopActivity /*activity*/, void* /*info*/)
244 MemoryPressureHandler::singleton().respondToMemoryPressureIfNeeded();
245 CFRunLoopObserverInvalidate(observer);
249 void MemoryPressureHandler::installMemoryReleaseBlock(void (^releaseMemoryBlock)(), bool clearPressureOnMemoryRelease)
253 m_releaseMemoryBlock = Block_copy(releaseMemoryBlock);
254 m_clearPressureOnMemoryRelease = clearPressureOnMemoryRelease;
258 void MemoryPressureHandler::setReceivedMemoryPressure(MemoryPressureReason reason)
260 m_underMemoryPressure = true;
263 MutexLocker locker(m_observerMutex);
265 m_observer = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting | kCFRunLoopExit, NO /* don't repeat */,
266 0, WebCore::respondToMemoryPressureCallback, NULL);
267 CFRunLoopAddObserver(WebThreadRunLoop(), m_observer, kCFRunLoopCommonModes);
268 CFRunLoopWakeUp(WebThreadRunLoop());
270 m_memoryPressureReason |= reason;
274 void MemoryPressureHandler::clearMemoryPressure()
276 m_underMemoryPressure = false;
279 MutexLocker locker(m_observerMutex);
280 m_memoryPressureReason = MemoryPressureReasonNone;
284 bool MemoryPressureHandler::shouldWaitForMemoryClearMessage()
286 MutexLocker locker(m_observerMutex);
287 return m_memoryPressureReason & MemoryPressureReasonVMStatus;
290 void MemoryPressureHandler::respondToMemoryPressureIfNeeded()
292 ASSERT(WebThreadIsLockedOrDisabled());
295 MutexLocker locker(m_observerMutex);
299 if (isUnderMemoryPressure()) {
300 ASSERT(m_releaseMemoryBlock);
301 LOG(MemoryPressure, "Handle memory pressure at %s", __PRETTY_FUNCTION__);
302 m_releaseMemoryBlock();
303 if (m_clearPressureOnMemoryRelease)
304 clearMemoryPressure();
310 } // namespace WebCore