Backed out 2 changesets (bug 1881078, bug 1879806) for causing dt failures @ devtools...
[gecko.git] / hal / linux / LinuxProcessPriority.cpp
bloba0f72a4f388205a7248b47045c5365c6a4005135
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "Hal.h"
6 #include "HalLog.h"
8 #include "mozilla/Sprintf.h"
9 #include "mozilla/Unused.h"
11 #include <fcntl.h>
12 #include <unistd.h>
14 using namespace mozilla::hal;
16 namespace mozilla::hal_impl {
18 /* The Linux OOM score is a value computed by the kernel ranging between 0 and
19 * 1000 and indicating how likely is a process to be killed when memory is
20 * tight. The larger the value the more likely a process is to be killed. The
21 * score is computed based on the amount of memory used plus an adjustment
22 * value. We chose our adjustment values to make it likely that processes are
23 * killed in the following order:
25 * 1. preallocated processes
26 * 2. background processes
27 * 3. background processes playing video (but no audio)
28 * 4. foreground processes or processes playing or recording audio
29 * 5. the parent process
31 * At the time of writing (2022) the base score for a process consuming very
32 * little memory seems to be around ~667. Our adjustments are thus designed
33 * to ensure this order starting from a 667 baseline but trying not to go too
34 * close to the 1000 limit where they would be clamped. */
36 const uint32_t kParentOomScoreAdjust = 0;
37 const uint32_t kForegroundOomScoreAdjust = 100;
38 const uint32_t kBackgroundPerceivableOomScoreAdjust = 133;
39 const uint32_t kBackgroundOomScoreAdjust = 167;
40 const uint32_t kPreallocOomScoreAdjust = 233;
42 static uint32_t OomScoreAdjForPriority(ProcessPriority aPriority) {
43 switch (aPriority) {
44 case PROCESS_PRIORITY_BACKGROUND:
45 return kBackgroundOomScoreAdjust;
46 case PROCESS_PRIORITY_BACKGROUND_PERCEIVABLE:
47 return kBackgroundPerceivableOomScoreAdjust;
48 case PROCESS_PRIORITY_PREALLOC:
49 return kPreallocOomScoreAdjust;
50 case PROCESS_PRIORITY_FOREGROUND:
51 return kForegroundOomScoreAdjust;
52 default:
53 return kParentOomScoreAdjust;
57 void SetProcessPriority(int aPid, ProcessPriority aPriority) {
58 HAL_LOG("LinuxProcessPriority - SetProcessPriority(%d, %s)\n", aPid,
59 ProcessPriorityToString(aPriority));
61 uint32_t oomScoreAdj = OomScoreAdjForPriority(aPriority);
63 char path[32] = {};
64 SprintfLiteral(path, "/proc/%d/oom_score_adj", aPid);
66 char oomScoreAdjStr[11] = {};
67 SprintfLiteral(oomScoreAdjStr, "%d", oomScoreAdj);
69 int fd = open(path, O_WRONLY);
70 if (fd < 0) {
71 return;
73 const size_t len = strlen(oomScoreAdjStr);
74 Unused << write(fd, oomScoreAdjStr, len);
75 Unused << close(fd);
78 } // namespace mozilla::hal_impl