1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/AvailableMemoryTracker.h"
10 # include "mozilla/WindowsVersion.h"
11 # include "nsExceptionHandler.h"
12 # include "nsICrashReporter.h"
13 # include "nsIMemoryReporter.h"
14 # include "nsMemoryPressure.h"
17 #include "nsIObserver.h"
18 #include "nsIObserverService.h"
19 #include "nsIRunnable.h"
20 #include "nsISupports.h"
22 #include "nsThreadUtils.h"
23 #include "nsXULAppAPI.h"
25 #include "mozilla/ResultExtensions.h"
26 #include "mozilla/Services.h"
27 #include "mozilla/Unused.h"
29 #if defined(MOZ_MEMORY)
30 # include "mozmemory.h"
33 using namespace mozilla
;
39 # if (NTDDI_VERSION < NTDDI_WINBLUE) || \
40 (NTDDI_VERSION == NTDDI_WINBLUE && !defined(WINBLUE_KBSPRING14))
41 // Definitions for heap optimization that require the Windows SDK to target the
43 static const HEAP_INFORMATION_CLASS HeapOptimizeResources
=
44 static_cast<HEAP_INFORMATION_CLASS
>(3);
46 static const DWORD HEAP_OPTIMIZE_RESOURCES_CURRENT_VERSION
= 1;
48 typedef struct _HEAP_OPTIMIZE_RESOURCES_INFORMATION
{
51 } HEAP_OPTIMIZE_RESOURCES_INFORMATION
, *PHEAP_OPTIMIZE_RESOURCES_INFORMATION
;
54 Atomic
<uint32_t, MemoryOrdering::Relaxed
> sNumLowVirtualMemEvents
;
55 Atomic
<uint32_t, MemoryOrdering::Relaxed
> sNumLowCommitSpaceEvents
;
57 class nsAvailableMemoryWatcher final
: public nsIObserver
,
58 public nsITimerCallback
{
62 NS_DECL_NSITIMERCALLBACK
64 nsAvailableMemoryWatcher();
68 // Fire a low-memory notification if we have less than this many bytes of
69 // virtual address space available.
70 # if defined(HAVE_64BIT_BUILD)
71 static const size_t kLowVirtualMemoryThreshold
= 0;
73 static const size_t kLowVirtualMemoryThreshold
= 384 * 1024 * 1024;
76 // Fire a low-memory notification if we have less than this many bytes of
77 // commit space (physical memory plus page file) left.
78 static const size_t kLowCommitSpaceThreshold
= 384 * 1024 * 1024;
80 // Don't fire a low-memory notification more often than this interval.
81 static const uint32_t kLowMemoryNotificationIntervalMS
= 10000;
83 // Poll the amount of free memory at this rate.
84 static const uint32_t kPollingIntervalMS
= 1000;
86 // Observer topics we subscribe to, see below.
87 static const char* const kObserverTopics
[];
89 static bool IsVirtualMemoryLow(const MEMORYSTATUSEX
& aStat
);
90 static bool IsCommitSpaceLow(const MEMORYSTATUSEX
& aStat
);
92 ~nsAvailableMemoryWatcher(){};
93 bool OngoingMemoryPressure() { return mUnderMemoryPressure
; }
94 void AdjustPollingInterval(const bool aLowMemory
);
95 void SendMemoryPressureEvent();
96 void MaybeSendMemoryPressureStopEvent();
97 void MaybeSaveMemoryReport();
100 nsCOMPtr
<nsITimer
> mTimer
;
101 bool mUnderMemoryPressure
;
105 const char* const nsAvailableMemoryWatcher::kObserverTopics
[] = {
107 "user-interaction-active",
108 "user-interaction-inactive",
111 NS_IMPL_ISUPPORTS(nsAvailableMemoryWatcher
, nsIObserver
, nsITimerCallback
)
113 nsAvailableMemoryWatcher::nsAvailableMemoryWatcher()
114 : mTimer(nullptr), mUnderMemoryPressure(false), mSavedReport(false) {}
116 nsresult
nsAvailableMemoryWatcher::Init() {
117 mTimer
= NS_NewTimer();
119 nsCOMPtr
<nsIObserverService
> observerService
= services::GetObserverService();
120 MOZ_ASSERT(observerService
);
122 for (auto topic
: kObserverTopics
) {
123 nsresult rv
= observerService
->AddObserver(this, topic
,
124 /* ownsWeak */ false);
125 NS_ENSURE_SUCCESS(rv
, rv
);
128 MOZ_TRY(mTimer
->InitWithCallback(this, kPollingIntervalMS
,
129 nsITimer::TYPE_REPEATING_SLACK
));
133 void nsAvailableMemoryWatcher::Shutdown() {
134 nsCOMPtr
<nsIObserverService
> observerService
= services::GetObserverService();
135 MOZ_ASSERT(observerService
);
137 for (auto topic
: kObserverTopics
) {
138 Unused
<< observerService
->RemoveObserver(this, topic
);
148 bool nsAvailableMemoryWatcher::IsVirtualMemoryLow(const MEMORYSTATUSEX
& aStat
) {
149 if ((kLowVirtualMemoryThreshold
!= 0) &&
150 (aStat
.ullAvailVirtual
< kLowVirtualMemoryThreshold
)) {
151 sNumLowVirtualMemEvents
++;
159 bool nsAvailableMemoryWatcher::IsCommitSpaceLow(const MEMORYSTATUSEX
& aStat
) {
160 if ((kLowCommitSpaceThreshold
!= 0) &&
161 (aStat
.ullAvailPageFile
< kLowCommitSpaceThreshold
)) {
162 sNumLowCommitSpaceEvents
++;
163 CrashReporter::AnnotateCrashReport(
164 CrashReporter::Annotation::LowCommitSpaceEvents
,
165 uint32_t(sNumLowCommitSpaceEvents
));
172 void nsAvailableMemoryWatcher::SendMemoryPressureEvent() {
173 MemoryPressureState state
=
174 OngoingMemoryPressure() ? MemPressure_Ongoing
: MemPressure_New
;
175 NS_DispatchEventualMemoryPressure(state
);
178 void nsAvailableMemoryWatcher::MaybeSendMemoryPressureStopEvent() {
179 if (OngoingMemoryPressure()) {
180 NS_DispatchEventualMemoryPressure(MemPressure_Stopping
);
184 void nsAvailableMemoryWatcher::MaybeSaveMemoryReport() {
185 if (!mSavedReport
&& OngoingMemoryPressure()) {
186 nsCOMPtr
<nsICrashReporter
> cr
=
187 do_GetService("@mozilla.org/toolkit/crash-reporter;1");
189 if (NS_SUCCEEDED(cr
->SaveMemoryReport())) {
196 void nsAvailableMemoryWatcher::AdjustPollingInterval(const bool aLowMemory
) {
198 // We entered a low-memory state, wait for a longer interval before polling
199 // again as there's no point in rapidly sending further notifications.
200 mTimer
->SetDelay(kLowMemoryNotificationIntervalMS
);
201 } else if (OngoingMemoryPressure()) {
202 // We were under memory pressure but we're not anymore, resume polling at
204 mTimer
->SetDelay(kPollingIntervalMS
);
208 // Timer callback, polls memory stats to detect low-memory conditions. This
209 // will send memory-pressure events if memory is running low and adjust the
210 // polling interval accordingly.
212 nsAvailableMemoryWatcher::Notify(nsITimer
* aTimer
) {
214 stat
.dwLength
= sizeof(stat
);
215 bool success
= GlobalMemoryStatusEx(&stat
);
218 bool lowMemory
= IsVirtualMemoryLow(stat
) || IsCommitSpaceLow(stat
);
221 SendMemoryPressureEvent();
223 MaybeSendMemoryPressureStopEvent();
227 MaybeSaveMemoryReport();
229 mSavedReport
= false; // Save a new report if memory gets low again
232 AdjustPollingInterval(lowMemory
);
233 mUnderMemoryPressure
= lowMemory
;
239 // Observer service callback, used to stop the polling timer when the user
240 // stops interacting with Firefox and resuming it when they interact again.
241 // Also used to shut down the service if the application is quitting.
243 nsAvailableMemoryWatcher::Observe(nsISupports
* aSubject
, const char* aTopic
,
244 const char16_t
* aData
) {
245 if (strcmp(aTopic
, "quit-application") == 0) {
247 } else if (strcmp(aTopic
, "user-interaction-inactive") == 0) {
249 } else if (strcmp(aTopic
, "user-interaction-active") == 0) {
250 mTimer
->InitWithCallback(this, kPollingIntervalMS
,
251 nsITimer::TYPE_REPEATING_SLACK
);
253 MOZ_ASSERT_UNREACHABLE("Unknown topic");
259 static int64_t LowMemoryEventsVirtualDistinguishedAmount() {
260 return sNumLowVirtualMemEvents
;
263 static int64_t LowMemoryEventsCommitSpaceDistinguishedAmount() {
264 return sNumLowCommitSpaceEvents
;
267 class LowEventsReporter final
: public nsIMemoryReporter
{
268 ~LowEventsReporter() {}
273 NS_IMETHOD
CollectReports(nsIHandleReportCallback
* aHandleReport
,
274 nsISupports
* aData
, bool aAnonymize
) override
{
277 "low-memory-events/virtual", KIND_OTHER
, UNITS_COUNT_CUMULATIVE
,
278 LowMemoryEventsVirtualDistinguishedAmount(),
279 "Number of low-virtual-memory events fired since startup. We fire such an "
280 "event if we notice there is less than predefined amount of virtual address "
281 "space available (if zero, this behavior is disabled, see "
282 "xpcom/base/AvailableMemoryTracker.cpp). The process will probably crash if "
283 "it runs out of virtual address space, so this event is dire.");
286 "low-memory-events/commit-space", KIND_OTHER
, UNITS_COUNT_CUMULATIVE
,
287 LowMemoryEventsCommitSpaceDistinguishedAmount(),
288 "Number of low-commit-space events fired since startup. We fire such an "
289 "event if we notice there is less than a predefined amount of commit space "
290 "available (if zero, this behavior is disabled, see "
291 "xpcom/base/AvailableMemoryTracker.cpp). Windows will likely kill the process "
292 "if it runs out of commit space, so this event is dire.");
298 NS_IMPL_ISUPPORTS(LowEventsReporter
, nsIMemoryReporter
)
300 #endif // defined(XP_WIN)
303 * This runnable is executed in response to a memory-pressure event; we spin
304 * the event-loop when receiving the memory-pressure event in the hope that
305 * other observers will synchronously free some memory that we'll be able to
308 class nsJemallocFreeDirtyPagesRunnable final
: public Runnable
{
309 ~nsJemallocFreeDirtyPagesRunnable() = default;
312 void OptimizeSystemHeap();
318 nsJemallocFreeDirtyPagesRunnable()
319 : Runnable("nsJemallocFreeDirtyPagesRunnable") {}
323 nsJemallocFreeDirtyPagesRunnable::Run() {
324 MOZ_ASSERT(NS_IsMainThread());
326 #if defined(MOZ_MEMORY)
327 jemalloc_free_dirty_pages();
331 OptimizeSystemHeap();
338 void nsJemallocFreeDirtyPagesRunnable::OptimizeSystemHeap() {
339 // HeapSetInformation exists prior to Windows 8.1, but the
340 // HeapOptimizeResources information class does not.
341 if (IsWin8Point1OrLater()) {
342 HEAP_OPTIMIZE_RESOURCES_INFORMATION heapOptInfo
= {
343 HEAP_OPTIMIZE_RESOURCES_CURRENT_VERSION
};
345 ::HeapSetInformation(nullptr, HeapOptimizeResources
, &heapOptInfo
,
346 sizeof(heapOptInfo
));
349 #endif // defined(XP_WIN)
352 * The memory pressure watcher is used for listening to memory-pressure events
353 * and reacting upon them. We use one instance per process currently only for
354 * cleaning up dirty unused pages held by jemalloc.
356 class nsMemoryPressureWatcher final
: public nsIObserver
{
357 ~nsMemoryPressureWatcher() = default;
366 NS_IMPL_ISUPPORTS(nsMemoryPressureWatcher
, nsIObserver
)
369 * Initialize and subscribe to the memory-pressure events. We subscribe to the
370 * observer service in this method and not in the constructor because we need
371 * to hold a strong reference to 'this' before calling the observer service.
373 void nsMemoryPressureWatcher::Init() {
374 nsCOMPtr
<nsIObserverService
> os
= services::GetObserverService();
377 os
->AddObserver(this, "memory-pressure", /* ownsWeak */ false);
382 * Reacts to all types of memory-pressure events, launches a runnable to
383 * free dirty pages held by jemalloc.
386 nsMemoryPressureWatcher::Observe(nsISupports
* aSubject
, const char* aTopic
,
387 const char16_t
* aData
) {
388 MOZ_ASSERT(!strcmp(aTopic
, "memory-pressure"), "Unknown topic");
390 nsCOMPtr
<nsIRunnable
> runnable
= new nsJemallocFreeDirtyPagesRunnable();
392 NS_DispatchToMainThread(runnable
);
400 namespace AvailableMemoryTracker
{
403 // The watchers are held alive by the observer service.
404 RefPtr
<nsMemoryPressureWatcher
> watcher
= new nsMemoryPressureWatcher();
408 RegisterStrongMemoryReporter(new LowEventsReporter());
409 RegisterLowMemoryEventsVirtualDistinguishedAmount(
410 LowMemoryEventsVirtualDistinguishedAmount
);
411 RegisterLowMemoryEventsCommitSpaceDistinguishedAmount(
412 LowMemoryEventsCommitSpaceDistinguishedAmount
);
414 if (XRE_IsParentProcess()) {
415 RefPtr
<nsAvailableMemoryWatcher
> poller
= new nsAvailableMemoryWatcher();
417 if (NS_FAILED(poller
->Init())) {
418 NS_WARNING("Could not start the available memory watcher");
421 #endif // defined(XP_WIN)
424 } // namespace AvailableMemoryTracker
425 } // namespace mozilla