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

Commit 42001174 authored by Harshit Mahajan's avatar Harshit Mahajan Committed by Android (Google) Code Review
Browse files

Merge "Make mLock static for accessibility" into main

parents ea290f88 ba000ae7
Loading
Loading
Loading
Loading
+72 −72
Original line number Diff line number Diff line
@@ -218,7 +218,7 @@ public class PackageWatchdog {
    @GuardedBy("sPackageWatchdogLock")
    private static PackageWatchdog sPackageWatchdog;

    private final Object mLock = new Object();
    private static final Object sLock = new Object();
    // System server context
    private final Context mContext;
    // Handler to run short running tasks
@@ -228,7 +228,7 @@ public class PackageWatchdog {
    // Contains (observer-name -> observer-handle) that have ever been registered from
    // previous boots. Observers with all packages expired are periodically pruned.
    // It is saved to disk on system shutdown and repouplated on startup so it survives reboots.
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private final ArrayMap<String, ObserverInternal> mAllObservers = new ArrayMap<>();
    // File containing the XML data of monitored packages /data/system/package-watchdog.xml
    private final AtomicFile mPolicyFile;
@@ -244,26 +244,26 @@ public class PackageWatchdog {
    private final Set<String> mPackagesExemptFromImpactLevelThreshold = new ArraySet<>();

    // The set of packages that have been synced with the ExplicitHealthCheckController
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private Set<String> mRequestedHealthCheckPackages = new ArraySet<>();
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private boolean mIsPackagesReady;
    // Flag to control whether explicit health checks are supported or not
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private boolean mIsHealthCheckEnabled = DEFAULT_EXPLICIT_HEALTH_CHECK_ENABLED;
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private int mTriggerFailureDurationMs = DEFAULT_TRIGGER_FAILURE_DURATION_MS;
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private int mTriggerFailureCount = DEFAULT_TRIGGER_FAILURE_COUNT;
    // SystemClock#uptimeMillis when we last executed #syncState
    // 0 if no prune is scheduled.
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private long mUptimeAtLastStateSync;
    // If true, sync explicit health check packages with the ExplicitHealthCheckController.
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private boolean mSyncRequired = false;

    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private long mLastMitigation = -1000000;

    @FunctionalInterface
@@ -323,7 +323,7 @@ public class PackageWatchdog {
     * @hide
     */
    public void onPackagesReady() {
        synchronized (mLock) {
        synchronized (sLock) {
            mIsPackagesReady = true;
            mHealthCheckController.setCallbacks(packageName -> onHealthCheckPassed(packageName),
                    packages -> onSupportedPackages(packages),
@@ -342,7 +342,7 @@ public class PackageWatchdog {
     * @hide
     */
    public void registerHealthObserver(PackageHealthObserver observer) {
        synchronized (mLock) {
        synchronized (sLock) {
            ObserverInternal internalObserver = mAllObservers.get(observer.getUniqueIdentifier());
            if (internalObserver != null) {
                internalObserver.registeredObserver = observer;
@@ -409,7 +409,7 @@ public class PackageWatchdog {
        mLongTaskHandler.post(() -> {
            syncState("observing new packages");

            synchronized (mLock) {
            synchronized (sLock) {
                ObserverInternal oldObserver = mAllObservers.get(observer.getUniqueIdentifier());
                if (oldObserver == null) {
                    Slog.d(TAG, observer.getUniqueIdentifier() + " started monitoring health "
@@ -441,7 +441,7 @@ public class PackageWatchdog {
     */
    public void unregisterHealthObserver(PackageHealthObserver observer) {
        mLongTaskHandler.post(() -> {
            synchronized (mLock) {
            synchronized (sLock) {
                mAllObservers.remove(observer.getUniqueIdentifier());
            }
            syncState("unregistering observer: " + observer.getUniqueIdentifier());
@@ -462,7 +462,7 @@ public class PackageWatchdog {
            Slog.w(TAG, "Could not resolve a list of failing packages");
            return;
        }
        synchronized (mLock) {
        synchronized (sLock) {
            final long now = mSystemClock.uptimeMillis();
            if (Flags.recoverabilityDetection()) {
                if (now >= mLastMitigation
@@ -473,7 +473,7 @@ public class PackageWatchdog {
            }
        }
        mLongTaskHandler.post(() -> {
            synchronized (mLock) {
            synchronized (sLock) {
                if (mAllObservers.isEmpty()) {
                    return;
                }
@@ -573,7 +573,7 @@ public class PackageWatchdog {
                              int currentObserverImpact,
                              int mitigationCount) {
        if (allowMitigations(currentObserverImpact, versionedPackage)) {
            synchronized (mLock) {
            synchronized (sLock) {
                mLastMitigation = mSystemClock.uptimeMillis();
            }
            currentObserverToNotify.onExecuteHealthCheckMitigation(versionedPackage, failureReason,
@@ -603,7 +603,7 @@ public class PackageWatchdog {
     */
    @SuppressWarnings("GuardedBy")
    public void noteBoot() {
        synchronized (mLock) {
        synchronized (sLock) {
            // if boot count has reached threshold, start mitigation.
            // We wait until threshold number of restarts only for the first time. Perform
            // mitigations for every restart after that.
@@ -656,7 +656,7 @@ public class PackageWatchdog {
    // This currently adds about 7ms extra to shutdown thread
    /** @hide Writes the package information to file during shutdown. */
    public void writeNow() {
        synchronized (mLock) {
        synchronized (sLock) {
            // Must only run synchronous tasks as this runs on the ShutdownThread and no other
            // thread is guaranteed to run during shutdown.
            if (!mAllObservers.isEmpty()) {
@@ -675,7 +675,7 @@ public class PackageWatchdog {
     * passed and the health check service is stopped.
     */
    private void setExplicitHealthCheckEnabled(boolean enabled) {
        synchronized (mLock) {
        synchronized (sLock) {
            mIsHealthCheckEnabled = enabled;
            mHealthCheckController.setEnabled(enabled);
            mSyncRequired = true;
@@ -860,14 +860,14 @@ public class PackageWatchdog {

    @VisibleForTesting
    long getTriggerFailureCount() {
        synchronized (mLock) {
        synchronized (sLock) {
            return mTriggerFailureCount;
        }
    }

    @VisibleForTesting
    long getTriggerFailureDurationMs() {
        synchronized (mLock) {
        synchronized (sLock) {
            return mTriggerFailureDurationMs;
        }
    }
@@ -888,7 +888,7 @@ public class PackageWatchdog {
     */
    private void syncRequests() {
        boolean syncRequired = false;
        synchronized (mLock) {
        synchronized (sLock) {
            if (mIsPackagesReady) {
                Set<String> packages = getPackagesPendingHealthChecksLocked();
                if (mSyncRequired || !packages.equals(mRequestedHealthCheckPackages)
@@ -925,7 +925,7 @@ public class PackageWatchdog {
        Slog.i(TAG, "Health check passed for package: " + packageName);
        boolean isStateChanged = false;

        synchronized (mLock) {
        synchronized (sLock) {
            for (int observerIdx = 0; observerIdx < mAllObservers.size(); observerIdx++) {
                ObserverInternal observer = mAllObservers.valueAt(observerIdx);
                MonitoredPackage monitoredPackage = observer.getMonitoredPackage(packageName);
@@ -953,7 +953,7 @@ public class PackageWatchdog {
            supportedPackageTimeouts.put(info.getPackageName(), info.getHealthCheckTimeoutMillis());
        }

        synchronized (mLock) {
        synchronized (sLock) {
            Slog.d(TAG, "Received supported packages " + supportedPackages);
            Iterator<ObserverInternal> oit = mAllObservers.values().iterator();
            while (oit.hasNext()) {
@@ -984,13 +984,13 @@ public class PackageWatchdog {
    }

    private void onSyncRequestNotified() {
        synchronized (mLock) {
        synchronized (sLock) {
            mSyncRequired = true;
            syncRequestsAsync();
        }
    }

    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private Set<String> getPackagesPendingHealthChecksLocked() {
        Set<String> packages = new ArraySet<>();
        Iterator<ObserverInternal> oit = mAllObservers.values().iterator();
@@ -1016,7 +1016,7 @@ public class PackageWatchdog {
     * health check service and schedules the next state sync.
     */
    private void syncState(String reason) {
        synchronized (mLock) {
        synchronized (sLock) {
            Slog.i(TAG, "Syncing state, reason: " + reason);
            pruneObserversLocked();

@@ -1032,7 +1032,7 @@ public class PackageWatchdog {
        syncState("scheduled");
    }

    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private void scheduleNextSyncStateLocked() {
        long durationMs = getNextStateSyncMillisLocked();
        mShortTaskHandler.removeCallbacks(mSyncStateWithScheduledReason);
@@ -1050,7 +1050,7 @@ public class PackageWatchdog {
     *
     * @returns Long#MAX_VALUE if there are no observed packages.
     */
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private long getNextStateSyncMillisLocked() {
        long shortestDurationMs = Long.MAX_VALUE;
        for (int oIndex = 0; oIndex < mAllObservers.size(); oIndex++) {
@@ -1071,7 +1071,7 @@ public class PackageWatchdog {
     * Removes {@code elapsedMs} milliseconds from all durations on monitored packages
     * and updates other internal state.
     */
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    private void pruneObserversLocked() {
        long elapsedMs = mUptimeAtLastStateSync == 0
                ? 0 : mSystemClock.uptimeMillis() - mUptimeAtLastStateSync;
@@ -1099,7 +1099,7 @@ public class PackageWatchdog {
    private void onHealthCheckFailed(ObserverInternal observer,
            Set<MonitoredPackage> failedPackages) {
        mLongTaskHandler.post(() -> {
            synchronized (mLock) {
            synchronized (sLock) {
                PackageHealthObserver registeredObserver = observer.registeredObserver;
                if (registeredObserver != null) {
                    Iterator<MonitoredPackage> it = failedPackages.iterator();
@@ -1208,7 +1208,7 @@ public class PackageWatchdog {
     */
    @VisibleForTesting
    void updateConfigs() {
        synchronized (mLock) {
        synchronized (sLock) {
            mTriggerFailureCount = DeviceConfig.getInt(
                    DeviceConfig.NAMESPACE_ROLLBACK,
                    PROPERTY_WATCHDOG_TRIGGER_FAILURE_COUNT,
@@ -1237,7 +1237,7 @@ public class PackageWatchdog {
     */
    private boolean saveToFile() {
        Slog.i(TAG, "Saving observer state to file");
        synchronized (mLock) {
        synchronized (sLock) {
            FileOutputStream stream;
            try {
                stream = mPolicyFile.startWrite();
@@ -1307,7 +1307,7 @@ public class PackageWatchdog {
        if (Flags.synchronousRebootInRescueParty() && RescueParty.isRecoveryTriggeredReboot()) {
            dumpInternal(pw);
        } else {
            synchronized (mLock) {
            synchronized (sLock) {
                dumpInternal(pw);
            }
        }
@@ -1317,7 +1317,7 @@ public class PackageWatchdog {
        IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
        ipw.println("Package Watchdog status");
        ipw.increaseIndent();
        synchronized (mLock) {
        synchronized (sLock) {
            for (String observerName : mAllObservers.keySet()) {
                ipw.println("Observer name: " + observerName);
                ipw.increaseIndent();
@@ -1331,7 +1331,7 @@ public class PackageWatchdog {
    }

    @VisibleForTesting
    @GuardedBy("mLock")
    @GuardedBy("sLock")
    void registerObserverInternal(ObserverInternal observerInternal) {
        mAllObservers.put(observerInternal.name, observerInternal);
    }
@@ -1340,15 +1340,15 @@ public class PackageWatchdog {
     * Represents an observer monitoring a set of packages along with the failure thresholds for
     * each package.
     *
     * <p> Note, the PackageWatchdog#mLock must always be held when reading or writing
     * <p> Note, the PackageWatchdog#sLock must always be held when reading or writing
     * instances of this class.
     */
    static class ObserverInternal {
        public final String name;
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private final ArrayMap<String, MonitoredPackage> mPackages = new ArrayMap<>();
        @Nullable
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public PackageHealthObserver registeredObserver;
        private int mMitigationCount;

@@ -1366,7 +1366,7 @@ public class PackageWatchdog {
         * Writes important {@link MonitoredPackage} details for this observer to file.
         * Does not persist any package failure thresholds.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public boolean writeLocked(XmlSerializer out) {
            try {
                out.startTag(null, TAG_OBSERVER);
@@ -1394,7 +1394,7 @@ public class PackageWatchdog {
            mMitigationCount = mitigationCount;
        }

        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public void updatePackagesLocked(List<MonitoredPackage> packages) {
            for (int pIndex = 0; pIndex < packages.size(); pIndex++) {
                MonitoredPackage p = packages.get(pIndex);
@@ -1417,7 +1417,7 @@ public class PackageWatchdog {
         * health check passing, or an empty list if no package expired for which an explicit health
         * check was still pending
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private Set<MonitoredPackage> prunePackagesLocked(long elapsedMs) {
            Set<MonitoredPackage> failedPackages = new ArraySet<>();
            Iterator<MonitoredPackage> it = mPackages.values().iterator();
@@ -1442,7 +1442,7 @@ public class PackageWatchdog {
         * @returns {@code true} if failure threshold is exceeded, {@code false} otherwise
         * @hide
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public boolean onPackageFailureLocked(String packageName) {
            if (getMonitoredPackage(packageName) == null && registeredObserver.isPersistent()
                    && registeredObserver.mayObservePackage(packageName)) {
@@ -1461,7 +1461,7 @@ public class PackageWatchdog {
         *
         * @return a mapping of package names to {@link MonitoredPackage} objects.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public ArrayMap<String, MonitoredPackage> getMonitoredPackages() {
            return mPackages;
        }
@@ -1474,7 +1474,7 @@ public class PackageWatchdog {
         * @return the {@link MonitoredPackage} object associated with the package name if one
         *         exists, {@code null} otherwise.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        @Nullable
        public MonitoredPackage getMonitoredPackage(String packageName) {
            return mPackages.get(packageName);
@@ -1485,7 +1485,7 @@ public class PackageWatchdog {
         *
         * @param p: the {@link MonitoredPackage} to store.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public void putMonitoredPackage(MonitoredPackage p) {
            mPackages.put(p.getName(), p);
        }
@@ -1608,17 +1608,17 @@ public class PackageWatchdog {
     * Represents a package and its health check state along with the time
     * it should be monitored for.
     *
     * <p> Note, the PackageWatchdog#mLock must always be held when reading or writing
     * <p> Note, the PackageWatchdog#sLock must always be held when reading or writing
     * instances of this class.
     */
    class MonitoredPackage {
        private final String mPackageName;
        // Times when package failures happen sorted in ascending order
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private final LongArrayQueue mFailureHistory = new LongArrayQueue();
        // Times when an observer was called to mitigate this package's failure. Sorted in
        // ascending order.
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private final LongArrayQueue mMitigationCalls;
        // One of STATE_[ACTIVE|INACTIVE|PASSED|FAILED]. Updated on construction and after
        // methods that could change the health check state: handleElapsedTimeLocked and
@@ -1627,17 +1627,17 @@ public class PackageWatchdog {
        // Whether an explicit health check has passed.
        // This value in addition with mHealthCheckDurationMs determines the health check state
        // of the package, see #getHealthCheckStateLocked
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private boolean mHasPassedHealthCheck;
        // System uptime duration to monitor package.
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private long mDurationMs;
        // System uptime duration to check the result of an explicit health check
        // Initially, MAX_VALUE until we get a value from the health check service
        // and request health checks.
        // This value in addition with mHasPassedHealthCheck determines the health check state
        // of the package, see #getHealthCheckStateLocked
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private long mHealthCheckDurationMs = Long.MAX_VALUE;

        MonitoredPackage(String packageName, long durationMs,
@@ -1654,7 +1654,7 @@ public class PackageWatchdog {
        /** Writes the salient fields to disk using {@code out}.
         * @hide
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public void writeLocked(XmlSerializer out) throws IOException {
            out.startTag(null, TAG_PACKAGE);
            out.attribute(null, ATTR_NAME, getName());
@@ -1672,7 +1672,7 @@ public class PackageWatchdog {
         *
         * @return {@code true} if failure count exceeds a threshold, {@code false} otherwise
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public boolean onFailureLocked() {
            // Sliding window algorithm: find out if there exists a window containing failures >=
            // mTriggerFailureCount.
@@ -1692,7 +1692,7 @@ public class PackageWatchdog {
        /**
         * Notes the timestamp of a mitigation call into the observer.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public void noteMitigationCallLocked() {
            mMitigationCalls.addLast(mSystemClock.uptimeMillis());
        }
@@ -1703,7 +1703,7 @@ public class PackageWatchdog {
         *
         * @return the number of mitigation calls made in the de-escalation window.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public int getMitigationCountLocked() {
            try {
                final long now = mSystemClock.uptimeMillis();
@@ -1723,7 +1723,7 @@ public class PackageWatchdog {
         *
         * @return a LongArrayQueue of the mitigation calls relative to the current system uptime.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public LongArrayQueue normalizeMitigationCalls() {
            LongArrayQueue normalized = new LongArrayQueue();
            final long now = mSystemClock.uptimeMillis();
@@ -1738,7 +1738,7 @@ public class PackageWatchdog {
         *
         * @return the new health check state
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public int setHealthCheckActiveLocked(long initialHealthCheckDurationMs) {
            if (initialHealthCheckDurationMs <= 0) {
                Slog.wtf(TAG, "Cannot set non-positive health check duration "
@@ -1758,7 +1758,7 @@ public class PackageWatchdog {
         *
         * @return the new health check state
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public int handleElapsedTimeLocked(long elapsedMs) {
            if (elapsedMs <= 0) {
                Slog.w(TAG, "Cannot handle non-positive elapsed time for package " + getName());
@@ -1776,7 +1776,7 @@ public class PackageWatchdog {
        }

        /** Explicitly update the monitoring duration of the package. */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public void updateHealthCheckDuration(long newDurationMs) {
            mDurationMs = newDurationMs;
        }
@@ -1787,7 +1787,7 @@ public class PackageWatchdog {
         *
         * @return the new {@link HealthCheckState health check state}
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        @HealthCheckState
        public int tryPassHealthCheckLocked() {
            if (mHealthCheckState != HealthCheckState.FAILED) {
@@ -1806,7 +1806,7 @@ public class PackageWatchdog {
        /**
         * Returns the current {@link HealthCheckState health check state}.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        @HealthCheckState
        public int getHealthCheckStateLocked() {
            return mHealthCheckState;
@@ -1817,7 +1817,7 @@ public class PackageWatchdog {
         *
         * @return the duration or {@link Long#MAX_VALUE} if the package should not be scheduled
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public long getShortestScheduleDurationMsLocked() {
            // Consider health check duration only if #isPendingHealthChecksLocked is true
            return Math.min(toPositive(mDurationMs),
@@ -1829,7 +1829,7 @@ public class PackageWatchdog {
         * Returns {@code true} if the total duration left to monitor the package is less than or
         * equal to 0 {@code false} otherwise.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public boolean isExpiredLocked() {
            return mDurationMs <= 0;
        }
@@ -1838,7 +1838,7 @@ public class PackageWatchdog {
         * Returns {@code true} if the package, {@link #getName} is expecting health check results
         * {@code false} otherwise.
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public boolean isPendingHealthChecksLocked() {
            return mHealthCheckState == HealthCheckState.ACTIVE
                    || mHealthCheckState == HealthCheckState.INACTIVE;
@@ -1850,7 +1850,7 @@ public class PackageWatchdog {
         *
         * @return the new {@link HealthCheckState health check state}
         */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        @HealthCheckState
        private int updateHealthCheckStateLocked() {
            int oldState = mHealthCheckState;
@@ -1905,7 +1905,7 @@ public class PackageWatchdog {
        }
    }

    @GuardedBy("mLock")
    @GuardedBy("sLock")
    @SuppressWarnings("GuardedBy")
    void saveAllObserversBootMitigationCountToMetadata(String filePath) {
        HashMap<String, Integer> bootMitigationCounts = new HashMap<>();
@@ -2008,7 +2008,7 @@ public class PackageWatchdog {


        /** Increments the boot counter, and returns whether the device is bootlooping. */
        @GuardedBy("mLock")
        @GuardedBy("sLock")
        public boolean incrementAndTest() {
            if (Flags.recoverabilityDetection()) {
                readAllObserversBootMitigationCountIfNecessary(METADATA_FILE);
@@ -2049,7 +2049,7 @@ public class PackageWatchdog {
            }
        }

        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private boolean performedMitigationsDuringWindow() {
            for (ObserverInternal observerInternal: mAllObservers.values()) {
                if (observerInternal.getBootMitigationCount() > 0) {
@@ -2059,7 +2059,7 @@ public class PackageWatchdog {
            return false;
        }

        @GuardedBy("mLock")
        @GuardedBy("sLock")
        private void resetAllObserversBootMitigationCount() {
            for (int i = 0; i < mAllObservers.size(); i++) {
                final ObserverInternal observer = mAllObservers.valueAt(i);
@@ -2068,7 +2068,7 @@ public class PackageWatchdog {
            saveAllObserversBootMitigationCountToMetadata(METADATA_FILE);
        }

        @GuardedBy("mLock")
        @GuardedBy("sLock")
        @SuppressWarnings("GuardedBy")
        void readAllObserversBootMitigationCountIfNecessary(String filePath) {
            File metadataFile = new File(filePath);