Add collectRssInBackground()
This change adds collectRssInBackground() and recordRssSampleLPf(),
which are intended to be drop-in replacements for their less-efficient
PSS counterparts. These methods are only used if the
removeAppProfilerPssCollection flag is enabled.
In general, references to PSS have been kept in places where they can
apply to RSS without much friction (e.g. getLastPssTime). In places
where PSS was actually recorded for use, method names were renamed to
include "OrRss" (e.g. getInitialIdlePss -> getInitialIdlePssOrRss).
If an app has set a PSS threshold for collecting a heap dump using
ActivityManager.setWatchHeapLimit(), Debug.getPss() is called if the
build is debug or the app is debuggable. This is done _in addition_ to
the RSS read, but should be a relatively small cost compared to the
decrease in PSS reads overall.
The threshold for downgrading a service to a service B in OomAdjuster
is increased by a default 1.5 when the flag is enabled to account for
RSS > PSS. This value can be updated in device-specific configs, or on
the command line with:
device_config put activity_manager pss_to_rss_threshold_modifier <value>
This flag is still disabled, so this change will have no effect once
submitted. However, before the flag is flipped on in any capacity, we
should notify android-chatty that the PSS info in logs/dumps will
change in case these are being read for dashboards/metrics/etc.
Lastly, reportCachedKill() has been removed from ProcessProfileRecord
and ProcessState because while they seem to report AppProfiler-collected
PSS to WW, they are actually unused.
Test: - Check with test logs that collectRssInBackground() is called
when the feature flag is enabled.
- Check that device_config put activity_manager
pss_to_rss_threshold_modifier <value> propagates to AM.
Bug: 296454553
Change-Id: Ia4c4e14d7fb116e75857ea92c9fa2d2f534355f1
diff --git a/core/java/com/android/internal/app/procstats/ProcessState.java b/core/java/com/android/internal/app/procstats/ProcessState.java
index 755113b..0dbdb36 100644
--- a/core/java/com/android/internal/app/procstats/ProcessState.java
+++ b/core/java/com/android/internal/app/procstats/ProcessState.java
@@ -690,18 +690,6 @@
}
}
- public void reportCachedKill(ArrayMap<String, ProcessStateHolder> pkgList, long pss) {
- ensureNotDead();
- mCommonProcess.addCachedKill(1, pss, pss, pss);
- if (!mCommonProcess.mMultiPackage) {
- return;
- }
-
- for (int ip=pkgList.size()-1; ip>=0; ip--) {
- pullFixedProc(pkgList, ip).addCachedKill(1, pss, pss, pss);
- }
- }
-
public ProcessState pullFixedProc(String pkgName) {
if (mMultiPackage) {
// The array map is still pointing to a common process state
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index f827d28..68bad45 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -6806,6 +6806,10 @@
<!-- Whether or not ActivityManager PSS profiling is disabled. -->
<bool name="config_am_disablePssProfiling">false</bool>
+ <!-- The modifier used to adjust AM's PSS threshold for downgrading services to service B if
+ RSS is being collected instead. -->
+ <item name="config_am_pssToRssThresholdModifier" format="float" type="dimen">1.5</item>
+
<!-- Whether unlocking and waking a device are sequenced -->
<bool name="config_orderUnlockAndWake">false</bool>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 2f3b510..681a758 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -5262,6 +5262,7 @@
<!-- For ActivityManager PSS profiling configurability -->
<java-symbol type="bool" name="config_am_disablePssProfiling" />
+ <java-symbol type="dimen" name="config_am_pssToRssThresholdModifier" />
<java-symbol type="raw" name="default_ringtone_vibration_effect" />
diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java
index 9716cf6..3ce91c8 100644
--- a/services/core/java/com/android/server/am/ActivityManagerConstants.java
+++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java
@@ -1076,6 +1076,16 @@
public boolean APP_PROFILER_PSS_PROFILING_DISABLED;
+ /**
+ * The modifier used to adjust PSS thresholds in OomAdjuster when RSS is collected instead.
+ */
+ static final String KEY_PSS_TO_RSS_THRESHOLD_MODIFIER =
+ "pss_to_rss_threshold_modifier";
+
+ private final float mDefaultPssToRssThresholdModifier;
+
+ public float PSS_TO_RSS_THRESHOLD_MODIFIER;
+
private final OnPropertiesChangedListener mOnDeviceConfigChangedListener =
new OnPropertiesChangedListener() {
@Override
@@ -1254,6 +1264,9 @@
case KEY_DISABLE_APP_PROFILER_PSS_PROFILING:
updateDisableAppProfilerPssProfiling();
break;
+ case KEY_PSS_TO_RSS_THRESHOLD_MODIFIER:
+ updatePssToRssThresholdModifier();
+ break;
default:
updateFGSPermissionEnforcementFlagsIfNecessary(name);
break;
@@ -1339,6 +1352,10 @@
mDefaultDisableAppProfilerPssProfiling = context.getResources().getBoolean(
R.bool.config_am_disablePssProfiling);
APP_PROFILER_PSS_PROFILING_DISABLED = mDefaultDisableAppProfilerPssProfiling;
+
+ mDefaultPssToRssThresholdModifier = context.getResources().getFloat(
+ com.android.internal.R.dimen.config_am_pssToRssThresholdModifier);
+ PSS_TO_RSS_THRESHOLD_MODIFIER = mDefaultPssToRssThresholdModifier;
}
public void start(ContentResolver resolver) {
@@ -2051,6 +2068,12 @@
mDefaultDisableAppProfilerPssProfiling);
}
+ private void updatePssToRssThresholdModifier() {
+ PSS_TO_RSS_THRESHOLD_MODIFIER = DeviceConfig.getFloat(
+ DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_PSS_TO_RSS_THRESHOLD_MODIFIER,
+ mDefaultPssToRssThresholdModifier);
+ }
+
@NeverCompile // Avoid size overhead of debugging code.
void dump(PrintWriter pw) {
pw.println("ACTIVITY MANAGER SETTINGS (dumpsys activity settings) "
@@ -2242,6 +2265,9 @@
pw.print(" "); pw.print(KEY_DISABLE_APP_PROFILER_PSS_PROFILING);
pw.print("="); pw.println(APP_PROFILER_PSS_PROFILING_DISABLED);
+ pw.print(" "); pw.print(KEY_PSS_TO_RSS_THRESHOLD_MODIFIER);
+ pw.print("="); pw.println(PSS_TO_RSS_THRESHOLD_MODIFIER);
+
pw.println();
if (mOverrideMaxCachedProcesses >= 0) {
pw.print(" mOverrideMaxCachedProcesses="); pw.println(mOverrideMaxCachedProcesses);
diff --git a/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java b/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
index 5dd0a3f..55b161a 100644
--- a/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
+++ b/services/core/java/com/android/server/am/ActivityManagerDebugConfig.java
@@ -71,6 +71,7 @@
static final boolean DEBUG_PROCESSES = DEBUG_ALL || false;
static final boolean DEBUG_PROVIDER = DEBUG_ALL || false;
static final boolean DEBUG_PSS = DEBUG_ALL || false;
+ static final boolean DEBUG_RSS = DEBUG_ALL || false;
static final boolean DEBUG_SERVICE = DEBUG_ALL || false;
static final boolean DEBUG_FOREGROUND_SERVICE = DEBUG_ALL || false;
static final boolean DEBUG_SERVICE_EXECUTING = DEBUG_ALL || false;
@@ -91,6 +92,7 @@
? "_ProcessObservers" : "";
static final String POSTFIX_PROCESSES = (APPEND_CATEGORY_NAME) ? "_Processes" : "";
static final String POSTFIX_PSS = (APPEND_CATEGORY_NAME) ? "_Pss" : "";
+ static final String POSTFIX_RSS = (APPEND_CATEGORY_NAME) ? "_Rss" : "";
static final String POSTFIX_SERVICE = (APPEND_CATEGORY_NAME) ? "_Service" : "";
static final String POSTFIX_SERVICE_EXECUTING =
(APPEND_CATEGORY_NAME) ? "_ServiceExecuting" : "";
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index b99a98f..56e27d1 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -327,6 +327,7 @@
import android.os.DropBoxManager;
import android.os.FactoryTest;
import android.os.FileUtils;
+import android.os.Flags;
import android.os.Handler;
import android.os.IBinder;
import android.os.IDeviceIdentifiersPolicyService;
@@ -8560,6 +8561,12 @@
// If the processes' memory has increased by more than 1% of the total memory,
// or 10 MB, whichever is greater, then the processes' are eligible to be killed.
final long totalMemoryInKb = getTotalMemory() / 1000;
+
+ // This threshold should be applicable to both PSS and RSS because the value is absolute
+ // and represents an increase in process memory relative to its own previous state.
+ //
+ // TODO(b/296454553): Tune this value during the flag rollout process if more processes
+ // seem to be getting killed than before.
final long memoryGrowthThreshold =
Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD);
mProcessList.forEachLruProcessesLOSP(false, proc -> {
@@ -8572,24 +8579,34 @@
if (state.isNotCachedSinceIdle()) {
if (setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
&& setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
- final long initialIdlePss, lastPss, lastSwapPss;
+ final long initialIdlePssOrRss, lastPssOrRss, lastSwapPss;
synchronized (mAppProfiler.mProfilerLock) {
- initialIdlePss = pr.getInitialIdlePss();
- lastPss = pr.getLastPss();
+ initialIdlePssOrRss = pr.getInitialIdlePssOrRss();
+ lastPssOrRss = !Flags.removeAppProfilerPssCollection()
+ ? pr.getLastPss() : pr.getLastRss();
lastSwapPss = pr.getLastSwapPss();
}
- if (doKilling && initialIdlePss != 0
- && lastPss > (initialIdlePss * 3 / 2)
- && lastPss > (initialIdlePss + memoryGrowthThreshold)) {
+ if (doKilling && initialIdlePssOrRss != 0
+ && lastPssOrRss > (initialIdlePssOrRss * 3 / 2)
+ && lastPssOrRss > (initialIdlePssOrRss + memoryGrowthThreshold)) {
final StringBuilder sb2 = new StringBuilder(128);
sb2.append("Kill");
sb2.append(proc.processName);
- sb2.append(" in idle maint: pss=");
- sb2.append(lastPss);
- sb2.append(", swapPss=");
- sb2.append(lastSwapPss);
- sb2.append(", initialPss=");
- sb2.append(initialIdlePss);
+ if (!Flags.removeAppProfilerPssCollection()) {
+ sb2.append(" in idle maint: pss=");
+ } else {
+ sb2.append(" in idle maint: rss=");
+ }
+ sb2.append(lastPssOrRss);
+
+ if (!Flags.removeAppProfilerPssCollection()) {
+ sb2.append(", swapPss=");
+ sb2.append(lastSwapPss);
+ sb2.append(", initialPss=");
+ } else {
+ sb2.append(", initialRss=");
+ }
+ sb2.append(initialIdlePssOrRss);
sb2.append(", period=");
TimeUtils.formatDuration(timeSinceLastIdle, sb2);
sb2.append(", lowRamPeriod=");
@@ -8597,8 +8614,9 @@
Slog.wtfQuiet(TAG, sb2.toString());
mHandler.post(() -> {
synchronized (ActivityManagerService.this) {
- proc.killLocked("idle maint (pss " + lastPss
- + " from " + initialIdlePss + ")",
+ proc.killLocked(!Flags.removeAppProfilerPssCollection()
+ ? "idle maint (pss " : "idle maint (rss " + lastPssOrRss
+ + " from " + initialIdlePssOrRss + ")",
ApplicationExitInfo.REASON_OTHER,
ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE,
true);
@@ -8610,7 +8628,7 @@
&& setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) {
state.setNotCachedSinceIdle(true);
synchronized (mAppProfiler.mProfilerLock) {
- pr.setInitialIdlePss(0);
+ pr.setInitialIdlePssOrRss(0);
mAppProfiler.updateNextPssTimeLPf(
state.getSetProcState(), proc.mProfile, now, true);
}
diff --git a/services/core/java/com/android/server/am/AppProfiler.java b/services/core/java/com/android/server/am/AppProfiler.java
index 3cf4332..2e0aec9 100644
--- a/services/core/java/com/android/server/am/AppProfiler.java
+++ b/services/core/java/com/android/server/am/AppProfiler.java
@@ -28,7 +28,9 @@
import static com.android.internal.app.procstats.ProcessStats.ADJ_MEM_FACTOR_NORMAL;
import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PSS;
+import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RSS;
import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PSS;
+import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RSS;
import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
import static com.android.server.am.ActivityManagerService.DUMP_MEM_OOM_ADJ;
@@ -64,6 +66,7 @@
import android.os.Binder;
import android.os.Build;
import android.os.Debug;
+import android.os.Flags;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
@@ -125,6 +128,7 @@
private static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessList" : TAG_AM;
static final String TAG_PSS = TAG + POSTFIX_PSS;
+ static final String TAG_RSS = TAG + POSTFIX_RSS;
static final String TAG_OOM_ADJ = ActivityManagerService.TAG_OOM_ADJ;
@@ -183,10 +187,10 @@
private volatile long mPssDeferralTime = 0;
/**
- * Processes we want to collect PSS data from.
+ * Processes we want to collect PSS or RSS data from.
*/
@GuardedBy("mProfilerLock")
- private final ArrayList<ProcessProfileRecord> mPendingPssProfiles = new ArrayList<>();
+ private final ArrayList<ProcessProfileRecord> mPendingPssOrRssProfiles = new ArrayList<>();
/**
* Depth of overlapping activity-start PSS deferral notes
@@ -200,18 +204,18 @@
private long mLastFullPssTime = SystemClock.uptimeMillis();
/**
- * If set, the next time we collect PSS data we should do a full collection
- * with data from native processes and the kernel.
+ * If set, the next time we collect PSS or RSS data we should do a full collection with data
+ * from native processes and the kernel.
*/
@GuardedBy("mProfilerLock")
- private boolean mFullPssPending = false;
+ private boolean mFullPssOrRssPending = false;
/**
- * If true, we are running under a test environment so will sample PSS from processes
- * much more rapidly to try to collect better data when the tests are rapidly
- * running through apps.
+ * If true, we are running under a test environment so will sample PSS or RSS from processes
+ * much more rapidly to try to collect better data when the tests are rapidly running through
+ * apps.
*/
- private volatile boolean mTestPssMode = false;
+ private volatile boolean mTestPssOrRssMode = false;
private final LowMemDetector mLowMemDetector;
@@ -598,7 +602,11 @@
public void handleMessage(Message msg) {
switch (msg.what) {
case COLLECT_PSS_BG_MSG:
- collectPssInBackground();
+ if (!Flags.removeAppProfilerPssCollection()) {
+ collectPssInBackground();
+ } else {
+ collectRssInBackground();
+ }
break;
case DEFER_PSS_MSG:
deferPssForActivityStart();
@@ -619,8 +627,8 @@
long start = SystemClock.uptimeMillis();
MemInfoReader memInfo = null;
synchronized (mProfilerLock) {
- if (mFullPssPending) {
- mFullPssPending = false;
+ if (mFullPssOrRssPending) {
+ mFullPssOrRssPending = false;
memInfo = new MemInfoReader();
}
}
@@ -673,16 +681,16 @@
int pid = -1;
long lastPssTime;
synchronized (mProfilerLock) {
- if (mPendingPssProfiles.size() <= 0) {
- if (mTestPssMode || DEBUG_PSS) {
+ if (mPendingPssOrRssProfiles.size() <= 0) {
+ if (mTestPssOrRssMode || DEBUG_PSS) {
Slog.d(TAG_PSS,
"Collected pss of " + num + " processes in "
+ (SystemClock.uptimeMillis() - start) + "ms");
}
- mPendingPssProfiles.clear();
+ mPendingPssOrRssProfiles.clear();
return;
}
- profile = mPendingPssProfiles.remove(0);
+ profile = mPendingPssOrRssProfiles.remove(0);
procState = profile.getPssProcState();
statType = profile.getPssStatType();
lastPssTime = profile.getLastPssTime();
@@ -740,13 +748,149 @@
} while (true);
}
+ // This method is analogous to collectPssInBackground() and is intended to be used as a
+ // replacement if Flags.removeAppProfilerPssCollection() is enabled. References to PSS in
+ // methods outside of AppProfiler have generally been kept where a new RSS equivalent is not
+ // technically necessary. These can be updated once the flag is completely rolled out.
+ private void collectRssInBackground() {
+ long start = SystemClock.uptimeMillis();
+ MemInfoReader memInfo = null;
+ synchronized (mProfilerLock) {
+ if (mFullPssOrRssPending) {
+ mFullPssOrRssPending = false;
+ memInfo = new MemInfoReader();
+ }
+ }
+ if (memInfo != null) {
+ updateCpuStatsNow();
+ long nativeTotalRss = 0;
+ final List<ProcessCpuTracker.Stats> stats;
+ synchronized (mProcessCpuTracker) {
+ stats = mProcessCpuTracker.getStats(st -> {
+ return st.vsize > 0 && st.uid < FIRST_APPLICATION_UID;
+ });
+ }
+
+ // We assume that if PSS collection isn't needed or desired, RSS collection can be
+ // disabled as well.
+ if (!mService.mConstants.APP_PROFILER_PSS_PROFILING_DISABLED) {
+ final int numOfStats = stats.size();
+ for (int j = 0; j < numOfStats; j++) {
+ synchronized (mService.mPidsSelfLocked) {
+ if (mService.mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) {
+ // This is one of our own processes; skip it.
+ continue;
+ }
+ }
+ nativeTotalRss += Debug.getRss(stats.get(j).pid, null);
+ }
+ }
+
+ memInfo.readMemInfo();
+ synchronized (mService.mProcessStats.mLock) {
+ // We assume that an enabled DEBUG_PSS can apply to RSS as well, since only one of
+ // either collectPssInBackground() or collectRssInBackground() will be used.
+ if (DEBUG_RSS) {
+ Slog.d(TAG_RSS, "Collected native and kernel memory in "
+ + (SystemClock.uptimeMillis() - start) + "ms");
+ }
+ final long cachedKb = memInfo.getCachedSizeKb();
+ final long freeKb = memInfo.getFreeSizeKb();
+ final long zramKb = memInfo.getZramTotalSizeKb();
+ final long kernelKb = memInfo.getKernelUsedSizeKb();
+ // The last value needs to be updated in log tags to refer to RSS; this will be
+ // updated once the flag is fully rolled out.
+ EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024,
+ kernelKb * 1024, nativeTotalRss * 1024);
+ mService.mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
+ nativeTotalRss);
+ }
+ }
+
+ // This loop differs from its original form in collectPssInBackground(), as it does not
+ // collect USS or SwapPss (since those are reported in smaps, not status).
+ int num = 0;
+ do {
+ ProcessProfileRecord profile;
+ int procState;
+ int statType;
+ int pid = -1;
+ long lastRssTime;
+ synchronized (mProfilerLock) {
+ if (mPendingPssOrRssProfiles.size() <= 0) {
+ if (mTestPssOrRssMode || DEBUG_RSS) {
+ Slog.d(TAG_RSS,
+ "Collected rss of " + num + " processes in "
+ + (SystemClock.uptimeMillis() - start) + "ms");
+ }
+ mPendingPssOrRssProfiles.clear();
+ return;
+ }
+ profile = mPendingPssOrRssProfiles.remove(0);
+ procState = profile.getPssProcState();
+ statType = profile.getPssStatType();
+ lastRssTime = profile.getLastPssTime();
+ long now = SystemClock.uptimeMillis();
+ if (profile.getThread() != null && procState == profile.getSetProcState()
+ && (lastRssTime + ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE) < now) {
+ pid = profile.getPid();
+ } else {
+ profile.abortNextPssTime();
+ if (DEBUG_RSS) {
+ Slog.d(TAG_RSS, "Skipped rss collection of " + pid
+ + ": still need "
+ + (lastRssTime + ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE - now)
+ + "ms until safe");
+ }
+ profile = null;
+ pid = 0;
+ }
+ }
+ if (profile != null) {
+ long startTime = SystemClock.currentThreadTimeMillis();
+ // skip background RSS calculation under the following situations:
+ // - app is capturing camera imagery
+ // - app is frozen and we have already collected RSS once.
+ final boolean skipRSSCollection =
+ (profile.mApp.mOptRecord != null
+ && profile.mApp.mOptRecord.skipPSSCollectionBecauseFrozen())
+ || mService.isCameraActiveForUid(profile.mApp.uid)
+ || mService.mConstants.APP_PROFILER_PSS_PROFILING_DISABLED;
+ long rss = skipRSSCollection ? 0 : Debug.getRss(pid, null);
+ long endTime = SystemClock.currentThreadTimeMillis();
+ synchronized (mProfilerLock) {
+ if (rss != 0 && profile.getThread() != null
+ && profile.getSetProcState() == procState
+ && profile.getPid() == pid && profile.getLastPssTime() == lastRssTime) {
+ num++;
+ profile.commitNextPssTime();
+ recordRssSampleLPf(profile, procState, rss, statType, endTime - startTime,
+ SystemClock.uptimeMillis());
+ } else {
+ profile.abortNextPssTime();
+ if (DEBUG_RSS) {
+ Slog.d(TAG_RSS, "Skipped rss collection of " + pid
+ + ": " + (profile.getThread() == null ? "NO_THREAD " : "")
+ + (skipRSSCollection ? "SKIP_RSS_COLLECTION " : "")
+ + (profile.getPid() != pid ? "PID_CHANGED " : "")
+ + " initState=" + procState + " curState="
+ + profile.getSetProcState() + " "
+ + (profile.getLastPssTime() != lastRssTime
+ ? "TIME_CHANGED" : ""));
+ }
+ }
+ }
+ }
+ } while (true);
+ }
+
@GuardedBy("mProfilerLock")
void updateNextPssTimeLPf(int procState, ProcessProfileRecord profile, long now,
boolean forceUpdate) {
if (!forceUpdate) {
if (now <= profile.getNextPssTime() && now <= Math.max(profile.getLastPssTime()
+ ProcessList.PSS_MAX_INTERVAL, profile.getLastStateTime()
- + ProcessList.minTimeFromStateChange(mTestPssMode))) {
+ + ProcessList.minTimeFromStateChange(mTestPssOrRssMode))) {
// update is not due, ignore it.
return;
}
@@ -755,7 +899,7 @@
}
}
profile.setNextPssTime(profile.computeNextPssTime(procState,
- mTestPssMode, mService.mAtmInternal.isSleeping(), now));
+ mTestPssOrRssMode, mService.mAtmInternal.isSleeping(), now));
}
/**
@@ -776,8 +920,8 @@
+ " lastPss=" + profile.getLastPss()
+ " state=" + ProcessList.makeProcStateString(procState));
}
- if (profile.getInitialIdlePss() == 0) {
- profile.setInitialIdlePss(pss);
+ if (profile.getInitialIdlePssOrRss() == 0) {
+ profile.setInitialIdlePssOrRss(pss);
}
profile.setLastPss(pss);
profile.setLastSwapPss(swapPss);
@@ -813,6 +957,72 @@
}
}
+ /**
+ * Record new RSS sample for a process.
+ *
+ * This method is analogous to recordPssSampleLPf() and is intended to be used as a replacement
+ * if Flags.removeAppProfilerPssCollection() is enabled. Functionally, this differs in that PSS,
+ * SwapPss, and USS are no longer collected and reported.
+ *
+ * This method will also poll PSS if the app has requested that a heap dump be taken if its PSS
+ * reaches some threshold set with ActivityManager.setWatchHeapLimit().
+ */
+ @GuardedBy("mProfilerLock")
+ private void recordRssSampleLPf(ProcessProfileRecord profile, int procState, long rss,
+ int statType, long rssDuration, long now) {
+ final ProcessRecord proc = profile.mApp;
+ // TODO(b/296454553): writeAmPss needs to be renamed to writeAmRss, and the zeroed out
+ // fields need to be removed. This will be updated once the flag is fully rolled out to
+ // avoid churn in the .logtags file, which has a mapping of IDs to tags (and is also
+ // technically deprecated).
+ EventLogTags.writeAmPss(
+ profile.getPid(), proc.uid, proc.processName, /* pss = */ 0, /* uss = */ 0,
+ /* swapPss = */ 0, rss * 1024, statType, procState, rssDuration);
+ profile.setLastPssTime(now);
+ // The PSS here is emitted in logs, so we can zero it out instead of subbing in RSS.
+ profile.addPss(/* pss = */ 0, /* uss = */ 0, rss, true, statType, rssDuration);
+ if (DEBUG_RSS) {
+ Slog.d(TAG_RSS,
+ "rss of " + proc.toShortString() + ": " + rss
+ + " lastRss=" + profile.getLastRss()
+ + " state=" + ProcessList.makeProcStateString(procState));
+ }
+ if (profile.getInitialIdlePssOrRss() == 0) {
+ profile.setInitialIdlePssOrRss(rss);
+ }
+ profile.setLastRss(rss);
+ if (procState >= ActivityManager.PROCESS_STATE_HOME) {
+ profile.setLastCachedRss(rss);
+ }
+
+ final SparseArray<Pair<Long, String>> watchUids =
+ mMemWatchProcesses.getMap().get(proc.processName);
+ Long check = null;
+ if (watchUids != null) {
+ Pair<Long, String> val = watchUids.get(proc.uid);
+ if (val == null) {
+ val = watchUids.get(0);
+ }
+ if (val != null) {
+ check = val.first;
+ }
+ }
+
+ if (check != null) {
+ long pss = Debug.getPss(profile.getPid(), null, null);
+ if ((pss * 1024) >= check && profile.getThread() != null
+ && mMemWatchDumpProcName == null) {
+ if (Build.IS_DEBUGGABLE || proc.isDebuggable()) {
+ Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check + "; reporting");
+ startHeapDumpLPf(profile, false);
+ } else {
+ Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check
+ + ", but debugging not enabled");
+ }
+ }
+ }
+ }
+
private final class RecordPssRunnable implements Runnable {
private final ProcessProfileRecord mProfile;
private final Uri mDumpUri;
@@ -984,10 +1194,10 @@
*/
@GuardedBy("mProfilerLock")
private boolean requestPssLPf(ProcessProfileRecord profile, int procState) {
- if (mPendingPssProfiles.contains(profile)) {
+ if (mPendingPssOrRssProfiles.contains(profile)) {
return false;
}
- if (mPendingPssProfiles.size() == 0) {
+ if (mPendingPssOrRssProfiles.size() == 0) {
final long deferral = (mPssDeferralTime > 0 && mActivityStartingNesting.get() > 0)
? mPssDeferralTime : 0;
if (DEBUG_PSS && deferral > 0) {
@@ -999,7 +1209,7 @@
if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of: " + profile.mApp);
profile.setPssProcState(procState);
profile.setPssStatType(ProcessStats.ADD_PSS_INTERNAL_SINGLE);
- mPendingPssProfiles.add(profile);
+ mPendingPssOrRssProfiles.add(profile);
return true;
}
@@ -1009,7 +1219,7 @@
*/
@GuardedBy("mProfilerLock")
private void deferPssIfNeededLPf() {
- if (mPendingPssProfiles.size() > 0) {
+ if (mPendingPssOrRssProfiles.size() > 0) {
mBgHandler.removeMessages(BgHandler.COLLECT_PSS_BG_MSG);
mBgHandler.sendEmptyMessageDelayed(BgHandler.COLLECT_PSS_BG_MSG, mPssDeferralTime);
}
@@ -1063,12 +1273,12 @@
Slog.d(TAG_PSS, "Requesting pss of all procs! memLowered=" + memLowered);
}
mLastFullPssTime = now;
- mFullPssPending = true;
- for (int i = mPendingPssProfiles.size() - 1; i >= 0; i--) {
- mPendingPssProfiles.get(i).abortNextPssTime();
+ mFullPssOrRssPending = true;
+ for (int i = mPendingPssOrRssProfiles.size() - 1; i >= 0; i--) {
+ mPendingPssOrRssProfiles.get(i).abortNextPssTime();
}
- mPendingPssProfiles.ensureCapacity(mService.mProcessList.getLruSizeLOSP());
- mPendingPssProfiles.clear();
+ mPendingPssOrRssProfiles.ensureCapacity(mService.mProcessList.getLruSizeLOSP());
+ mPendingPssOrRssProfiles.clear();
mService.mProcessList.forEachLruProcessesLOSP(false, app -> {
final ProcessProfileRecord profile = app.mProfile;
if (profile.getThread() == null
@@ -1083,7 +1293,7 @@
profile.setPssStatType(always ? ProcessStats.ADD_PSS_INTERNAL_ALL_POLL
: ProcessStats.ADD_PSS_INTERNAL_ALL_MEM);
updateNextPssTimeLPf(profile.getSetProcState(), profile, now, true);
- mPendingPssProfiles.add(profile);
+ mPendingPssOrRssProfiles.add(profile);
}
});
if (!mBgHandler.hasMessages(BgHandler.COLLECT_PSS_BG_MSG)) {
@@ -1094,7 +1304,7 @@
void setTestPssMode(boolean enabled) {
synchronized (mProcLock) {
- mTestPssMode = enabled;
+ mTestPssOrRssMode = enabled;
if (enabled) {
// Whenever we enable the mode, we want to take a snapshot all of current
// process mem use.
@@ -1104,7 +1314,7 @@
}
boolean getTestPssMode() {
- return mTestPssMode;
+ return mTestPssOrRssMode;
}
@GuardedBy("mService")
@@ -2346,7 +2556,7 @@
synchronized (mProfilerLock) {
final ProcessProfileRecord profile = app.mProfile;
mProcessesToGc.remove(app);
- mPendingPssProfiles.remove(profile);
+ mPendingPssOrRssProfiles.remove(profile);
profile.abortNextPssTime();
}
}
diff --git a/services/core/java/com/android/server/am/OomAdjuster.java b/services/core/java/com/android/server/am/OomAdjuster.java
index 9bba08a..5eccfc5 100644
--- a/services/core/java/com/android/server/am/OomAdjuster.java
+++ b/services/core/java/com/android/server/am/OomAdjuster.java
@@ -144,6 +144,7 @@
import android.content.pm.ApplicationInfo;
import android.content.pm.ServiceInfo;
import android.net.NetworkPolicyManager;
+import android.os.Flags;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManagerInternal;
@@ -2416,9 +2417,23 @@
// normally be a B service, but if we are low on RAM and it
// is large we want to force it down since we would prefer to
// keep launcher over it.
+ long lastPssOrRss = !Flags.removeAppProfilerPssCollection()
+ ? app.mProfile.getLastPss() : app.mProfile.getLastRss();
+
+ // RSS is larger than PSS, but the RSS/PSS ratio varies per-process based on how
+ // many shared pages a process uses. The threshold is increased if the flag for
+ // reading RSS instead of PSS is enabled.
+ //
+ // TODO(b/296454553): Tune the second value so that the relative number of
+ // service B is similar before/after this flag is enabled.
+ double thresholdModifier = !Flags.removeAppProfilerPssCollection()
+ ? 1
+ : mConstants.PSS_TO_RSS_THRESHOLD_MODIFIER;
+ double cachedRestoreThreshold =
+ mProcessList.getCachedRestoreThresholdKb() * thresholdModifier;
+
if (!mService.mAppProfiler.isLastMemoryLevelNormal()
- && app.mProfile.getLastPss()
- >= mProcessList.getCachedRestoreThresholdKb()) {
+ && lastPssOrRss >= cachedRestoreThreshold) {
state.setServiceHighRam(true);
state.setServiceB(true);
//Slog.i(TAG, "ADJ " + app + " high ram!");
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index 2efac12..cb2b5fb 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -94,6 +94,7 @@
import android.os.Build;
import android.os.Bundle;
import android.os.DropBoxManager;
+import android.os.Flags;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
@@ -4594,6 +4595,8 @@
r.mProfile.getLastPss() * 1024, new StringBuilder()));
proto.write(ProcessOomProto.Detail.LAST_SWAP_PSS, DebugUtils.sizeValueToString(
r.mProfile.getLastSwapPss() * 1024, new StringBuilder()));
+ // TODO(b/296454553): This proto field should be replaced with last cached RSS once
+ // AppProfiler is no longer collecting PSS.
proto.write(ProcessOomProto.Detail.LAST_CACHED_PSS, DebugUtils.sizeValueToString(
r.mProfile.getLastCachedPss() * 1024, new StringBuilder()));
proto.write(ProcessOomProto.Detail.CACHED, state.isCached());
@@ -4725,12 +4728,20 @@
pw.print(" ");
pw.print("state: cur="); pw.print(makeProcStateString(state.getCurProcState()));
pw.print(" set="); pw.print(makeProcStateString(state.getSetProcState()));
- pw.print(" lastPss=");
- DebugUtils.printSizeValue(pw, r.mProfile.getLastPss() * 1024);
- pw.print(" lastSwapPss=");
- DebugUtils.printSizeValue(pw, r.mProfile.getLastSwapPss() * 1024);
- pw.print(" lastCachedPss=");
- DebugUtils.printSizeValue(pw, r.mProfile.getLastCachedPss() * 1024);
+ // These values won't be collected if the flag is enabled.
+ if (!Flags.removeAppProfilerPssCollection()) {
+ pw.print(" lastPss=");
+ DebugUtils.printSizeValue(pw, r.mProfile.getLastPss() * 1024);
+ pw.print(" lastSwapPss=");
+ DebugUtils.printSizeValue(pw, r.mProfile.getLastSwapPss() * 1024);
+ pw.print(" lastCachedPss=");
+ DebugUtils.printSizeValue(pw, r.mProfile.getLastCachedPss() * 1024);
+ } else {
+ pw.print(" lastRss=");
+ DebugUtils.printSizeValue(pw, r.mProfile.getLastRss() * 1024);
+ pw.print(" lastCachedRss=");
+ DebugUtils.printSizeValue(pw, r.mProfile.getLastCachedRss() * 1024);
+ }
pw.println();
pw.print(prefix);
pw.print(" ");
diff --git a/services/core/java/com/android/server/am/ProcessProfileRecord.java b/services/core/java/com/android/server/am/ProcessProfileRecord.java
index 354f3d3..8ca64f8 100644
--- a/services/core/java/com/android/server/am/ProcessProfileRecord.java
+++ b/services/core/java/com/android/server/am/ProcessProfileRecord.java
@@ -23,6 +23,7 @@
import android.app.ProcessMemoryState.HostingComponentType;
import android.content.pm.ApplicationInfo;
import android.os.Debug;
+import android.os.Flags;
import android.os.Process;
import android.os.SystemClock;
import android.util.DebugUtils;
@@ -32,7 +33,6 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.app.procstats.ProcessState;
import com.android.internal.app.procstats.ProcessStats;
-import com.android.internal.util.FrameworkStatsLog;
import com.android.server.am.ProcessList.ProcStateMemTracker;
import com.android.server.power.stats.BatteryStatsImpl;
@@ -42,6 +42,8 @@
/**
* Profiling info of the process, such as PSS, cpu, etc.
+ *
+ * TODO(b/297542292): Update PSS names with RSS once AppProfiler's PSS profiling has been replaced.
*/
final class ProcessProfileRecord {
final ProcessRecord mApp;
@@ -76,7 +78,7 @@
* Initial memory pss of process for idle maintenance.
*/
@GuardedBy("mProfilerLock")
- private long mInitialIdlePss;
+ private long mInitialIdlePssOrRss;
/**
* Last computed memory pss.
@@ -109,6 +111,14 @@
private long mLastRss;
/**
+ * Last computed rss when in cached state.
+ *
+ * This value is not set or retrieved unless Flags.removeAppProfilerPssCollection() is true.
+ */
+ @GuardedBy("mProfilerLock")
+ private long mLastCachedRss;
+
+ /**
* Cache of last retrieve memory info, to throttle how frequently apps can request it.
*/
@GuardedBy("mProfilerLock")
@@ -347,13 +357,13 @@
}
@GuardedBy("mProfilerLock")
- long getInitialIdlePss() {
- return mInitialIdlePss;
+ long getInitialIdlePssOrRss() {
+ return mInitialIdlePssOrRss;
}
@GuardedBy("mProfilerLock")
- void setInitialIdlePss(long initialIdlePss) {
- mInitialIdlePss = initialIdlePss;
+ void setInitialIdlePssOrRss(long initialIdlePssOrRss) {
+ mInitialIdlePssOrRss = initialIdlePssOrRss;
}
@GuardedBy("mProfilerLock")
@@ -377,6 +387,16 @@
}
@GuardedBy("mProfilerLock")
+ long getLastCachedRss() {
+ return mLastCachedRss;
+ }
+
+ @GuardedBy("mProfilerLock")
+ void setLastCachedRss(long lastCachedRss) {
+ mLastCachedRss = lastCachedRss;
+ }
+
+ @GuardedBy("mProfilerLock")
long getLastSwapPss() {
return mLastSwapPss;
}
@@ -530,26 +550,6 @@
}
}
- void reportCachedKill() {
- synchronized (mService.mProcessStats.mLock) {
- final ProcessState tracker = mBaseProcessTracker;
- if (tracker != null) {
- final PackageList pkgList = mApp.getPkgList();
- synchronized (pkgList) {
- tracker.reportCachedKill(pkgList.getPackageListLocked(), mLastCachedPss);
- pkgList.forEachPackageProcessStats(holder ->
- FrameworkStatsLog.write(FrameworkStatsLog.CACHED_KILL_REPORTED,
- getUidForAttribution(mApp),
- holder.state.getName(),
- holder.state.getPackage(),
- mLastCachedPss,
- holder.appVersion)
- );
- }
- }
- }
- }
-
void setProcessTrackerState(int procState, int memFactor) {
synchronized (mService.mProcessStats.mLock) {
final ProcessState tracker = mBaseProcessTracker;
@@ -676,27 +676,46 @@
@GuardedBy("mService")
void dumpPss(PrintWriter pw, String prefix, long nowUptime) {
synchronized (mProfilerLock) {
- pw.print(prefix);
- pw.print("lastPssTime=");
- TimeUtils.formatDuration(mLastPssTime, nowUptime, pw);
- pw.print(" pssProcState=");
- pw.print(mPssProcState);
- pw.print(" pssStatType=");
- pw.print(mPssStatType);
- pw.print(" nextPssTime=");
- TimeUtils.formatDuration(mNextPssTime, nowUptime, pw);
- pw.println();
- pw.print(prefix);
- pw.print("lastPss=");
- DebugUtils.printSizeValue(pw, mLastPss * 1024);
- pw.print(" lastSwapPss=");
- DebugUtils.printSizeValue(pw, mLastSwapPss * 1024);
- pw.print(" lastCachedPss=");
- DebugUtils.printSizeValue(pw, mLastCachedPss * 1024);
- pw.print(" lastCachedSwapPss=");
- DebugUtils.printSizeValue(pw, mLastCachedSwapPss * 1024);
- pw.print(" lastRss=");
- DebugUtils.printSizeValue(pw, mLastRss * 1024);
+ // TODO(b/297542292): Remove this case once PSS profiling is replaced
+ if (!Flags.removeAppProfilerPssCollection()) {
+ pw.print(prefix);
+ pw.print("lastPssTime=");
+ TimeUtils.formatDuration(mLastPssTime, nowUptime, pw);
+ pw.print(" pssProcState=");
+ pw.print(mPssProcState);
+ pw.print(" pssStatType=");
+ pw.print(mPssStatType);
+ pw.print(" nextPssTime=");
+ TimeUtils.formatDuration(mNextPssTime, nowUptime, pw);
+ pw.println();
+ pw.print(prefix);
+ pw.print("lastPss=");
+ DebugUtils.printSizeValue(pw, mLastPss * 1024);
+ pw.print(" lastSwapPss=");
+ DebugUtils.printSizeValue(pw, mLastSwapPss * 1024);
+ pw.print(" lastCachedPss=");
+ DebugUtils.printSizeValue(pw, mLastCachedPss * 1024);
+ pw.print(" lastCachedSwapPss=");
+ DebugUtils.printSizeValue(pw, mLastCachedSwapPss * 1024);
+ pw.print(" lastRss=");
+ DebugUtils.printSizeValue(pw, mLastRss * 1024);
+ } else {
+ pw.print(prefix);
+ pw.print("lastRssTime=");
+ TimeUtils.formatDuration(mLastPssTime, nowUptime, pw);
+ pw.print(" rssProcState=");
+ pw.print(mPssProcState);
+ pw.print(" rssStatType=");
+ pw.print(mPssStatType);
+ pw.print(" nextRssTime=");
+ TimeUtils.formatDuration(mNextPssTime, nowUptime, pw);
+ pw.println();
+ pw.print(prefix);
+ pw.print("lastRss=");
+ DebugUtils.printSizeValue(pw, mLastRss * 1024);
+ pw.print(" lastCachedRss=");
+ DebugUtils.printSizeValue(pw, mLastCachedRss * 1024);
+ }
pw.println();
pw.print(prefix);
pw.print("trimMemoryLevel=");
diff --git a/services/core/java/com/android/server/am/ProcessStateRecord.java b/services/core/java/com/android/server/am/ProcessStateRecord.java
index 27c0876..8723c5d 100644
--- a/services/core/java/com/android/server/am/ProcessStateRecord.java
+++ b/services/core/java/com/android/server/am/ProcessStateRecord.java
@@ -29,6 +29,7 @@
import android.annotation.ElapsedRealtimeLong;
import android.app.ActivityManager;
import android.content.ComponentName;
+import android.os.Flags;
import android.os.SystemClock;
import android.os.Trace;
import android.util.Slog;
@@ -1366,7 +1367,12 @@
}
if (mNotCachedSinceIdle) {
pw.print(prefix); pw.print("notCachedSinceIdle="); pw.print(mNotCachedSinceIdle);
- pw.print(" initialIdlePss="); pw.println(mApp.mProfile.getInitialIdlePss());
+ if (!Flags.removeAppProfilerPssCollection()) {
+ pw.print(" initialIdlePss=");
+ } else {
+ pw.print(" initialIdleRss=");
+ }
+ pw.println(mApp.mProfile.getInitialIdlePssOrRss());
}
if (hasTopUi() || hasOverlayUi() || mRunningRemoteAnimation) {
pw.print(prefix); pw.print("hasTopUi="); pw.print(hasTopUi());