File: AvailableMemoryWatcherLinux.cpp

package info (click to toggle)
firefox 146.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,653,260 kB
  • sloc: cpp: 7,587,892; javascript: 6,509,455; ansic: 3,755,295; python: 1,410,813; xml: 629,201; asm: 438,677; java: 186,096; sh: 62,697; makefile: 18,086; objc: 13,087; perl: 12,811; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (430 lines) | stat: -rw-r--r-- 13,819 bytes parent folder | download
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "AvailableMemoryWatcher.h"
#include "AvailableMemoryWatcherUtils.h"
#include "mozilla/FileUtils.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_browser.h"
#include "nsAppRunner.h"
#include "nsIAvailableMemoryWatcherTestingLinux.h"
#include "nsIObserverService.h"
#include "nsISupports.h"
#include "nsITimer.h"
#include "nsIThread.h"
#include "nsMemoryPressure.h"
#include "nsString.h"
#include <cstring>
#include <cstdio>

namespace mozilla {

/* PSIInfo struct holds parsed data from /proc/pressure/memory
 *
 * The values in /proc/pressure/memory are floating point numbers, but
 * PSIInfo has integer members.
 */
struct PSIInfo {
  unsigned long some_avg10 = 0;
  unsigned long some_avg60 = 0;
  unsigned long some_avg300 = 0;
  unsigned long some_total = 0;
  unsigned long full_avg10 = 0;
  unsigned long full_avg60 = 0;
  unsigned long full_avg300 = 0;
  unsigned long full_total = 0;
};

// Read PSI (Pressure Stall Information) data from /proc/pressure/memory
static nsresult ReadPSIFile(const char* aPSIPath, PSIInfo& aResult) {
  ScopedCloseFile file(fopen(aPSIPath, "r"));
  if (NS_WARN_IF(!file)) {
    // PSI file not available (kernel doesn't support PSI)
    return NS_ERROR_FAILURE;
  }

  char buff[256];
  // Initialize all values to 0
  aResult = {};

  /* The PSI file format looks like this:
   * some avg10=0.00 avg60=0.00 avg300=0.00 total=0
   * full avg10=0.00 avg60=0.00 avg300=0.00 total=0
   */
  float avg10, avg60, avg300, total;
  while ((fgets(buff, sizeof(buff), file.get())) != nullptr) {
    // Skip empty lines (exactly one '\n' character)
    if (strcmp(buff, "\n") == 0) {
      continue;
    }

    if (strstr(buff, "some")) {
      if (sscanf(buff, "some avg10=%f avg60=%f avg300=%f total=%f", &avg10,
                 &avg60, &avg300, &total) != 4) {
        return NS_ERROR_FAILURE;
      }
      if (avg10 < 0 || avg60 < 0 || avg300 < 0 || total < 0) {
        return NS_ERROR_FAILURE;
      }
      aResult.some_avg10 = avg10;
      aResult.some_avg60 = avg60;
      aResult.some_avg300 = avg300;
      aResult.some_total = total;
    } else if (strstr(buff, "full")) {
      if (sscanf(buff, "full avg10=%f avg60=%f avg300=%f total=%f", &avg10,
                 &avg60, &avg300, &total) != 4) {
        return NS_ERROR_FAILURE;
      }
      if (avg10 < 0 || avg60 < 0 || avg300 < 0 || total < 0) {
        return NS_ERROR_FAILURE;
      }
      aResult.full_avg10 = avg10;
      aResult.full_avg60 = avg60;
      aResult.full_avg300 = avg300;
      aResult.full_total = total;
    } else {
      // Unrecognized non-empty line
      return NS_ERROR_FAILURE;
    }
  }

  // Check PSI percentage values are in reasonable range (0-100)
  if (aResult.some_avg10 > 100UL || aResult.some_avg60 > 100UL ||
      aResult.some_avg300 > 100UL) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

// Linux has no native low memory detection. This class creates a timer that
// polls for low memory and sends a low memory notification if it notices a
// memory pressure event.
class nsAvailableMemoryWatcher final
    : public nsITimerCallback,
      public nsINamed,
      public nsAvailableMemoryWatcherBase,
      public nsIAvailableMemoryWatcherTestingLinux {
 public:
  NS_DECL_ISUPPORTS_INHERITED
  NS_DECL_NSITIMERCALLBACK
  NS_DECL_NSIOBSERVER
  NS_DECL_NSINAMED
  NS_DECL_NSIAVAILABLEMEMORYWATCHERTESTINGLINUX

  nsresult Init() override;
  nsAvailableMemoryWatcher();

  void HandleLowMemory();
  void MaybeHandleHighMemory();

 private:
  ~nsAvailableMemoryWatcher();
  void StartPolling(const MutexAutoLock&);
  void StopPolling(const MutexAutoLock&);
  void ShutDown();
  void UpdateCrashAnnotation(const MutexAutoLock&);
  void UpdatePSIInfo(const MutexAutoLock&);
  static bool IsMemoryLow();

  nsCOMPtr<nsITimer> mTimer MOZ_GUARDED_BY(mMutex);
  nsCOMPtr<nsIThread> mThread MOZ_GUARDED_BY(mMutex);

  bool mPolling MOZ_GUARDED_BY(mMutex);
  bool mUnderMemoryPressure MOZ_GUARDED_BY(mMutex);
  PSIInfo mPSIInfo MOZ_GUARDED_BY(mMutex);

  // PSI file path - can be overridden for testing
  nsCString mPSIPath MOZ_GUARDED_BY(mMutex);

  // Flag to track if SetPSIPathForTesting has been called
  bool mIsTesting MOZ_GUARDED_BY(mMutex);

  // Polling interval to check for low memory. In high memory scenarios,
  // default to 5000 ms between each check.
  static const uint32_t kHighMemoryPollingIntervalMS = 5000;

  // Polling interval to check for low memory. Default to 1000 ms between each
  // check. Use this interval when memory is low,
  static const uint32_t kLowMemoryPollingIntervalMS = 1000;
};

// A modern version of linux should keep memory information in the
// /proc/meminfo path.
static const char* kMeminfoPath = "/proc/meminfo";

// Linux memory PSI (Pressure Stall Information) path
static const auto kPSIPath = "/proc/pressure/memory"_ns;

nsAvailableMemoryWatcher::nsAvailableMemoryWatcher()
    : mPolling(false),
      mUnderMemoryPressure(false),
      mPSIInfo{},
      mPSIPath(kPSIPath),
      mIsTesting(false) {}

nsAvailableMemoryWatcher::~nsAvailableMemoryWatcher() {}

nsresult nsAvailableMemoryWatcher::Init() {
  nsresult rv = nsAvailableMemoryWatcherBase::Init();
  if (NS_FAILED(rv)) {
    return rv;
  }
  MutexAutoLock lock(mMutex);
  mTimer = NS_NewTimer();
  nsCOMPtr<nsIThread> thread;
  // We have to make our own thread here instead of using the background pool,
  // because some low memory scenarios can cause the background pool to fill.
  rv = NS_NewNamedThread("MemoryPoller", getter_AddRefs(thread));
  if (NS_FAILED(rv)) {
    NS_WARNING("Couldn't make a thread for nsAvailableMemoryWatcher.");
    // In this scenario we can't poll for low memory, since we can't dispatch
    // to our memory watcher thread.
    return rv;
  }
  mThread = thread;

  // Set the crash annotation to its initial state.
  UpdatePSIInfo(lock);
  UpdateCrashAnnotation(lock);

  StartPolling(lock);

  return NS_OK;
}

already_AddRefed<nsAvailableMemoryWatcherBase> CreateAvailableMemoryWatcher() {
  RefPtr watcher(new nsAvailableMemoryWatcher);

  if (NS_FAILED(watcher->Init())) {
    return do_AddRef(new nsAvailableMemoryWatcherBase);
  }

  return watcher.forget();
}

NS_IMPL_ISUPPORTS_INHERITED(nsAvailableMemoryWatcher,
                            nsAvailableMemoryWatcherBase, nsITimerCallback,
                            nsIObserver, nsINamed,
                            nsIAvailableMemoryWatcherTestingLinux);

void nsAvailableMemoryWatcher::StopPolling(const MutexAutoLock&)
    MOZ_REQUIRES(mMutex) {
  if (mPolling && mTimer) {
    // stop dispatching memory checks to the thread.
    mTimer->Cancel();
    mPolling = false;
  }
}

// Check /proc/meminfo for low memory. Largely C method for reading
// /proc/meminfo.
/* static */
bool nsAvailableMemoryWatcher::IsMemoryLow() {
  MemoryInfo memInfo{0, 0};
  nsresult rv = ReadMemoryFile(kMeminfoPath, memInfo);

  if (NS_FAILED(rv) || (memInfo.memAvailable == 0) || (memInfo.memTotal == 0)) {
    // If memAvailable cannot be found, then we are using an older system.
    // We can't accurately poll on this.
    // If memTotal is zero we can't calculate how much memory we're using.
    return false;
  }

  unsigned long memoryAsPercentage =
      (memInfo.memAvailable * 100) / memInfo.memTotal;

  return memoryAsPercentage <=
             StaticPrefs::browser_low_commit_space_threshold_percent() ||
         memInfo.memAvailable <
             StaticPrefs::browser_low_commit_space_threshold_mb() * 1024;
}

void nsAvailableMemoryWatcher::ShutDown() {
  nsCOMPtr<nsIThread> thread;
  {
    MutexAutoLock lock(mMutex);
    if (mTimer) {
      mTimer->Cancel();
      mTimer = nullptr;
    }
    thread = mThread.forget();
  }
  // thread->Shutdown() spins a nested event loop while waiting for the thread
  // to end. But the thread might execute some previously dispatched event that
  // wants to lock our mutex, too, before arriving at the shutdown event.
  if (thread) {
    thread->Shutdown();
  }
}

// We will use this to poll for low memory.
NS_IMETHODIMP
nsAvailableMemoryWatcher::Notify(nsITimer* aTimer) {
  MutexAutoLock lock(mMutex);
  if (!mThread) {
    // If we've made it this far and there's no  |mThread|,
    // we might have failed to dispatch it for some reason.
    MOZ_ASSERT(mThread);
    return NS_ERROR_FAILURE;
  }
  bool isTesting = mIsTesting;
  nsresult rv = mThread->Dispatch(NS_NewRunnableFunction(
      "MemoryPoller", [self = RefPtr{this}, isTesting]() {
        if (self->IsMemoryLow()) {
          self->HandleLowMemory();
        } else {
          self->MaybeHandleHighMemory();
        }
        if (isTesting) {
          NS_DispatchToMainThread(
              NS_NewRunnableFunction("MemoryPollerSync", [self]() {
                nsCOMPtr<nsIObserverService> observerService =
                    mozilla::services::GetObserverService();
                if (observerService) {
                  observerService->NotifyObservers(
                      nullptr, "memory-poller-sync", nullptr);
                }
              }));
        }
      }));

  if NS_FAILED (rv) {
    NS_WARNING("Cannot dispatch memory polling event.");
  }
  return NS_OK;
}

void nsAvailableMemoryWatcher::HandleLowMemory() {
  MutexAutoLock lock(mMutex);
  if (!mTimer) {
    // We have been shut down from outside while in flight.
    return;
  }
  if (!mUnderMemoryPressure) {
    mUnderMemoryPressure = true;
    // Poll more frequently under memory pressure.
    StartPolling(lock);
  }
  UpdatePSIInfo(lock);
  UpdateCrashAnnotation(lock);
  UpdateLowMemoryTimeStamp();
  // We handle low memory offthread, but we want to unload
  // tabs only from the main thread, so we will dispatch this
  // back to the main thread.
  // Since we are doing this async, we don't need to unlock the mutex first;
  // the AutoLock will unlock the mutex when we finish the dispatch.
  NS_DispatchToMainThread(NS_NewRunnableFunction(
      "nsAvailableMemoryWatcher::OnLowMemory",
      [self = RefPtr{this}]() { self->mTabUnloader->UnloadTabAsync(); }));
}

void nsAvailableMemoryWatcher::UpdateCrashAnnotation(const MutexAutoLock&)
    MOZ_REQUIRES(mMutex) {
  CrashReporter::RecordAnnotationBool(
      CrashReporter::Annotation::LinuxUnderMemoryPressure,
      mUnderMemoryPressure);

  // Record PSI (Pressure Stall Information) data from stored values
  nsPrintfCString psiValues("%lu,%lu,%lu,%lu,%lu,%lu,%lu,%lu",
                            mPSIInfo.some_avg10, mPSIInfo.some_avg60,
                            mPSIInfo.some_avg300, mPSIInfo.some_total,
                            mPSIInfo.full_avg10, mPSIInfo.full_avg60,
                            mPSIInfo.full_avg300, mPSIInfo.full_total);

  CrashReporter::RecordAnnotationNSCString(
      CrashReporter::Annotation::LinuxMemoryPSI, psiValues);
}

void nsAvailableMemoryWatcher::UpdatePSIInfo(const MutexAutoLock&)
    MOZ_REQUIRES(mMutex) {
  nsresult rv = ReadPSIFile(mPSIPath.get(), mPSIInfo);
  if (NS_FAILED(rv)) {
    mPSIInfo = {};
  }
}

// If memory is not low, we may need to dispatch an
// event for it if we have been under memory pressure.
// We can also adjust our polling interval.
void nsAvailableMemoryWatcher::MaybeHandleHighMemory() {
  MutexAutoLock lock(mMutex);
  if (!mTimer) {
    // We have been shut down from outside while in flight.
    return;
  }
  if (mUnderMemoryPressure) {
    RecordTelemetryEventOnHighMemory(lock);
    NS_NotifyOfEventualMemoryPressure(MemoryPressureState::NoPressure);
    mUnderMemoryPressure = false;
  }
  UpdatePSIInfo(lock);
  UpdateCrashAnnotation(lock);
  StartPolling(lock);
}

// When we change the polling interval, we will need to restart the timer
// on the new interval.
void nsAvailableMemoryWatcher::StartPolling(const MutexAutoLock& aLock)
    MOZ_REQUIRES(mMutex) {
  // Determine the effective polling interval up-front.
  uint32_t pollingInterval = mUnderMemoryPressure
                                 ? kLowMemoryPollingIntervalMS
                                 : kHighMemoryPollingIntervalMS;
  // For tests, enforce a very small interval to speed up polling.
  if (gIsGtest || mIsTesting) {
    pollingInterval = 10;
  }

  if (!mPolling) {
    // Restart the timer with the new interval if it has stopped.
    if (NS_SUCCEEDED(mTimer->InitWithCallback(
            this, pollingInterval, nsITimer::TYPE_REPEATING_SLACK))) {
      mPolling = true;
    }
  } else {
    mTimer->SetDelay(pollingInterval);
  }
}

// Observe events for shutting down and starting/stopping the timer.
NS_IMETHODIMP
nsAvailableMemoryWatcher::Observe(nsISupports* aSubject, const char* aTopic,
                                  const char16_t* aData) {
  nsresult rv = nsAvailableMemoryWatcherBase::Observe(aSubject, aTopic, aData);
  if (NS_FAILED(rv)) {
    return rv;
  }

  if (strcmp(aTopic, "xpcom-shutdown") == 0) {
    ShutDown();
  } else {
    MutexAutoLock lock(mMutex);
    if (mTimer) {
      if (strcmp(aTopic, "user-interaction-active") == 0) {
        StartPolling(lock);
      } else if (strcmp(aTopic, "user-interaction-inactive") == 0) {
        StopPolling(lock);
      }
    }
  }

  return NS_OK;
}

NS_IMETHODIMP nsAvailableMemoryWatcher::GetName(nsACString& aName) {
  aName.AssignLiteral("nsAvailableMemoryWatcher");
  return NS_OK;
}

NS_IMETHODIMP nsAvailableMemoryWatcher::SetPSIPathForTesting(
    const nsACString& aPSIPath) {
  MutexAutoLock lock(mMutex);
  mPSIPath.Assign(aPSIPath);
  mIsTesting = true;
  return NS_OK;
}

}  // namespace mozilla