LinuxProcessPriority.cpp (2843B)
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/. */ 4 5 #include "Hal.h" 6 #include "HalLog.h" 7 8 #include "mozilla/Sprintf.h" 9 10 #include <fcntl.h> 11 #include <unistd.h> 12 13 using namespace mozilla::hal; 14 15 namespace mozilla::hal_impl { 16 17 /* The Linux OOM score is a value computed by the kernel ranging between 0 and 18 * 1000 and indicating how likely is a process to be killed when memory is 19 * tight. The larger the value the more likely a process is to be killed. The 20 * score is computed based on the amount of memory used plus an adjustment 21 * value. We chose our adjustment values to make it likely that processes are 22 * killed in the following order: 23 * 24 * 1. preallocated processes 25 * 2. background processes 26 * 3. background processes playing video (but no audio) 27 * 4. foreground processes or processes playing or recording audio 28 * 5. gpu process or anything else high priority 29 * 6. the parent process 30 * 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. */ 35 36 const uint32_t kParentOomScoreAdjust = 0; 37 const uint32_t kForegroundHighOomScoreAdjust = 100; 38 const uint32_t kForegroundOomScoreAdjust = 133; 39 const uint32_t kBackgroundPerceivableOomScoreAdjust = 167; 40 const uint32_t kBackgroundOomScoreAdjust = 200; 41 const uint32_t kPreallocOomScoreAdjust = 233; 42 43 static uint32_t OomScoreAdjForPriority(ProcessPriority aPriority) { 44 switch (aPriority) { 45 case PROCESS_PRIORITY_BACKGROUND: 46 return kBackgroundOomScoreAdjust; 47 case PROCESS_PRIORITY_BACKGROUND_PERCEIVABLE: 48 return kBackgroundPerceivableOomScoreAdjust; 49 case PROCESS_PRIORITY_PREALLOC: 50 return kPreallocOomScoreAdjust; 51 case PROCESS_PRIORITY_FOREGROUND: 52 return kForegroundOomScoreAdjust; 53 case PROCESS_PRIORITY_FOREGROUND_HIGH: 54 return kForegroundHighOomScoreAdjust; 55 default: 56 return kParentOomScoreAdjust; 57 } 58 } 59 60 void SetProcessPriority(int aPid, ProcessPriority aPriority) { 61 HAL_LOG("LinuxProcessPriority - SetProcessPriority(%d, %s)\n", aPid, 62 ProcessPriorityToString(aPriority)); 63 64 uint32_t oomScoreAdj = OomScoreAdjForPriority(aPriority); 65 66 char path[32] = {}; 67 SprintfLiteral(path, "/proc/%d/oom_score_adj", aPid); 68 69 char oomScoreAdjStr[11] = {}; 70 SprintfLiteral(oomScoreAdjStr, "%d", oomScoreAdj); 71 72 int fd = open(path, O_WRONLY); 73 if (fd < 0) { 74 return; 75 } 76 const size_t len = strlen(oomScoreAdjStr); 77 [[maybe_unused]] ssize_t _ = write(fd, oomScoreAdjStr, len); 78 (void)close(fd); 79 } 80 81 } // namespace mozilla::hal_impl