Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 3fd24c96 authored by Chih-Yu Huang's avatar Chih-Yu Huang
Browse files

am: Make forEachConnectionLSP use internal classes

This change refactors the OomAdjusterImpl.forEachConnectionLSP() and its
related methods to internal record classes for improved encapsulation
and design.

Bug: 425766486
Test: m services.core
Test: atest MockingOomAdjusterTests OomAdjusterTests
Test: atest FrameworksServicesTestsRavenwood_ProcessStateController
Flag: EXEMPT pure refactor

Change-Id: Idb423b88beaea70a4fb60cc2f6fde08bcd827934
parent cfebc957
Loading
Loading
Loading
Loading
+33 −29
Original line number Diff line number Diff line
@@ -150,6 +150,7 @@ import com.android.server.am.psc.ConnectionRecordInternal;
import com.android.server.am.psc.ContentProviderConnectionInternal;
import com.android.server.am.psc.PlatformCompatCache;
import com.android.server.am.psc.PlatformCompatCache.CachedCompatChangeId;
import com.android.server.am.psc.ProcessProviderRecordInternal;
import com.android.server.am.psc.ProcessRecordInternal;
import com.android.server.am.psc.ProcessServiceRecordInternal;
import com.android.server.am.psc.ServiceRecordInternal;
@@ -349,12 +350,11 @@ public abstract class OomAdjuster {
    final ActivityManagerGlobalLock mProcLock;

    private final int mNumSlots;
    protected final ArrayList<ProcessRecord> mTmpProcessList = new ArrayList<ProcessRecord>();
    protected final ArrayList<UidRecordInternal> mTmpBecameIdle =
            new ArrayList<UidRecordInternal>();
    protected final ArrayList<ProcessRecordInternal> mTmpProcessList = new ArrayList<>();
    protected final ArrayList<UidRecordInternal> mTmpBecameIdle = new ArrayList<>();
    protected final ActiveUids mTmpUidRecords;
    protected final ArrayDeque<ProcessRecord> mTmpQueue;
    protected final ArraySet<ProcessRecord> mTmpProcessSet = new ArraySet<>();
    protected final ArrayDeque<ProcessRecordInternal> mTmpQueue;
    protected final ArraySet<ProcessRecordInternal> mTmpProcessSet = new ArraySet<>();
    protected final ArraySet<ProcessRecord> mPendingProcessSet = new ArraySet<>();

    /**
@@ -514,7 +514,7 @@ public abstract class OomAdjuster {
            return true;
        });
        mTmpUidRecords = new ActiveUids(null);
        mTmpQueue = new ArrayDeque<ProcessRecord>(mConstants.CUR_MAX_CACHED_PROCESSES << 1);
        mTmpQueue = new ArrayDeque<>(mConstants.CUR_MAX_CACHED_PROCESSES << 1);
        mNumSlots = ((CACHED_APP_MAX_ADJ - CACHED_APP_MIN_ADJ + 1) >> 1)
                / CACHED_APP_IMPORTANCE_LEVELS;
    }
@@ -682,7 +682,7 @@ public abstract class OomAdjuster {
     */
    @GuardedBy({"mService", "mProcLock"})
    protected abstract void collectReachableProcessesLSP(
            @NonNull ArrayList<ProcessRecord> reachables);
            @NonNull ArrayList<ProcessRecordInternal> reachables);

    /**
     * Collect the reachable processes from the given {@code apps}, the result will be
@@ -690,14 +690,14 @@ public abstract class OomAdjuster {
     * the given {@code apps}.
     */
    @GuardedBy("mService")
    protected boolean collectReachableProcessesLocked(ArraySet<ProcessRecord> apps,
            ArrayList<ProcessRecord> processes) {
    protected boolean collectReachableProcessesLocked(ArraySet<ProcessRecordInternal> apps,
            ArrayList<ProcessRecordInternal> processes) {
        final ActiveUidsInternal uids = mTmpUidRecords;
        final ArrayDeque<ProcessRecord> queue = mTmpQueue;
        final ArrayDeque<ProcessRecordInternal> queue = mTmpQueue;
        queue.clear();
        processes.clear();
        for (int i = 0, size = apps.size(); i < size; i++) {
            final ProcessRecord app = apps.valueAt(i);
            final ProcessRecordInternal app = apps.valueAt(i);
            app.setReachable(true);
            queue.offer(app);
        }
@@ -707,18 +707,19 @@ public abstract class OomAdjuster {
        // Track if any of them reachables could include a cycle
        boolean containsCycle = false;
        // Scan downstreams of the process record
        for (ProcessRecord pr = queue.poll(); pr != null; pr = queue.poll()) {
        while (!queue.isEmpty()) {
            final ProcessRecordInternal pr = queue.poll();
            processes.add(pr);
            final UidRecordInternal uidRec = pr.getUidRecord();
            if (uidRec != null) {
                uids.put(uidRec.getUid(), uidRec);
            }
            final ProcessServiceRecord psr = pr.mServices;
            final ProcessServiceRecordInternal psr = pr.getServices();
            for (int i = psr.numberOfConnections() - 1; i >= 0; i--) {
                ConnectionRecord cr = psr.getConnectionAt(i);
                ProcessRecord service = cr.hasFlag(ServiceInfo.FLAG_ISOLATED_PROCESS)
                        ? cr.binding.service.getIsolationHostProcess()
                        : cr.binding.service.getHostProcess();
                ConnectionRecordInternal cr = psr.getConnectionAt(i);
                ProcessRecordInternal service = cr.hasFlag(ServiceInfo.FLAG_ISOLATED_PROCESS)
                        ? cr.getService().getIsolationHostProcess()
                        : cr.getService().getHostProcess();
                if (service == null || service == pr
                        || ((service.getMaxAdj() >= ProcessList.SYSTEM_ADJ)
                                && (service.getMaxAdj() < FOREGROUND_APP_ADJ))) {
@@ -736,10 +737,10 @@ public abstract class OomAdjuster {
                queue.offer(service);
                service.setReachable(true);
            }
            final ProcessProviderRecord ppr = pr.getProviders();
            final ProcessProviderRecordInternal ppr = pr.getProviders();
            for (int i = ppr.numberOfProviderConnections() - 1; i >= 0; i--) {
                ContentProviderConnection cpc = ppr.getProviderConnectionAt(i);
                ProcessRecord provider = cpc.provider.getHostProcess();
                ContentProviderConnectionInternal cpc = ppr.getProviderConnectionAt(i);
                ProcessRecordInternal provider = cpc.getProvider().getHostProcess();
                if (provider == null || provider == pr
                        || ((provider.getMaxAdj() >= ProcessList.SYSTEM_ADJ)
                                && (provider.getMaxAdj() < FOREGROUND_APP_ADJ))) {
@@ -797,8 +798,8 @@ public abstract class OomAdjuster {
        if (size > 0) {
            // Reverse the process list, since the updateOomAdjInnerLSP scans from the end of it.
            for (int l = 0, r = size - 1; l < r; l++, r--) {
                final ProcessRecord t = processes.get(l);
                final ProcessRecord u = processes.get(r);
                final ProcessRecordInternal t = processes.get(l);
                final ProcessRecordInternal u = processes.get(r);
                t.setReachable(false);
                u.setReachable(false);
                processes.set(l, u);
@@ -1768,7 +1769,7 @@ public abstract class OomAdjuster {
        return isDeviceFullyAwake() || state.isRunningRemoteAnimation();
    }

    protected boolean isBackupProcess(ProcessRecord app) {
    protected boolean isBackupProcess(ProcessRecordInternal app) {
        if (Flags.pushGlobalStateToOomadjuster()) {
            return app == mGlobalState.getBackupTarget(app.userId);
        } else {
@@ -1976,7 +1977,8 @@ public abstract class OomAdjuster {
    }

    @CpuTimeReasons
    private static int getCpuTimeReasons(ProcessRecord app, boolean hasForegroundActivities) {
    private static int getCpuTimeReasons(ProcessRecordInternal app,
            boolean hasForegroundActivities) {
        // Note: persistent processes always get CPU_TIME with reason CPU_TIME_REASON_OTHER.
        // Currently, we only cite CPU_TIME_REASON_OTHER for all reasons. More specific reasons
        // can be used when they become interesting to observe.
@@ -1991,11 +1993,11 @@ public abstract class OomAdjuster {
            // Process has user perceptible activities.
            return CPU_TIME_REASON_OTHER;
        }
        if (app.mServices.hasExecutingServices()) {
        if (app.getServices().hasExecutingServices()) {
            // Ensure that services get cpu time during start-up and tear-down.
            return CPU_TIME_REASON_OTHER;
        }
        if (app.mServices.hasForegroundServices()) {
        if (app.getServices().hasForegroundServices()) {
            return CPU_TIME_REASON_OTHER;
        }
        if (app.getReceivers().isReceivingBroadcast()) {
@@ -2009,7 +2011,8 @@ public abstract class OomAdjuster {
        return CPU_TIME_REASON_NONE;
    }

    protected static int getCpuCapability(ProcessRecord app, boolean hasForegroundActivities) {
    protected static int getCpuCapability(ProcessRecordInternal app,
            boolean hasForegroundActivities) {
        final int reasons = getCpuTimeReasons(app, hasForegroundActivities);
        app.addCurCpuTimeReasons(reasons);
        return (reasons != CPU_TIME_REASON_NONE) ? PROCESS_CAPABILITY_CPU_TIME : 0;
@@ -2779,7 +2782,7 @@ public abstract class OomAdjuster {
            return;
        }

        final ArrayList<ProcessRecord> processes = mTmpProcessList;
        final ArrayList<ProcessRecordInternal> processes = mTmpProcessList;

        if (Flags.consolidateCollectReachable()) {
            processes.add(app);
@@ -2794,7 +2797,8 @@ public abstract class OomAdjuster {
        // Now processes contains app's downstream and app
        final int size = processes.size();
        for (int i = 0; i < size; i++) {
            ProcessRecord proc = processes.get(i);
            // TODO: b/425766486 - Consider how to pass ProcessRecordInternal to CachedAppOptimizer.
            ProcessRecord proc = (ProcessRecord) processes.get(i);
            mCachedAppOptimizer.unfreezeTemporarily(proc,
                    CachedAppOptimizer.getUnfreezeReasonCodeFromOomAdjReason(reason));
        }
+38 −33
Original line number Diff line number Diff line
@@ -541,15 +541,15 @@ public class OomAdjusterImpl extends OomAdjuster {
     * A helper consumer for marking and collecting reachable processes.
     */
    private static class ReachableCollectingConsumer implements
            BiConsumer<Connection, ProcessRecord> {
        ArrayList<ProcessRecord> mReachables = null;
            BiConsumer<Connection, ProcessRecordInternal> {
        ArrayList<ProcessRecordInternal> mReachables = null;

        public void init(ArrayList<ProcessRecord> reachables) {
        public void init(ArrayList<ProcessRecordInternal> reachables) {
            mReachables = reachables;
        }

        @Override
        public void accept(Connection unused, ProcessRecord host) {
        public void accept(Connection unused, ProcessRecordInternal host) {
            if (host.isReachable()) {
                return;
            }
@@ -603,11 +603,11 @@ public class OomAdjusterImpl extends OomAdjuster {
    /**
     * A helper consumer for computing host process importance from a connection from a client app.
     */
    private class ComputeHostConsumer implements BiConsumer<Connection, ProcessRecord> {
    private class ComputeHostConsumer implements BiConsumer<Connection, ProcessRecordInternal> {
        public OomAdjusterArgs args = null;

        @Override
        public void accept(Connection conn, ProcessRecord host) {
        public void accept(Connection conn, ProcessRecordInternal host) {
            final ProcessRecordInternal client = args.mApp;
            final int cachedAdj = args.mCachedAdj;
            final ProcessRecord topApp = args.mTopApp;
@@ -637,7 +637,7 @@ public class OomAdjusterImpl extends OomAdjuster {
    private class ComputeConnectionsConsumer implements Consumer<OomAdjusterArgs> {
        @Override
        public void accept(OomAdjusterArgs args) {
            final ProcessRecord app = args.mApp;
            final ProcessRecordInternal app = args.mApp;
            final ActiveUidsInternal uids = args.mUids;

            // This process was updated in some way, mark that it was last calculated this sequence.
@@ -849,7 +849,7 @@ public class OomAdjusterImpl extends OomAdjuster {

        mAdjSeq++;

        final ArrayList<ProcessRecord> reachables = mTmpProcessList;
        final ArrayList<ProcessRecordInternal> reachables = mTmpProcessList;
        reachables.clear();

        for (int i = 0, size = targets.size(); i < size; i++) {
@@ -915,7 +915,8 @@ public class OomAdjusterImpl extends OomAdjuster {

    @GuardedBy({"mService", "mProcLock"})
    @Override
    protected void collectReachableProcessesLSP(@NonNull ArrayList<ProcessRecord> reachables) {
    protected void collectReachableProcessesLSP(
            @NonNull ArrayList<ProcessRecordInternal> reachables) {
        collectAndMarkReachableProcessesLSP(reachables);
        for (int i = 0, size = reachables.size(); i < size; i++) {
            final ProcessRecordInternal state = reachables.get(i);
@@ -928,10 +929,10 @@ public class OomAdjusterImpl extends OomAdjuster {
     * provided {@code reachables} list (targets excluded).
     */
    @GuardedBy({"mService", "mProcLock"})
    private void collectAndMarkReachableProcessesLSP(ArrayList<ProcessRecord> reachables) {
    private void collectAndMarkReachableProcessesLSP(ArrayList<ProcessRecordInternal> reachables) {
        mReachableCollectingConsumer.init(reachables);
        for (int i = 0; i < reachables.size(); i++) {
            ProcessRecord pr = reachables.get(i);
            ProcessRecordInternal pr = reachables.get(i);
            forEachConnectionLSP(pr, mReachableCollectingConsumer);
        }
    }
@@ -940,18 +941,20 @@ public class OomAdjusterImpl extends OomAdjuster {
     * Calculate initial importance states for {@code reachables} and update their slot position
     * if necessary.
     */
    private void initReachableStatesLSP(ArrayList<ProcessRecord> reachables, int targetCount,
            OomAdjusterArgs args) {
    private void initReachableStatesLSP(ArrayList<ProcessRecordInternal> reachables,
            int targetCount, OomAdjusterArgs args) {
        int i = 0;
        boolean initReachables = !Flags.skipUnimportantConnections();
        for (; i < targetCount && !initReachables; i++) {
            final ProcessRecord target = reachables.get(i);
            final ProcessRecordInternal target = reachables.get(i);
            final int prevProcState = target.getCurProcState();
            final int prevAdj = target.getCurRawAdj();
            final int prevCapability = target.getCurCapability();
            final boolean prevShouldNotFreeze = target.mOptRecord.shouldNotFreeze();
            final boolean prevShouldNotFreeze = target.shouldNotFreeze();

            args.mApp = target;
            // TODO: b/425766486 - Remove the type casting after OomAdjusterArgs.mApp is migrated
            //  to ProcessRecordInternal.
            args.mApp = (ProcessRecord) target;
            // If target client is a reachable, reachables need to be reinited in case this
            // client is important enough to change this target in the computeConnection step.
            initReachables |= computeOomAdjIgnoringReachablesLSP(args);
@@ -969,8 +972,10 @@ public class OomAdjusterImpl extends OomAdjuster {
        }

        for (int size = reachables.size(); i < size; i++) {
            final ProcessRecord reachable = reachables.get(i);
            args.mApp = reachable;
            final ProcessRecordInternal reachable = reachables.get(i);
            // TODO: b/425766486 - Remove the type casting after OomAdjusterArgs.mApp is migrated
            //  to ProcessRecordInternal.
            args.mApp = (ProcessRecord) reachable;
            computeOomAdjIgnoringReachablesLSP(args);

            // Just add to the procState priority queue. The adj priority queue should be
@@ -1004,14 +1009,14 @@ public class OomAdjusterImpl extends OomAdjuster {
     * {@code connectionConsumer}.
     */
    @GuardedBy({"mService", "mProcLock"})
    private static void forEachConnectionLSP(ProcessRecord app,
            BiConsumer<Connection, ProcessRecord> connectionConsumer) {
        final ProcessServiceRecord psr = app.mServices;
    private static void forEachConnectionLSP(ProcessRecordInternal app,
            BiConsumer<Connection, ProcessRecordInternal> connectionConsumer) {
        final ProcessServiceRecordInternal psr =  app.getServices();
        for (int i = psr.numberOfConnections() - 1; i >= 0; i--) {
            ConnectionRecord cr = psr.getConnectionAt(i);
            ProcessRecord service = cr.hasFlag(ServiceInfo.FLAG_ISOLATED_PROCESS)
                    ? cr.binding.service.getIsolationHostProcess()
                    : cr.binding.service.getHostProcess();
            ConnectionRecordInternal cr = psr.getConnectionAt(i);
            ProcessRecordInternal service = cr.hasFlag(ServiceInfo.FLAG_ISOLATED_PROCESS)
                    ? cr.getService().getIsolationHostProcess()
                    : cr.getService().getHostProcess();
            if (service == null || service == app || isSandboxAttributedConnection(cr, service)) {
                continue;
            }
@@ -1024,8 +1029,8 @@ public class OomAdjusterImpl extends OomAdjuster {
        }

        for (int i = psr.numberOfSdkSandboxConnections() - 1; i >= 0; i--) {
            final ConnectionRecord cr = psr.getSdkSandboxConnectionAt(i);
            final ProcessRecord service = cr.binding.service.getHostProcess();
            final ConnectionRecordInternal cr = psr.getSdkSandboxConnectionAt(i);
            final ProcessRecordInternal service = cr.getService().getHostProcess();
            if (service == null || service == app) {
                continue;
            }
@@ -1035,10 +1040,10 @@ public class OomAdjusterImpl extends OomAdjuster {
            connectionConsumer.accept(cr, service);
        }

        final ProcessProviderRecord ppr = app.getProviders();
        final ProcessProviderRecordInternal ppr = app.getProviders();
        for (int i = ppr.numberOfProviderConnections() - 1; i >= 0; i--) {
            ContentProviderConnection cpc = ppr.getProviderConnectionAt(i);
            ProcessRecord provider = cpc.provider.getHostProcess();
            ContentProviderConnectionInternal cpc = ppr.getProviderConnectionAt(i);
            ProcessRecordInternal provider = cpc.getProvider().getHostProcess();
            if (provider == null || provider == app || isHighPriorityProcess(provider)) {
                continue;
            }
@@ -1052,7 +1057,7 @@ public class OomAdjusterImpl extends OomAdjuster {
     * but the host process has not set the corresponding flag,
     * {@link ProcessRecordInternal#mScheduleLikeTopApp}.
     */
    private static boolean allowSkipForBindScheduleLikeTopApp(ConnectionRecord cr,
    private static boolean allowSkipForBindScheduleLikeTopApp(ConnectionRecordInternal cr,
            ProcessRecordInternal host) {
        // If feature flag for optionally blocking skipping is disabled. Always allow skipping.
        if (!Flags.notSkipConnectionRecomputeForBindScheduleLikeTopApp()) {
@@ -1064,9 +1069,9 @@ public class OomAdjusterImpl extends OomAdjuster {
        return !(cr.hasFlag(Context.BIND_SCHEDULE_LIKE_TOP_APP) && !host.getScheduleLikeTopApp());
    }

    private static boolean isSandboxAttributedConnection(ConnectionRecord cr,
    private static boolean isSandboxAttributedConnection(ConnectionRecordInternal cr,
            ProcessRecordInternal host) {
        return host.isSdkSandbox && cr.binding.attributedClient != null;
        return host.isSdkSandbox && cr.getAttributedClient() != null;
    }

    private static boolean isHighPriorityProcess(ProcessRecordInternal proc) {
+0 −2
Original line number Diff line number Diff line
@@ -95,7 +95,6 @@ class ProcessRecord extends ProcessRecordInternal implements WindowProcessListen
    volatile ApplicationInfo info; // all about the first app in the process
    final ProcessInfo processInfo; // if non-null, process-specific manifest info
    final boolean appZygote;    // true if this is forked from the app zygote
    final int userId;           // user of process.
    final String processName;   // name of the process
    final String sdkSandboxClientAppPackage; // if this is an sdk sandbox process, name of the
                                             // app package for which it is running
@@ -593,7 +592,6 @@ class ProcessRecord extends ProcessRecordInternal implements WindowProcessListen
        processInfo = procInfo;
        appZygote = (UserHandle.getAppId(_uid) >= Process.FIRST_APP_ZYGOTE_ISOLATED_UID
                && UserHandle.getAppId(_uid) <= Process.LAST_APP_ZYGOTE_ISOLATED_UID);
        userId = UserHandle.getUserId(_uid);
        processName = _processName;
        sdkSandboxClientAppPackage = _sdkSandboxClientAppPackage;
        if (isSdkSandbox) {
+2 −4
Original line number Diff line number Diff line
@@ -154,10 +154,8 @@ final class ProcessServiceRecord extends ProcessServiceRecordInternal {
        }
    }

    /**
     * @return true if this process has any foreground services (even timed-out short-FGS)
     */
    boolean hasForegroundServices() {
    @Override
    public boolean hasForegroundServices() {
        return mHasForegroundServices;
    }

+7 −0
Original line number Diff line number Diff line
@@ -36,6 +36,7 @@ import android.app.ActivityManager;
import android.os.Process;
import android.os.SystemClock;
import android.os.Trace;
import android.os.UserHandle;
import android.util.TimeUtils;

import com.android.internal.annotations.CompositeRWLock;
@@ -235,6 +236,11 @@ public abstract class ProcessRecordInternal {
     * This may differ from {@link #getApplicationUid()} if it's an isolated process.
     */
    public final int uid;
    /**
     * The user ID of the process.
     * This is derived from {@link #uid} using {@link android.os.UserHandle#getUserId(int)}.
     */
    public final int userId;
    public final boolean isolated;     // true if this is a special isolated process
    public final boolean isSdkSandbox; // true if this is an SDK sandbox process

@@ -678,6 +684,7 @@ public abstract class ProcessRecordInternal {
    public ProcessRecordInternal(String processName, int uid, Object serviceLock, Object procLock) {
        mProcessName = processName;
        this.uid = uid;
        userId = UserHandle.getUserId(uid);
        isSdkSandbox = Process.isSdkSandboxUid(this.uid);
        isolated = Process.isIsolatedUid(this.uid);
        mServiceLock = serviceLock;
Loading