• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.power;
18 
19 import static android.hardware.display.DisplayManagerInternal.DisplayPowerRequest.policyToString;
20 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
21 import static android.os.PowerManager.GO_TO_SLEEP_REASON_DISPLAY_GROUPS_TURNED_OFF;
22 import static android.os.PowerManager.GO_TO_SLEEP_REASON_DISPLAY_GROUP_REMOVED;
23 import static android.os.PowerManager.WAKE_REASON_DISPLAY_GROUP_ADDED;
24 import static android.os.PowerManager.WAKE_REASON_DISPLAY_GROUP_TURNED_ON;
25 import static android.os.PowerManagerInternal.MODE_DEVICE_IDLE;
26 import static android.os.PowerManagerInternal.MODE_DISPLAY_INACTIVE;
27 import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
28 import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
29 import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
30 import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
31 import static android.os.PowerManagerInternal.isInteractive;
32 import static android.os.PowerManagerInternal.wakefulnessToString;
33 import static android.service.dreams.Flags.allowDreamWhenPostured;
34 
35 import static com.android.internal.util.LatencyTracker.ACTION_TURN_ON_SCREEN;
36 import static com.android.server.deviceidle.Flags.disableWakelocksInLightIdle;
37 import static com.android.server.display.DisplayDeviceConfig.INVALID_BRIGHTNESS_IN_CONFIG;
38 import static com.android.server.display.brightness.BrightnessUtils.isValidBrightnessValue;
39 import static com.android.server.power.ScreenTimeoutOverridePolicy.RELEASE_REASON_UNKNOWN;
40 import static com.android.server.power.ScreenTimeoutOverridePolicy.RELEASE_REASON_WAKE_LOCK_DEATH;
41 
42 import android.annotation.IntDef;
43 import android.annotation.NonNull;
44 import android.annotation.Nullable;
45 import android.annotation.RequiresPermission;
46 import android.annotation.UserIdInt;
47 import android.app.ActivityManager;
48 import android.app.SynchronousUserSwitchObserver;
49 import android.app.compat.CompatChanges;
50 import android.compat.annotation.ChangeId;
51 import android.compat.annotation.EnabledSince;
52 import android.content.AttributionSource;
53 import android.content.BroadcastReceiver;
54 import android.content.ContentResolver;
55 import android.content.Context;
56 import android.content.Intent;
57 import android.content.IntentFilter;
58 import android.content.PermissionChecker;
59 import android.content.pm.PackageManager;
60 import android.content.res.Resources;
61 import android.database.ContentObserver;
62 import android.hardware.SensorManager;
63 import android.hardware.SystemSensorManager;
64 import android.hardware.devicestate.DeviceState;
65 import android.hardware.devicestate.DeviceStateManager;
66 import android.hardware.display.AmbientDisplayConfiguration;
67 import android.hardware.display.DisplayManager;
68 import android.hardware.display.DisplayManagerInternal;
69 import android.hardware.power.Boost;
70 import android.hardware.power.Mode;
71 import android.net.Uri;
72 import android.os.BatteryManager;
73 import android.os.BatteryManagerInternal;
74 import android.os.BatterySaverPolicyConfig;
75 import android.os.Binder;
76 import android.os.Build;
77 import android.os.Handler;
78 import android.os.HandlerExecutor;
79 import android.os.IBinder;
80 import android.os.IPowerManager;
81 import android.os.IScreenTimeoutPolicyListener;
82 import android.os.IWakeLockCallback;
83 import android.os.Looper;
84 import android.os.Message;
85 import android.os.ParcelDuration;
86 import android.os.PowerManager;
87 import android.os.PowerManager.GoToSleepReason;
88 import android.os.PowerManager.ServiceType;
89 import android.os.PowerManager.WakeReason;
90 import android.os.PowerManagerInternal;
91 import android.os.PowerSaveState;
92 import android.os.Process;
93 import android.os.RemoteException;
94 import android.os.ResultReceiver;
95 import android.os.ShellCallback;
96 import android.os.SystemClock;
97 import android.os.SystemProperties;
98 import android.os.Trace;
99 import android.os.UserHandle;
100 import android.os.UserManager;
101 import android.os.WorkSource;
102 import android.os.WorkSource.WorkChain;
103 import android.provider.DeviceConfigInterface;
104 import android.provider.Settings;
105 import android.provider.Settings.SettingNotFoundException;
106 import android.service.dreams.DreamManagerInternal;
107 import android.sysprop.PowerProperties;
108 import android.util.ArrayMap;
109 import android.util.IntArray;
110 import android.util.KeyValueListParser;
111 import android.util.LongArray;
112 import android.util.PrintWriterPrinter;
113 import android.util.Slog;
114 import android.util.SparseArray;
115 import android.util.TimeUtils;
116 import android.util.proto.ProtoOutputStream;
117 import android.view.Display;
118 import android.view.DisplayInfo;
119 import android.view.KeyEvent;
120 
121 import com.android.internal.annotations.GuardedBy;
122 import com.android.internal.annotations.VisibleForTesting;
123 import com.android.internal.app.IBatteryStats;
124 import com.android.internal.display.BrightnessSynchronizer;
125 import com.android.internal.foldables.FoldGracePeriodProvider;
126 import com.android.internal.os.BackgroundThread;
127 import com.android.internal.util.DumpUtils;
128 import com.android.internal.util.FrameworkStatsLog;
129 import com.android.internal.util.LatencyTracker;
130 import com.android.internal.util.Preconditions;
131 import com.android.server.EventLogTags;
132 import com.android.server.LockGuard;
133 import com.android.server.PackageWatchdog;
134 import com.android.server.ServiceThread;
135 import com.android.server.SystemService;
136 import com.android.server.UiThread;
137 import com.android.server.Watchdog;
138 import com.android.server.am.BatteryStatsService;
139 import com.android.server.display.feature.DeviceConfigParameterProvider;
140 import com.android.server.lights.LightsManager;
141 import com.android.server.lights.LogicalLight;
142 import com.android.server.policy.WindowManagerPolicy;
143 import com.android.server.power.AmbientDisplaySuppressionController.AmbientDisplaySuppressionChangedCallback;
144 import com.android.server.power.batterysaver.BatterySaverController;
145 import com.android.server.power.batterysaver.BatterySaverPolicy;
146 import com.android.server.power.batterysaver.BatterySaverStateMachine;
147 import com.android.server.power.batterysaver.BatterySavingStats;
148 import com.android.server.power.feature.PowerManagerFlags;
149 
150 import dalvik.annotation.optimization.NeverCompile;
151 
152 import java.io.FileDescriptor;
153 import java.io.PrintWriter;
154 import java.lang.annotation.Retention;
155 import java.lang.annotation.RetentionPolicy;
156 import java.text.SimpleDateFormat;
157 import java.util.ArrayList;
158 import java.util.Arrays;
159 import java.util.Date;
160 import java.util.List;
161 import java.util.NoSuchElementException;
162 import java.util.Objects;
163 import java.util.concurrent.Executor;
164 
165 /**
166  * The power manager service is responsible for coordinating power management
167  * functions on the device.
168  */
169 public final class PowerManagerService extends SystemService
170         implements Watchdog.Monitor {
171     private static final String TAG = "PowerManagerService";
172 
173     private static final boolean DEBUG = false;
174     private static final boolean DEBUG_SPEW = DEBUG && true;
175 
176     // Message: Sent when a user activity timeout occurs to update the power state.
177     private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
178     // Message: Sent when the device enters or exits a dreaming or dozing state.
179     private static final int MSG_SANDMAN = 2;
180     // Message: Sent when the screen brightness boost expires.
181     private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
182     // Message: Polling to look for long held wake locks.
183     private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
184     // Message: Sent when an attentive timeout occurs to update the power state.
185     private static final int MSG_ATTENTIVE_TIMEOUT = 5;
186 
187     // Message: Sent when the policy want to release all timeout override wake locks.
188     private static final int MSG_RELEASE_ALL_OVERRIDE_WAKE_LOCKS = 6;
189 
190     // Dirty bit: mWakeLocks changed
191     private static final int DIRTY_WAKE_LOCKS = 1 << 0;
192     // Dirty bit: mWakefulness changed
193     private static final int DIRTY_WAKEFULNESS = 1 << 1;
194     // Dirty bit: user activity was poked or may have timed out
195     private static final int DIRTY_USER_ACTIVITY = 1 << 2;
196     // Dirty bit: actual display power state was updated asynchronously
197     private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
198     // Dirty bit: mBootCompleted changed
199     private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
200     // Dirty bit: settings changed
201     private static final int DIRTY_SETTINGS = 1 << 5;
202     // Dirty bit: mIsPowered changed
203     private static final int DIRTY_IS_POWERED = 1 << 6;
204     // Dirty bit: mStayOn changed
205     private static final int DIRTY_STAY_ON = 1 << 7;
206     // Dirty bit: battery state changed
207     private static final int DIRTY_BATTERY_STATE = 1 << 8;
208     // Dirty bit: proximity state changed
209     private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
210     // Dirty bit: dock state changed
211     private static final int DIRTY_DOCK_STATE = 1 << 10;
212     // Dirty bit: brightness boost changed
213     private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
214     // Dirty bit: sQuiescent changed
215     private static final int DIRTY_QUIESCENT = 1 << 12;
216     // Dirty bit: attentive timer may have timed out
217     private static final int DIRTY_ATTENTIVE = 1 << 14;
218     // Dirty bit: display group wakefulness has changed
219     private static final int DIRTY_DISPLAY_GROUP_WAKEFULNESS = 1 << 16;
220     // Dirty bit: device postured state has changed
221     private static final int DIRTY_POSTURED_STATE = 1 << 17;
222 
223     // Summarizes the state of all active wakelocks.
224     static final int WAKE_LOCK_CPU = 1 << 0;
225     static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
226     static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
227     static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
228     static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
229     static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
230     static final int WAKE_LOCK_DOZE = 1 << 6;
231     static final int WAKE_LOCK_DRAW = 1 << 7;
232     static final int WAKE_LOCK_SCREEN_TIMEOUT_OVERRIDE = 1 << 8;
233 
234     // Summarizes the user activity state.
235     static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
236     static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
237     static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
238 
239     // Default timeout in milliseconds.  This is only used until the settings
240     // provider populates the actual default value (R.integer.def_screen_off_timeout).
241     static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
242     private static final int DEFAULT_SLEEP_TIMEOUT = -1;
243 
244     // Screen brightness boost timeout.
245     // Hardcoded for now until we decide what the right policy should be.
246     // This should perhaps be a setting.
247     private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
248 
249     // How long a partial wake lock must be held until we consider it a long wake lock.
250     static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
251 
252     // Default setting for double tap to wake.
253     private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
254 
255     // System property indicating that the screen should remain off until an explicit user action
256     private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
257 
258     // System Property indicating that retail demo mode is currently enabled.
259     private static final String SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED = "sys.retaildemo.enabled";
260 
261     // System property for last reboot reason
262     private static final String SYSTEM_PROPERTY_REBOOT_REASON = "sys.boot.reason";
263 
264     // Possible reasons for shutting down or reboot for use in
265     // SYSTEM_PROPERTY_REBOOT_REASON(sys.boot.reason) which is set by bootstat
266     private static final String REASON_SHUTDOWN = "shutdown";
267     private static final String REASON_REBOOT = "reboot";
268     private static final String REASON_USERREQUESTED = "shutdown,userrequested";
269     private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
270     private static final String REASON_LOW_BATTERY = "shutdown,battery";
271     private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
272 
273     static final String TRACE_SCREEN_ON = "Screen turning on";
274 
275     /** If turning screen on takes more than this long, we show a warning on logcat. */
276     private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
277 
278     /** Constants for {@link #shutdownOrRebootInternal} */
279     @Retention(RetentionPolicy.SOURCE)
280     @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
281     public @interface HaltMode {}
282     private static final int HALT_MODE_SHUTDOWN = 0;
283     private static final int HALT_MODE_REBOOT = 1;
284     private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
285 
286     /**
287      * How stale we'll allow the enhanced discharge prediction values to get before considering them
288      * invalid.
289      */
290     private static final long ENHANCED_DISCHARGE_PREDICTION_TIMEOUT_MS = 30 * 60 * 1000L;
291 
292     /**
293      * The minimum amount of time between sending consequent
294      * {@link PowerManager#ACTION_ENHANCED_DISCHARGE_PREDICTION_CHANGED} broadcasts.
295      */
296     private static final long ENHANCED_DISCHARGE_PREDICTION_BROADCAST_MIN_DELAY_MS = 60 * 1000L;
297 
298     /**
299      * Apps targeting Android V and above need to define
300      * {@link android.Manifest.permission#TURN_SCREEN_ON} in their manifest for
301      * {@link android.os.PowerManager#ACQUIRE_CAUSES_WAKEUP} to have any effect.
302      * Note that most applications should use {@link android.R.attr#turnScreenOn} or
303      * {@link android.app.Activity#setTurnScreenOn(boolean)} instead, as this prevents the
304      * previous foreground app from being resumed first when the screen turns on.
305      */
306     @ChangeId
307     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.CUR_DEVELOPMENT)
308     public static final long REQUIRE_TURN_SCREEN_ON_PERMISSION = 216114297L;
309 
310     /** Reason ID for holding display suspend blocker. */
311     private static final String HOLDING_DISPLAY_SUSPEND_BLOCKER = "holding display";
312 
313     private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd HH:mm:ss.SSS");
314 
315     /** Display group IDs representing only DEFAULT_DISPLAY_GROUP. */
316     private static final IntArray DEFAULT_DISPLAY_GROUP_IDS =
317             IntArray.wrap(new int[]{Display.DEFAULT_DISPLAY_GROUP});
318 
319     private final Context mContext;
320     private final ServiceThread mHandlerThread;
321     private final Handler mHandler;
322     private final FoldGracePeriodProvider mFoldGracePeriodProvider;
323     private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
324     @Nullable
325     private final BatterySaverStateMachine mBatterySaverStateMachine;
326     private final LowPowerStandbyController mLowPowerStandbyController;
327     private final AttentionDetector mAttentionDetector;
328     private final FaceDownDetector mFaceDownDetector;
329     private final ScreenUndimDetector mScreenUndimDetector;
330     private final BinderService mBinderService;
331     private final LocalService mLocalService;
332     private final NativeWrapper mNativeWrapper;
333     private final SystemPropertiesWrapper mSystemProperties;
334     private final Clock mClock;
335     private final Injector mInjector;
336     private final PermissionCheckerWrapper mPermissionCheckerWrapper;
337     private final PowerPropertiesWrapper mPowerPropertiesWrapper;
338     private final DeviceConfigParameterProvider mDeviceConfigProvider;
339     // True if battery saver is supported on this device.
340     private final boolean mBatterySaverSupported;
341 
342     private final PowerManagerFlags mFeatureFlags;
343 
344     private boolean mDisableScreenWakeLocksWhileCached;
345 
346     private LightsManager mLightsManager;
347     private BatteryManagerInternal mBatteryManagerInternal;
348     private DisplayManagerInternal mDisplayManagerInternal;
349     private DisplayManager mDisplayManager;
350     private IBatteryStats mBatteryStats;
351     private WindowManagerPolicy mPolicy;
352     private Notifier mNotifier;
353     private WirelessChargerDetector mWirelessChargerDetector;
354     private SettingsObserver mSettingsObserver;
355     private DreamManagerInternal mDreamManager;
356     private LogicalLight mAttentionLight;
357 
358     private final InattentiveSleepWarningController mInattentiveSleepWarningOverlayController;
359     private final AmbientDisplaySuppressionController mAmbientDisplaySuppressionController;
360 
361     private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
362 
363     // A bitfield that indicates what parts of the power state have
364     // changed and need to be recalculated.
365     private int mDirty;
366 
367     // Indicates whether the device is awake or asleep or somewhere in between.
368     // This is distinct from the screen power state, which is managed separately.
369     // Do not access directly; always use {@link #setWakefulness} and {@link getWakefulness}.
370     private int mWakefulnessRaw;
371     private boolean mWakefulnessChanging;
372 
373     // True if MSG_SANDMAN has been scheduled.
374     private boolean mSandmanScheduled;
375 
376     // Table of all suspend blockers.
377     // There should only be a few of these.
378     private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<>();
379 
380     // Table of all wake locks acquired by applications.
381     private final ArrayList<WakeLock> mWakeLocks = new ArrayList<>();
382 
383     // A bitfield that summarizes the state of all active wakelocks.
384     private int mWakeLockSummary;
385 
386     // Have we scheduled a message to check for long wake locks?  This is when we will check.
387     private long mNotifyLongScheduled;
388 
389     // Last time we checked for long wake locks.
390     private long mNotifyLongDispatched;
391 
392     // The time we decided to do next long check.
393     private long mNotifyLongNextCheck;
394 
395     // If true, instructs the display controller to wait for the proximity sensor to
396     // go negative before turning the screen on.
397     private boolean mRequestWaitForNegativeProximity;
398 
399     // Timestamp of the last time the device was awoken or put to sleep.
400     private long mLastGlobalWakeTime;
401     private long mLastGlobalSleepTime;
402 
403     // Timestamp (in the elapsed realtime timebase) of the last time was awoken or put to sleep.
404     private long mLastGlobalWakeTimeRealtime;
405     private long mLastGlobalSleepTimeRealtime;
406 
407     // Last reason the device went to sleep.
408     private @WakeReason int mLastGlobalWakeReason;
409     private @GoToSleepReason int mLastGlobalSleepReason;
410 
411     // Timestamp of last time power boost interaction was sent.
412     private long mLastInteractivePowerHintTime;
413 
414     // Timestamp of the last screen brightness boost.
415     private long mLastScreenBrightnessBoostTime;
416     private boolean mScreenBrightnessBoostInProgress;
417 
418     private final PowerGroupWakefulnessChangeListener mPowerGroupWakefulnessChangeListener;
419 
420     // The suspend blocker used to keep the CPU alive while the device is booting.
421     private final SuspendBlocker mBootingSuspendBlocker;
422 
423     // True if the wake lock suspend blocker has been acquired.
424     private boolean mHoldingBootingSuspendBlocker;
425 
426     // The suspend blocker used to keep the CPU alive when an application has acquired
427     // a wake lock.
428     private final SuspendBlocker mWakeLockSuspendBlocker;
429 
430     // True if the wake lock suspend blocker has been acquired.
431     private boolean mHoldingWakeLockSuspendBlocker;
432 
433     // The suspend blocker used to keep the CPU alive when the display is on, the
434     // display is getting ready or there is user activity (in which case the display
435     // must be on).
436     private final SuspendBlocker mDisplaySuspendBlocker;
437 
438     // True if the display suspend blocker has been acquired.
439     private boolean mHoldingDisplaySuspendBlocker;
440 
441     // True if systemReady() has been called.
442     private boolean mSystemReady;
443 
444     // True if boot completed occurred. We keep the screen on until this happens.
445     // The screen will be off if we are in quiescent mode.
446     private boolean mBootCompleted;
447 
448     // True if auto-suspend mode is enabled.
449     // Refer to autosuspend.h.
450     private boolean mHalAutoSuspendModeEnabled;
451 
452     // True if the device uses auto-suspend mode.
453     private final boolean mUseAutoSuspend;
454 
455     // True if interactive mode is enabled.
456     // Refer to power.h.
457     private boolean mHalInteractiveModeEnabled;
458 
459     // True if the device is plugged into a power source.
460     private boolean mIsPowered;
461 
462     // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
463     private int mPlugType;
464 
465     // The current battery level percentage.
466     private int mBatteryLevel;
467 
468     // The amount of battery drained while the device has been in a dream state.
469     private int mDreamsBatteryLevelDrain;
470 
471     // True if updatePowerStateLocked() is already in progress.
472     // TODO(b/215518989): Remove this once transactions are in place
473     private boolean mUpdatePowerStateInProgress;
474 
475     /**
476      * The lock that should be held when interacting with {@link #mEnhancedDischargeTimeElapsed},
477      * {@link #mLastEnhancedDischargeTimeUpdatedElapsed}, and
478      * {@link #mEnhancedDischargePredictionIsPersonalized}.
479      */
480     private final Object mEnhancedDischargeTimeLock = new Object();
481 
482     /**
483      * The time (in the elapsed realtime timebase) at which the battery level will reach 0%. This
484      * is provided as an enhanced estimate and only valid if
485      * {@link #mLastEnhancedDischargeTimeUpdatedElapsed} is greater than 0.
486      */
487     @GuardedBy("mEnhancedDischargeTimeLock")
488     private long mEnhancedDischargeTimeElapsed;
489 
490     /**
491      * Timestamp (in the elapsed realtime timebase) of last update to enhanced battery estimate
492      * data.
493      */
494     @GuardedBy("mEnhancedDischargeTimeLock")
495     private long mLastEnhancedDischargeTimeUpdatedElapsed;
496 
497     /**
498      * Whether or not the current enhanced discharge prediction is personalized to the user.
499      */
500     @GuardedBy("mEnhancedDischargeTimeLock")
501     private boolean mEnhancedDischargePredictionIsPersonalized;
502 
503     // The current dock state.
504     private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
505 
506     /**
507      * Whether the device is upright and stationary.
508      */
509     private boolean mDevicePostured;
510 
511     // True to decouple auto-suspend mode from the display state.
512     private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
513 
514     // True to decouple interactive mode from the display state.
515     private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
516 
517     // True if the device should wake up when plugged or unplugged.
518     private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
519 
520     // True if the device should wake up when plugged or unplugged in theater mode.
521     private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
522 
523     // True if the device should suspend when the screen is off due to proximity.
524     private boolean mSuspendWhenScreenOffDueToProximityConfig;
525 
526     // Default value for attentive timeout.
527     private int mAttentiveTimeoutConfig;
528 
529     // True if dreams are supported on this device.
530     private boolean mDreamsSupportedConfig;
531 
532     // Default value for dreams enabled
533     private boolean mDreamsEnabledByDefaultConfig;
534 
535     // Default value for dreams activate-on-sleep
536     private boolean mDreamsActivatedOnSleepByDefaultConfig;
537 
538     // Default value for dreams activate-on-dock
539     private boolean mDreamsActivatedOnDockByDefaultConfig;
540 
541     /** Default value for whether dreams are activated when postured (stationary + upright) */
542     private boolean mDreamsActivatedWhilePosturedByDefaultConfig;
543 
544     // True if dreams can run while not plugged in.
545     private boolean mDreamsEnabledOnBatteryConfig;
546 
547     // Minimum battery level to allow dreaming when powered.
548     // Use -1 to disable this safety feature.
549     private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
550 
551     // Minimum battery level to allow dreaming when not powered.
552     // Use -1 to disable this safety feature.
553     private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
554 
555     // If the battery level drops by this percentage and the user activity timeout
556     // has expired, then assume the device is receiving insufficient current to charge
557     // effectively and terminate the dream.  Use -1 to disable this safety feature.
558     private int mDreamsBatteryLevelDrainCutoffConfig;
559 
560     // Whether dreams should be disabled when ambient mode is suppressed.
561     private boolean mDreamsDisabledByAmbientModeSuppressionConfig;
562 
563     // True if dreams are enabled by the user.
564     private boolean mDreamsEnabledSetting;
565 
566     // True if dreams should be activated on sleep.
567     private boolean mDreamsActivateOnSleepSetting;
568 
569     // True if dreams should be activated on dock.
570     private boolean mDreamsActivateOnDockSetting;
571 
572     /** Whether dreams should be activated when device is postured (stationary and upright) */
573     private boolean mDreamsActivateWhilePosturedSetting;
574 
575     // True if doze should not be started until after the screen off transition.
576     private boolean mDozeAfterScreenOff;
577 
578     // True if bright policy should be applied when we have entered dozing wakefulness but haven't
579     // started doze component.
580     private boolean mBrightWhenDozingConfig;
581 
582     // The minimum screen off timeout, in milliseconds.
583     private long mMinimumScreenOffTimeoutConfig;
584 
585     // The screen dim duration, in milliseconds.
586     // This is subtracted from the end of the screen off timeout so the
587     // minimum screen off timeout should be longer than this.
588     private long mMaximumScreenDimDurationConfig;
589 
590     // The maximum screen dim time expressed as a ratio relative to the screen
591     // off timeout.  If the screen off timeout is very short then we want the
592     // dim timeout to also be quite short so that most of the time is spent on.
593     // Otherwise the user won't get much screen on time before dimming occurs.
594     private float mMaximumScreenDimRatioConfig;
595 
596     // Whether device supports double tap to wake.
597     private boolean mSupportsDoubleTapWakeConfig;
598 
599     // The screen off timeout setting value in milliseconds.
600     private long mScreenOffTimeoutSetting;
601 
602     // Default for attentive warning duration.
603     private long mAttentiveWarningDurationConfig;
604 
605     // The sleep timeout setting value in milliseconds.
606     private long mSleepTimeoutSetting;
607 
608     // How long to show a warning message to user before the device goes to sleep
609     // after long user inactivity, even if wakelocks are held.
610     private long mAttentiveTimeoutSetting;
611 
612     // The maximum allowable screen off timeout according to the device
613     // administration policy.  Overrides other settings.
614     private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
615 
616     // The stay on while plugged in setting.
617     // A bitfield of battery conditions under which to make the screen stay on.
618     private int mStayOnWhilePluggedInSetting;
619 
620     // True if the device should stay on.
621     private boolean mStayOn;
622 
623     // True if the lights should stay off until an explicit user action.
624     private static boolean sQuiescent;
625 
626     // True if the proximity sensor reads a positive result.
627     private boolean mProximityPositive;
628 
629     // Indicates that we have already intercepted the power key to temporarily ignore the proximity
630     // wake lock and turn the screen back on. This should get reset when prox reads 'far' again
631     // (when {@link #mProximityPositive} is set to false).
632     private boolean mInterceptedPowerKeyForProximity;
633 
634     // Screen brightness setting limits.
635     public final float mScreenBrightnessMinimum;
636     public final float mScreenBrightnessMaximum;
637     public final float mScreenBrightnessDefault;
638     public final float mScreenBrightnessDim;
639 
640     // Value we store for tracking face down behavior.
641     @VisibleForTesting
642     boolean mIsFaceDown = false;
643     private long mLastFlipTime = 0L;
644 
645     // The window manager has determined the user to be inactive via other means.
646     // Set this to false to disable.
647     private boolean mUserInactiveOverrideFromWindowManager;
648 
649     // The next possible user activity timeout after being explicitly told the user is inactive.
650     // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
651     private long mOverriddenTimeout = -1;
652 
653     // The user activity timeout override from the window manager
654     // to allow the current foreground activity to override the user activity timeout.
655     // Use -1 to disable.
656     private long mUserActivityTimeoutOverrideFromWindowManager = -1;
657 
658     // The screen state to use while dozing.
659     private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
660 
661     private int mDozeScreenStateOverrideReasonFromDreamManager = Display.STATE_REASON_UNKNOWN;
662 
663     // The screen brightness between 1 and 255 to use while dozing.
664     private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
665 
666     /**
667      * The screen brightness between {@link PowerManager#BRIGHTNESS_MIN} and
668      * {@link PowerManager.BRIGHTNESS_MAX} to use while dozing.
669      */
670     private float mDozeScreenBrightnessOverrideFromDreamManagerFloat =
671             PowerManager.BRIGHTNESS_INVALID_FLOAT;
672     private boolean mUseNormalBrightnessForDoze;
673 
674     // Keep display state when dozing.
675     private boolean mDrawWakeLockOverrideFromSidekick;
676 
677     // Time when we last logged a warning about calling userActivity() without permission.
678     private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
679 
680     // True if the battery level is currently considered low.
681     private boolean mBatteryLevelLow;
682 
683     // True if we are currently in device idle mode.
684     @GuardedBy("mLock")
685     private boolean mDeviceIdleMode;
686 
687     // True if we are currently in light device idle mode.
688     @GuardedBy("mLock")
689     private boolean mLightDeviceIdleMode;
690 
691     // Set of app ids that we will respect the wake locks for while in device idle mode.
692     int[] mDeviceIdleWhitelist = new int[0];
693 
694     // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
695     int[] mDeviceIdleTempWhitelist = new int[0];
696 
697     // Set of uids that are allowed to acquire wakelocks while low power standby is active
698     int[] mLowPowerStandbyAllowlist = new int[0];
699 
700     private boolean mLowPowerStandbyActive;
701 
702     private final SparseArray<UidState> mUidState = new SparseArray<>();
703 
704     // A mapping from DisplayGroup Id to PowerGroup. There is a 1-1 mapping between DisplayGroups
705     // and PowerGroups. For simplicity the same ids are being used.
706     @GuardedBy("mLock")
707     private final SparseArray<PowerGroup> mPowerGroups = new SparseArray<>();
708 
709     // We are currently in the middle of a batch change of uids.
710     private boolean mUidsChanging;
711 
712     // Some uids have actually changed while mUidsChanging was true.
713     private boolean mUidsChanged;
714 
715     // True if theater mode is enabled
716     private boolean mTheaterModeEnabled;
717 
718     // True if always on display is enabled
719     private boolean mAlwaysOnEnabled;
720 
721     // True if double tap to wake is enabled
722     private boolean mDoubleTapWakeEnabled;
723 
724     // True if we in the process of performing a forceSuspend
725     private boolean mForceSuspendActive;
726 
727     // Transition to Doze is in progress.  We have transitioned to WAKEFULNESS_DOZING,
728     // but the DreamService has not yet been told to start (it's an async process).
729     private boolean mDozeStartInProgress;
730 
731     // Whether to keep dreaming when the device is unplugging.
732     private boolean mKeepDreamingWhenUnplugging;
733 
734     @GuardedBy("mLock")
735     private ScreenTimeoutOverridePolicy mScreenTimeoutOverridePolicy;
736 
737     private final class DreamManagerStateListener implements
738             DreamManagerInternal.DreamManagerStateListener {
739         @Override
onKeepDreamingWhenUnpluggingChanged(boolean keepDreaming)740         public void onKeepDreamingWhenUnpluggingChanged(boolean keepDreaming) {
741             synchronized (mLock) {
742                 mKeepDreamingWhenUnplugging = keepDreaming;
743             }
744         }
745     }
746 
747     private final class PowerGroupWakefulnessChangeListener implements
748             PowerGroup.PowerGroupListener {
749         @GuardedBy("mLock")
750         @Override
onWakefulnessChangedLocked(int groupId, int wakefulness, long eventTime, int reason, int uid, int opUid, String opPackageName, String details)751         public void onWakefulnessChangedLocked(int groupId, int wakefulness, long eventTime,
752                 int reason, int uid, int opUid, String opPackageName, String details) {
753             mWakefulnessChanging = true;
754             mDirty |= DIRTY_WAKEFULNESS;
755             mInjector.invalidateIsInteractiveCaches();
756             if (wakefulness == WAKEFULNESS_AWAKE) {
757                 // Kick user activity to prevent newly awake group from timing out instantly.
758                 // The dream may end without user activity if the dream app crashes / is updated,
759                 // don't poke the user activity timer for these wakes.
760                 int flags = reason == PowerManager.WAKE_REASON_DREAM_FINISHED
761                         ? PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0;
762                 userActivityNoUpdateLocked(mPowerGroups.get(groupId), eventTime,
763                         PowerManager.USER_ACTIVITY_EVENT_OTHER, flags, uid);
764             }
765 
766             // Release wake lock when default display is not interactive.
767             if (mScreenTimeoutOverridePolicy != null && groupId == Display.DEFAULT_DISPLAY_GROUP) {
768                 mScreenTimeoutOverridePolicy.onWakefulnessChange(mWakeLockSummary, wakefulness);
769             }
770 
771             mDirty |= DIRTY_DISPLAY_GROUP_WAKEFULNESS;
772             mNotifier.onGroupWakefulnessChangeStarted(groupId, wakefulness, reason, eventTime);
773             updateGlobalWakefulnessLocked(eventTime, reason, uid, opUid, opPackageName, details);
774             updatePowerStateLocked();
775         }
776     }
777 
778     private final class DisplayListener implements DisplayManager.DisplayListener {
779 
780         @Override
onDisplayAdded(int displayId)781         public void onDisplayAdded(int displayId) {
782 
783         }
784 
785         @Override
onDisplayRemoved(int displayId)786         public void onDisplayRemoved(int displayId) {
787             mNotifier.clearScreenTimeoutPolicyListeners(displayId);
788         }
789 
790         @Override
onDisplayChanged(int displayId)791         public void onDisplayChanged(int displayId) {
792 
793         }
794     }
795 
796     private final class DisplayGroupPowerChangeListener implements
797             DisplayManagerInternal.DisplayGroupListener {
798 
799         static final int DISPLAY_GROUP_ADDED = 0;
800         static final int DISPLAY_GROUP_REMOVED = 1;
801         static final int DISPLAY_GROUP_CHANGED = 2;
802 
803         @Override
onDisplayGroupAdded(int groupId)804         public void onDisplayGroupAdded(int groupId) {
805             synchronized (mLock) {
806                 if (mPowerGroups.contains(groupId)) {
807                     Slog.e(TAG, "Tried to add already existing group:" + groupId);
808                     return;
809                 }
810                 // For now, only the default group supports sandman (dream/AOD).
811                 final boolean supportsSandman = groupId == Display.DEFAULT_DISPLAY_GROUP;
812                 final PowerGroup powerGroup = new PowerGroup(
813                         groupId,
814                         mPowerGroupWakefulnessChangeListener,
815                         mNotifier,
816                         mDisplayManagerInternal,
817                         WAKEFULNESS_AWAKE,
818                         /* ready= */ false,
819                         supportsSandman,
820                         mClock.uptimeMillis(),
821                         mFeatureFlags);
822                 mPowerGroups.append(groupId, powerGroup);
823                 onPowerGroupEventLocked(DISPLAY_GROUP_ADDED, powerGroup);
824             }
825         }
826 
827         @Override
onDisplayGroupRemoved(int groupId)828         public void onDisplayGroupRemoved(int groupId) {
829             synchronized (mLock) {
830                 if (groupId == Display.DEFAULT_DISPLAY_GROUP) {
831                     Slog.wtf(TAG, "Tried to remove default display group: " + groupId);
832                     return;
833                 }
834                 if (!mPowerGroups.contains(groupId)) {
835                     Slog.e(TAG, "Tried to remove non-existent group:" + groupId);
836                     return;
837                 }
838                 onPowerGroupEventLocked(DISPLAY_GROUP_REMOVED, mPowerGroups.get(groupId));
839             }
840         }
841 
842         @Override
onDisplayGroupChanged(int groupId)843         public void onDisplayGroupChanged(int groupId) {
844             synchronized (mLock) {
845                 if (!mPowerGroups.contains(groupId)) {
846                     Slog.e(TAG, "Tried to change non-existent group: " + groupId);
847                     return;
848                 }
849                 onPowerGroupEventLocked(DISPLAY_GROUP_CHANGED, mPowerGroups.get(groupId));
850             }
851         }
852     }
853 
854     private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
855         @Override
onUserSwitching(@serIdInt int newUserId)856         public void onUserSwitching(@UserIdInt int newUserId) throws RemoteException {
857             synchronized (mLock) {
858                 mUserId = newUserId;
859             }
860         }
861 
862         @Override
onForegroundProfileSwitch(@serIdInt int newProfileId)863         public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
864             final long now = mClock.uptimeMillis();
865             synchronized (mLock) {
866                 mForegroundProfile = newProfileId;
867                 maybeUpdateForegroundProfileLastActivityLocked(now);
868             }
869         }
870     }
871 
872     // User id corresponding to activity the user is currently interacting with.
873     private @UserIdInt int mForegroundProfile;
874     // User id of main profile for the current user (doesn't include managed profiles)
875     private @UserIdInt int mUserId;
876 
877     // Per-profile state to track when a profile should be locked.
878     private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
879 
880     private static final class ProfilePowerState {
881         // Profile user id.
882         final @UserIdInt int mUserId;
883         // Maximum time to lock set by admin.
884         long mScreenOffTimeout;
885         // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
886         int mWakeLockSummary;
887         // Last user activity that happened in an app running in the profile.
888         long mLastUserActivityTime;
889         // Whether profile has been locked last time it timed out.
890         boolean mLockingNotified;
891 
ProfilePowerState(@serIdInt int userId, long screenOffTimeout, long now)892         public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout, long now) {
893             mUserId = userId;
894             mScreenOffTimeout = screenOffTimeout;
895             // Not accurate but at least won't cause immediate locking of the profile.
896             mLastUserActivityTime = now;
897         }
898     }
899 
900     /**
901      * All times are in milliseconds. These constants are kept synchronized with the system
902      * global Settings. Any access to this class or its fields should be done while
903      * holding the PowerManagerService.mLock lock.
904      */
905     private final class Constants extends ContentObserver {
906         // Key names stored in the settings value.
907         private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
908 
909         private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
910 
911         // Prevent processes that are cached from holding wake locks?
912         public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
913 
914         private ContentResolver mResolver;
915         private final KeyValueListParser mParser = new KeyValueListParser(',');
916 
Constants(Handler handler)917         public Constants(Handler handler) {
918             super(handler);
919         }
920 
start(ContentResolver resolver)921         public void start(ContentResolver resolver) {
922             mResolver = resolver;
923             mResolver.registerContentObserver(Settings.Global.getUriFor(
924                     Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
925             updateConstants();
926         }
927 
928         @Override
onChange(boolean selfChange, Uri uri)929         public void onChange(boolean selfChange, Uri uri) {
930             updateConstants();
931         }
932 
updateConstants()933         private void updateConstants() {
934             synchronized (mLock) {
935                 try {
936                     mParser.setString(Settings.Global.getString(mResolver,
937                             Settings.Global.POWER_MANAGER_CONSTANTS));
938                 } catch (IllegalArgumentException e) {
939                     // Failed to parse the settings string, log this and move on
940                     // with defaults.
941                     Slog.e(TAG, "Bad alarm manager settings", e);
942                 }
943 
944                 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
945                         DEFAULT_NO_CACHED_WAKE_LOCKS);
946             }
947         }
948 
dump(PrintWriter pw)949         void dump(PrintWriter pw) {
950             pw.println("  Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
951 
952             pw.print("    "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
953             pw.println(NO_CACHED_WAKE_LOCKS);
954         }
955 
dumpProto(ProtoOutputStream proto)956         void dumpProto(ProtoOutputStream proto) {
957             final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
958             proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
959                     NO_CACHED_WAKE_LOCKS);
960             proto.end(constantsToken);
961         }
962     }
963 
964     /**
965      * Wrapper around the static-native methods of PowerManagerService.
966      *
967      * This class exists to allow us to mock static native methods in our tests. If mocking static
968      * methods becomes easier than this in the future, we can delete this class.
969      */
970     @VisibleForTesting
971     public static class NativeWrapper {
972         /** Wrapper for PowerManager.nativeInit */
nativeInit(PowerManagerService service)973         public void nativeInit(PowerManagerService service) {
974             service.nativeInit();
975         }
976 
977         /** Wrapper for PowerManager.nativeAcquireSuspectBlocker */
nativeAcquireSuspendBlocker(String name)978         public void nativeAcquireSuspendBlocker(String name) {
979             PowerManagerService.nativeAcquireSuspendBlocker(name);
980         }
981 
982         /** Wrapper for PowerManager.nativeReleaseSuspendBlocker */
nativeReleaseSuspendBlocker(String name)983         public void nativeReleaseSuspendBlocker(String name) {
984             PowerManagerService.nativeReleaseSuspendBlocker(name);
985         }
986 
987         /** Wrapper for PowerManager.nativeSetAutoSuspend */
nativeSetAutoSuspend(boolean enable)988         public void nativeSetAutoSuspend(boolean enable) {
989             PowerManagerService.nativeSetAutoSuspend(enable);
990         }
991 
992         /** Wrapper for PowerManager.nativeSetPowerBoost */
nativeSetPowerBoost(int boost, int durationMs)993         public void nativeSetPowerBoost(int boost, int durationMs) {
994             PowerManagerService.nativeSetPowerBoost(boost, durationMs);
995         }
996 
997         /** Wrapper for PowerManager.nativeSetPowerMode */
nativeSetPowerMode(int mode, boolean enabled)998         public boolean nativeSetPowerMode(int mode, boolean enabled) {
999             return PowerManagerService.nativeSetPowerMode(mode, enabled);
1000         }
1001 
1002         /** Wrapper for PowerManager.nativeForceSuspend */
nativeForceSuspend()1003         public boolean nativeForceSuspend() {
1004             return PowerManagerService.nativeForceSuspend();
1005         }
1006     }
1007 
1008     /** Functional interface for providing time. */
1009     @VisibleForTesting
1010     interface Clock {
1011         /**
1012          * Returns current time in milliseconds since boot, not counting time spent in deep sleep.
1013          */
uptimeMillis()1014         long uptimeMillis();
1015 
1016         /**
1017          * Returns milliseconds since boot, including time spent in sleep.
1018          */
elapsedRealtime()1019         long elapsedRealtime();
1020     }
1021 
1022     @VisibleForTesting
1023     static class Injector {
createNotifier(Looper looper, Context context, IBatteryStats batteryStats, SuspendBlocker suspendBlocker, WindowManagerPolicy policy, FaceDownDetector faceDownDetector, ScreenUndimDetector screenUndimDetector, Executor backgroundExecutor, PowerManagerFlags powerManagerFlags)1024         Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
1025                 SuspendBlocker suspendBlocker, WindowManagerPolicy policy,
1026                 FaceDownDetector faceDownDetector, ScreenUndimDetector screenUndimDetector,
1027                 Executor backgroundExecutor, PowerManagerFlags powerManagerFlags) {
1028             return new Notifier(
1029                     looper, context, batteryStats, suspendBlocker, policy, faceDownDetector,
1030                     screenUndimDetector, backgroundExecutor, powerManagerFlags, /*injector=*/ null);
1031         }
1032 
createSuspendBlocker(PowerManagerService service, String name)1033         SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
1034             SuspendBlocker suspendBlocker = service.new SuspendBlockerImpl(name);
1035             service.mSuspendBlockers.add(suspendBlocker);
1036             return suspendBlocker;
1037         }
1038 
createBatterySaverStateMachine(Object lock, Context context)1039         BatterySaverStateMachine createBatterySaverStateMachine(Object lock, Context context) {
1040             BatterySavingStats batterySavingStats = new BatterySavingStats(lock);
1041             BatterySaverPolicy batterySaverPolicy = new BatterySaverPolicy(lock, context,
1042                     batterySavingStats);
1043             BatterySaverController batterySaverController = new BatterySaverController(lock,
1044                     context, BackgroundThread.get().getLooper(),
1045                     batterySaverPolicy, batterySavingStats);
1046             return new BatterySaverStateMachine(lock, context, batterySaverController);
1047         }
1048 
createNativeWrapper()1049         NativeWrapper createNativeWrapper() {
1050             return new NativeWrapper();
1051         }
1052 
createWirelessChargerDetector( SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler)1053         WirelessChargerDetector createWirelessChargerDetector(
1054                 SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
1055             return new WirelessChargerDetector(sensorManager, suspendBlocker, handler);
1056         }
1057 
createAmbientDisplayConfiguration(Context context)1058         AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
1059             return new AmbientDisplayConfiguration(context);
1060         }
1061 
createAmbientDisplaySuppressionController( @onNull AmbientDisplaySuppressionChangedCallback callback)1062         AmbientDisplaySuppressionController createAmbientDisplaySuppressionController(
1063                 @NonNull AmbientDisplaySuppressionChangedCallback callback) {
1064             return new AmbientDisplaySuppressionController(callback);
1065         }
1066 
createInattentiveSleepWarningController()1067         InattentiveSleepWarningController createInattentiveSleepWarningController() {
1068             return new InattentiveSleepWarningController();
1069         }
1070 
createFoldGracePeriodProvider()1071         FoldGracePeriodProvider createFoldGracePeriodProvider() {
1072             return new FoldGracePeriodProvider();
1073         }
1074 
createSystemPropertiesWrapper()1075         public SystemPropertiesWrapper createSystemPropertiesWrapper() {
1076             return new SystemPropertiesWrapper() {
1077                 @Override
1078                 public String get(String key, String def) {
1079                     return SystemProperties.get(key, def);
1080                 }
1081 
1082                 @Override
1083                 public void set(String key, String val) {
1084                     SystemProperties.set(key, val);
1085                 }
1086             };
1087         }
1088 
createClock()1089         Clock createClock() {
1090             return new Clock() {
1091                 @Override
1092                 public long uptimeMillis() {
1093                     return SystemClock.uptimeMillis();
1094                 }
1095 
1096                 @Override
1097                 public long elapsedRealtime() {
1098                     return SystemClock.elapsedRealtime();
1099                 }
1100             };
1101 
1102         }
1103 
1104         /**
1105          * Handler for asynchronous operations performed by the power manager.
1106          */
1107         Handler createHandler(Looper looper, Handler.Callback callback) {
1108             return new Handler(looper, callback, /* async= */ true);
1109         }
1110 
1111         void invalidateIsInteractiveCaches() {
1112             PowerManager.invalidateIsInteractiveCaches();
1113         }
1114 
1115         LowPowerStandbyController createLowPowerStandbyController(Context context, Looper looper) {
1116             return new LowPowerStandbyController(context, looper);
1117         }
1118 
1119         PermissionCheckerWrapper createPermissionCheckerWrapper() {
1120             return PermissionChecker::checkPermissionForDataDelivery;
1121         }
1122 
1123         PowerPropertiesWrapper createPowerPropertiesWrapper() {
1124             return new PowerPropertiesWrapper() {
1125                 @Override
1126                 public boolean waive_target_sdk_check_for_turn_screen_on() {
1127                     return PowerProperties.waive_target_sdk_check_for_turn_screen_on().orElse(
1128                             false);
1129                 }
1130 
1131                 @Override
1132                 public boolean permissionless_turn_screen_on() {
1133                     return PowerProperties.permissionless_turn_screen_on().orElse(false);
1134                 }
1135             };
1136         }
1137 
1138         DeviceConfigParameterProvider createDeviceConfigParameterProvider() {
1139             return new DeviceConfigParameterProvider(DeviceConfigInterface.REAL);
1140         }
1141 
1142         PowerManagerFlags getFlags() {
1143             return new PowerManagerFlags();
1144         }
1145     }
1146 
1147     /** Interface for checking an app op permission */
1148     @VisibleForTesting
1149     interface PermissionCheckerWrapper {
1150         /**
1151          * Checks whether a given data access chain described by the given {@link AttributionSource}
1152          * has a given permission and whether the app op that corresponds to this permission
1153          * is allowed.
1154          * See {@link PermissionChecker#checkPermissionForDataDelivery} for more details.
1155          *
1156          * @param context Context for accessing resources.
1157          * @param permission The permission to check.
1158          * @param pid The process id for which to check. Use {@link PermissionChecker#PID_UNKNOWN}
1159          *    if the PID is not known.
1160          * @param attributionSource the permission identity
1161          * @param message A message describing the reason the permission was checked
1162          * @return The permission check result which is any of
1163          *     {@link PermissionChecker#PERMISSION_GRANTED},
1164          *     {@link PermissionChecker#PERMISSION_SOFT_DENIED},
1165          *     or {@link PermissionChecker#PERMISSION_HARD_DENIED}.
1166          */
1167         int checkPermissionForDataDelivery(@NonNull Context context, @NonNull String permission,
1168                 int pid, @NonNull AttributionSource attributionSource, @Nullable String message);
1169     }
1170 
1171     /** Interface for querying {@link PowerProperties} */
1172     @VisibleForTesting
1173     interface PowerPropertiesWrapper {
1174         /**
1175          * Waives the minimum target-sdk check for android.os.PowerManager#ACQUIRE_CAUSES_WAKEUP
1176          * and only allows the flag for apps holding android.permission.TURN_SCREEN_ON
1177          */
1178         boolean waive_target_sdk_check_for_turn_screen_on();
1179 
1180         /**
1181          * Allows apps to turn the screen on with android.os.PowerManager#ACQUIRE_CAUSES_WAKEUP
1182          * without being granted android.app.AppOpsManager#OP_TURN_SCREEN_ON.
1183          */
1184         boolean permissionless_turn_screen_on();
1185     }
1186 
1187     final Constants mConstants;
1188 
1189     private native void nativeInit();
1190     private static native void nativeAcquireSuspendBlocker(String name);
1191     private static native void nativeReleaseSuspendBlocker(String name);
1192     private static native void nativeSetAutoSuspend(boolean enable);
1193     private static native void nativeSetPowerBoost(int boost, int durationMs);
1194     private static native boolean nativeSetPowerMode(int mode, boolean enabled);
1195     private static native boolean nativeForceSuspend();
1196 
1197     public PowerManagerService(Context context) {
1198         this(context, new Injector());
1199     }
1200 
1201     @VisibleForTesting
1202     PowerManagerService(Context context, Injector injector) {
1203         super(context);
1204 
1205         mContext = context;
1206         mBinderService = new BinderService(mContext);
1207         mLocalService = new LocalService();
1208         mNativeWrapper = injector.createNativeWrapper();
1209         mSystemProperties = injector.createSystemPropertiesWrapper();
1210         mClock = injector.createClock();
1211         mFeatureFlags = injector.getFlags();
1212         mInjector = injector;
1213 
1214         mHandlerThread = new ServiceThread(TAG,
1215                 Process.THREAD_PRIORITY_DISPLAY, /* allowIo= */ false);
1216         mHandlerThread.start();
1217         mHandler = injector.createHandler(mHandlerThread.getLooper(),
1218                 new PowerManagerHandlerCallback());
1219         mConstants = new Constants(mHandler);
1220         mFoldGracePeriodProvider = injector.createFoldGracePeriodProvider();
1221         mAmbientDisplayConfiguration = mInjector.createAmbientDisplayConfiguration(context);
1222         mAmbientDisplaySuppressionController =
1223                 mInjector.createAmbientDisplaySuppressionController(
1224                         mAmbientSuppressionChangedCallback);
1225         mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
1226         mFaceDownDetector = new FaceDownDetector(this::onFlip);
1227         mScreenUndimDetector = new ScreenUndimDetector();
1228 
1229         mBatterySaverSupported = mContext.getResources().getBoolean(
1230                 com.android.internal.R.bool.config_batterySaverSupported);
1231         mBatterySaverStateMachine =
1232                 mBatterySaverSupported ? mInjector.createBatterySaverStateMachine(mLock, mContext)
1233                         : null;
1234 
1235         mLowPowerStandbyController = mInjector.createLowPowerStandbyController(mContext,
1236                 Looper.getMainLooper());
1237         mInattentiveSleepWarningOverlayController =
1238                 mInjector.createInattentiveSleepWarningController();
1239         mPermissionCheckerWrapper = mInjector.createPermissionCheckerWrapper();
1240         mPowerPropertiesWrapper = mInjector.createPowerPropertiesWrapper();
1241         mDeviceConfigProvider = mInjector.createDeviceConfigParameterProvider();
1242 
1243         mPowerGroupWakefulnessChangeListener = new PowerGroupWakefulnessChangeListener();
1244 
1245         mUseAutoSuspend = mContext.getResources().getBoolean(com.android.internal.R.bool
1246                 .config_useAutoSuspend);
1247 
1248         // Save brightness values:
1249         // Get float values from config.
1250         // Store float if valid
1251         // Otherwise, get int values and convert to float and then store.
1252         final float min = mContext.getResources().getFloat(com.android.internal.R.dimen
1253                 .config_screenBrightnessSettingMinimumFloat);
1254         final float max = mContext.getResources().getFloat(com.android.internal.R.dimen
1255                 .config_screenBrightnessSettingMaximumFloat);
1256         final float def = mContext.getResources().getFloat(com.android.internal.R.dimen
1257                 .config_screenBrightnessSettingDefaultFloat);
1258         final float dim = mContext.getResources().getFloat(com.android.internal.R.dimen
1259                 .config_screenBrightnessDimFloat);
1260 
1261         if (min == INVALID_BRIGHTNESS_IN_CONFIG || max == INVALID_BRIGHTNESS_IN_CONFIG
1262                 || def == INVALID_BRIGHTNESS_IN_CONFIG) {
1263             mScreenBrightnessMinimum = BrightnessSynchronizer.brightnessIntToFloat(
1264                     mContext.getResources().getInteger(com.android.internal.R.integer
1265                             .config_screenBrightnessSettingMinimum));
1266             mScreenBrightnessMaximum = BrightnessSynchronizer.brightnessIntToFloat(
1267                     mContext.getResources().getInteger(com.android.internal.R.integer
1268                             .config_screenBrightnessSettingMaximum));
1269             mScreenBrightnessDefault = BrightnessSynchronizer.brightnessIntToFloat(
1270                     mContext.getResources().getInteger(com.android.internal.R.integer
1271                             .config_screenBrightnessSettingDefault));
1272         } else {
1273             mScreenBrightnessMinimum = min;
1274             mScreenBrightnessMaximum = max;
1275             mScreenBrightnessDefault = def;
1276         }
1277         if (dim == INVALID_BRIGHTNESS_IN_CONFIG) {
1278             mScreenBrightnessDim = BrightnessSynchronizer.brightnessIntToFloat(
1279                     mContext.getResources().getInteger(com.android.internal.R.integer
1280                             .config_screenBrightnessDim));
1281         } else {
1282             mScreenBrightnessDim = dim;
1283         }
1284 
1285         synchronized (mLock) {
1286             mBootingSuspendBlocker =
1287                     mInjector.createSuspendBlocker(this, "PowerManagerService.Booting");
1288             mWakeLockSuspendBlocker =
1289                     mInjector.createSuspendBlocker(this, "PowerManagerService.WakeLocks");
1290             mDisplaySuspendBlocker =
1291                     mInjector.createSuspendBlocker(this, "PowerManagerService.Display");
1292             if (mBootingSuspendBlocker != null) {
1293                 mBootingSuspendBlocker.acquire();
1294                 mHoldingBootingSuspendBlocker = true;
1295             }
1296             if (mDisplaySuspendBlocker != null) {
1297                 mDisplaySuspendBlocker.acquire(HOLDING_DISPLAY_SUSPEND_BLOCKER);
1298                 mHoldingDisplaySuspendBlocker = true;
1299             }
1300             mHalAutoSuspendModeEnabled = false;
1301             mHalInteractiveModeEnabled = true;
1302 
1303             mWakefulnessRaw = WAKEFULNESS_AWAKE;
1304             sQuiescent = mSystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
1305 
1306             mNativeWrapper.nativeInit(this);
1307             mNativeWrapper.nativeSetAutoSuspend(false);
1308             mNativeWrapper.nativeSetPowerMode(Mode.INTERACTIVE, true);
1309             mNativeWrapper.nativeSetPowerMode(Mode.DOUBLE_TAP_TO_WAKE, false);
1310             mInjector.invalidateIsInteractiveCaches();
1311         }
1312     }
1313 
1314     private void onFlip(boolean isFaceDown) {
1315         long millisUntilNormalTimeout = 0;
1316         synchronized (mLock) {
1317             if (!mBootCompleted) {
1318                 return;
1319             }
1320 
1321             Slog.i(TAG, "onFlip(): Face " + (isFaceDown ? "down." : "up."));
1322             mIsFaceDown = isFaceDown;
1323             if (isFaceDown) {
1324                 final long currentTime = mClock.uptimeMillis();
1325                 mLastFlipTime = currentTime;
1326                 final long sleepTimeout = getSleepTimeoutLocked(-1L);
1327                 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, -1L);
1328                 final PowerGroup powerGroup = mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP);
1329                 millisUntilNormalTimeout =
1330                         powerGroup.getLastUserActivityTimeLocked() + screenOffTimeout - currentTime;
1331                 userActivityInternal(Display.DEFAULT_DISPLAY, currentTime,
1332                         PowerManager.USER_ACTIVITY_EVENT_FACE_DOWN,
1333                         PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS, Process.SYSTEM_UID);
1334             }
1335         }
1336         if (isFaceDown) {
1337             mFaceDownDetector.setMillisSaved(millisUntilNormalTimeout);
1338         }
1339     }
1340 
1341     @Override
1342     public void onStart() {
1343         publishBinderService(Context.POWER_SERVICE, mBinderService, /* allowIsolated= */ false,
1344                 DUMP_FLAG_PRIORITY_CRITICAL);
1345         publishLocalService(PowerManagerInternal.class, mLocalService);
1346 
1347         Watchdog.getInstance().addMonitor(this);
1348         Watchdog.getInstance().addThread(mHandler);
1349     }
1350 
1351     @Override
1352     public void onBootPhase(int phase) {
1353         if (phase == PHASE_SYSTEM_SERVICES_READY) {
1354             systemReady();
1355 
1356         } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
1357             incrementBootCount();
1358 
1359         } else if (phase == PHASE_BOOT_COMPLETED) {
1360             synchronized (mLock) {
1361                 final long now = mClock.uptimeMillis();
1362                 mBootCompleted = true;
1363                 mDirty |= DIRTY_BOOT_COMPLETED;
1364 
1365                 if (mBatterySaverSupported) {
1366                     mBatterySaverStateMachine.onBootCompleted();
1367                 }
1368                 userActivityNoUpdateLocked(
1369                         now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1370 
1371                 updatePowerStateLocked();
1372                 if (sQuiescent) {
1373                     sleepPowerGroupLocked(mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP),
1374                             mClock.uptimeMillis(),
1375                             PowerManager.GO_TO_SLEEP_REASON_QUIESCENT,
1376                             Process.SYSTEM_UID);
1377                 }
1378 
1379                 mContext.getSystemService(DeviceStateManager.class).registerCallback(
1380                         new HandlerExecutor(mHandler), new DeviceStateListener());
1381             }
1382         }
1383     }
1384 
1385     private void systemReady() {
1386         synchronized (mLock) {
1387             mSystemReady = true;
1388             mDreamManager = getLocalService(DreamManagerInternal.class);
1389             mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
1390             mPolicy = getLocalService(WindowManagerPolicy.class);
1391             mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
1392             mDisplayManager = mContext.getSystemService(DisplayManager.class);
1393             mAttentionDetector.systemReady(mContext);
1394 
1395             SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
1396 
1397             // The notifier runs on the system server's main looper so as not to interfere
1398             // with the animations and other critical functions of the power manager.
1399             mBatteryStats = BatteryStatsService.getService();
1400             mNotifier = mInjector.createNotifier(Looper.getMainLooper(), mContext, mBatteryStats,
1401                     mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
1402                     mPolicy, mFaceDownDetector, mScreenUndimDetector,
1403                     BackgroundThread.getExecutor(), mFeatureFlags);
1404 
1405             mPowerGroups.append(Display.DEFAULT_DISPLAY_GROUP,
1406                     new PowerGroup(WAKEFULNESS_AWAKE, mPowerGroupWakefulnessChangeListener,
1407                             mNotifier, mDisplayManagerInternal, mClock.uptimeMillis(),
1408                             mFeatureFlags));
1409             DisplayGroupPowerChangeListener displayGroupPowerChangeListener =
1410                     new DisplayGroupPowerChangeListener();
1411             mDisplayManagerInternal.registerDisplayGroupListener(displayGroupPowerChangeListener);
1412             if (mFeatureFlags.isScreenTimeoutPolicyListenerApiEnabled()) {
1413                 mDisplayManager.registerDisplayListener(new DisplayListener(), mHandler);
1414             }
1415 
1416             if(mDreamManager != null){
1417                 // This DreamManager method does not acquire a lock, so it should be safe to call.
1418                 mDreamManager.registerDreamManagerStateListener(new DreamManagerStateListener());
1419             }
1420 
1421             mWirelessChargerDetector = mInjector.createWirelessChargerDetector(sensorManager,
1422                     mInjector.createSuspendBlocker(
1423                             this, "PowerManagerService.WirelessChargerDetector"),
1424                     mHandler);
1425             mSettingsObserver = new SettingsObserver(mHandler);
1426 
1427             mLightsManager = getLocalService(LightsManager.class);
1428             mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
1429             updateDeviceConfigLocked();
1430             mDeviceConfigProvider.addOnPropertiesChangedListener(BackgroundThread.getExecutor(),
1431                     properties -> {
1432                         synchronized (mLock) {
1433                             updateDeviceConfigLocked();
1434                             updateWakeLockDisabledStatesLocked();
1435                         }
1436                     });
1437 
1438             // Initialize display power management.
1439             mDisplayManagerInternal.initPowerManagement(
1440                     mDisplayPowerCallbacks, mHandler, sensorManager);
1441 
1442             // Create power groups for display groups other than DEFAULT_DISPLAY_GROUP.
1443             addPowerGroupsForNonDefaultDisplayGroupLocked();
1444 
1445             try {
1446                 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
1447                 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
1448             } catch (RemoteException e) {
1449                 // Shouldn't happen since in-process.
1450             }
1451 
1452             mLowPowerStandbyController.systemReady();
1453 
1454             // Go.
1455             readConfigurationLocked();
1456             updateSettingsLocked();
1457             if (mFeatureFlags.isEarlyScreenTimeoutDetectorEnabled()) {
1458                 mScreenTimeoutOverridePolicy = new ScreenTimeoutOverridePolicy(mContext,
1459                         mMinimumScreenOffTimeoutConfig, (releaseReason) -> {
1460                     Message msg = mHandler.obtainMessage(MSG_RELEASE_ALL_OVERRIDE_WAKE_LOCKS);
1461                     msg.arg1 = releaseReason;
1462                     mHandler.sendMessageAtTime(msg, mClock.uptimeMillis());
1463                 });
1464             }
1465             mDirty |= DIRTY_BATTERY_STATE;
1466             updatePowerStateLocked();
1467         }
1468 
1469         final ContentResolver resolver = mContext.getContentResolver();
1470         mConstants.start(resolver);
1471 
1472         if (mBatterySaverSupported) {
1473             mBatterySaverStateMachine.systemReady();
1474         }
1475         mFaceDownDetector.systemReady(mContext);
1476         mScreenUndimDetector.systemReady(mContext);
1477 
1478         // Register for settings changes.
1479         resolver.registerContentObserver(Settings.Secure.getUriFor(
1480                 Settings.Secure.SCREENSAVER_ENABLED),
1481                 false, mSettingsObserver, UserHandle.USER_ALL);
1482         resolver.registerContentObserver(Settings.Secure.getUriFor(
1483                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
1484                 false, mSettingsObserver, UserHandle.USER_ALL);
1485         resolver.registerContentObserver(Settings.Secure.getUriFor(
1486                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
1487                 false, mSettingsObserver, UserHandle.USER_ALL);
1488         resolver.registerContentObserver(Settings.Secure.getUriFor(
1489                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_POSTURED),
1490                 false, mSettingsObserver, UserHandle.USER_ALL);
1491         resolver.registerContentObserver(Settings.System.getUriFor(
1492                 Settings.System.SCREEN_OFF_TIMEOUT),
1493                 false, mSettingsObserver, UserHandle.USER_ALL);
1494         resolver.registerContentObserver(Settings.Secure.getUriFor(
1495                 Settings.Secure.SLEEP_TIMEOUT),
1496                 false, mSettingsObserver, UserHandle.USER_ALL);
1497         resolver.registerContentObserver(Settings.Secure.getUriFor(
1498                 Settings.Secure.ATTENTIVE_TIMEOUT),
1499                 false, mSettingsObserver, UserHandle.USER_ALL);
1500         resolver.registerContentObserver(Settings.Global.getUriFor(
1501                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
1502                 false, mSettingsObserver, UserHandle.USER_ALL);
1503         resolver.registerContentObserver(Settings.System.getUriFor(
1504                 Settings.System.SCREEN_BRIGHTNESS_MODE),
1505                 false, mSettingsObserver, UserHandle.USER_ALL);
1506         resolver.registerContentObserver(Settings.System.getUriFor(
1507                 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
1508                 false, mSettingsObserver, UserHandle.USER_ALL);
1509         resolver.registerContentObserver(Settings.Global.getUriFor(
1510                 Settings.Global.THEATER_MODE_ON),
1511                 false, mSettingsObserver, UserHandle.USER_ALL);
1512         resolver.registerContentObserver(Settings.Secure.getUriFor(
1513                 Settings.Secure.DOZE_ALWAYS_ON),
1514                 false, mSettingsObserver, UserHandle.USER_ALL);
1515         resolver.registerContentObserver(Settings.Secure.getUriFor(
1516                 Settings.Secure.DOUBLE_TAP_TO_WAKE),
1517                 false, mSettingsObserver, UserHandle.USER_ALL);
1518         resolver.registerContentObserver(Settings.Global.getUriFor(
1519                 Settings.Global.DEVICE_DEMO_MODE),
1520                 false, mSettingsObserver, UserHandle.USER_SYSTEM);
1521 
1522         // Register for broadcasts from other components of the system.
1523         IntentFilter filter = new IntentFilter();
1524         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
1525         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1526         mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
1527 
1528         filter = new IntentFilter();
1529         filter.addAction(Intent.ACTION_DREAMING_STARTED);
1530         filter.addAction(Intent.ACTION_DREAMING_STOPPED);
1531         mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
1532 
1533         filter = new IntentFilter();
1534         filter.addAction(Intent.ACTION_USER_SWITCHED);
1535         mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
1536 
1537         filter = new IntentFilter();
1538         filter.addAction(Intent.ACTION_DOCK_EVENT);
1539         mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
1540     }
1541 
1542     @VisibleForTesting
1543     @GuardedBy("mLock")
1544     void readConfigurationLocked() {
1545         final Resources resources = mContext.getResources();
1546 
1547         mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
1548                 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
1549         mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
1550                 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
1551         mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
1552                 com.android.internal.R.bool.config_unplugTurnsOnScreen);
1553         mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
1554                 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
1555         mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
1556                 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
1557         mAttentiveTimeoutConfig = resources.getInteger(
1558                 com.android.internal.R.integer.config_attentiveTimeout);
1559         mAttentiveWarningDurationConfig = resources.getInteger(
1560                 com.android.internal.R.integer.config_attentiveWarningDuration);
1561         mDreamsSupportedConfig = resources.getBoolean(
1562                 com.android.internal.R.bool.config_dreamsSupported);
1563         mDreamsEnabledByDefaultConfig = resources.getBoolean(
1564                 com.android.internal.R.bool.config_dreamsEnabledByDefault);
1565         mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
1566                 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
1567         mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
1568                 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
1569         mDreamsActivatedWhilePosturedByDefaultConfig = resources.getBoolean(
1570                 com.android.internal.R.bool.config_dreamsActivatedOnPosturedByDefault);
1571         mDreamsEnabledOnBatteryConfig = resources.getBoolean(
1572                 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
1573         mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
1574                 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
1575         mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
1576                 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
1577         mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
1578                 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
1579         mDreamsDisabledByAmbientModeSuppressionConfig = resources.getBoolean(
1580                 com.android.internal.R.bool.config_dreamsDisabledByAmbientModeSuppressionConfig);
1581         mDozeAfterScreenOff = resources.getBoolean(
1582                 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
1583         mBrightWhenDozingConfig = resources.getBoolean(
1584                 com.android.internal.R.bool.config_brightWhenDozing);
1585         mMinimumScreenOffTimeoutConfig = resources.getInteger(
1586                 com.android.internal.R.integer.config_minimumScreenOffTimeout);
1587         mMaximumScreenDimDurationConfig = resources.getInteger(
1588                 com.android.internal.R.integer.config_maximumScreenDimDuration);
1589         mMaximumScreenDimRatioConfig = resources.getFraction(
1590                 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
1591         mSupportsDoubleTapWakeConfig = resources.getBoolean(
1592                 com.android.internal.R.bool.config_supportDoubleTapWake);
1593     }
1594 
1595     @GuardedBy("mLock")
1596     private void updateSettingsLocked() {
1597         final ContentResolver resolver = mContext.getContentResolver();
1598 
1599         mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
1600                 Settings.Secure.SCREENSAVER_ENABLED,
1601                 mDreamsEnabledByDefaultConfig ? 1 : 0,
1602                 UserHandle.USER_CURRENT) != 0);
1603         mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
1604                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
1605                 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
1606                 UserHandle.USER_CURRENT) != 0);
1607         mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
1608                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
1609                 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
1610                 UserHandle.USER_CURRENT) != 0);
1611         mDreamsActivateWhilePosturedSetting = (Settings.Secure.getIntForUser(resolver,
1612                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_POSTURED,
1613                 mDreamsActivatedWhilePosturedByDefaultConfig ? 1 : 0,
1614                 UserHandle.USER_CURRENT) != 0);
1615         mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
1616                 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
1617                 UserHandle.USER_CURRENT);
1618         mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1619                 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
1620                 UserHandle.USER_CURRENT);
1621         mAttentiveTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1622                 Settings.Secure.ATTENTIVE_TIMEOUT, mAttentiveTimeoutConfig,
1623                 UserHandle.USER_CURRENT);
1624         mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
1625                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
1626         mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1627                 Settings.Global.THEATER_MODE_ON, 0) == 1;
1628         mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
1629 
1630         if (mSupportsDoubleTapWakeConfig) {
1631             boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
1632                     Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
1633                             UserHandle.USER_CURRENT) != 0;
1634             if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
1635                 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
1636                 mNativeWrapper.nativeSetPowerMode(Mode.DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled);
1637             }
1638         }
1639 
1640         final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
1641         if (!retailDemoValue.equals(
1642                 mSystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, null))) {
1643             mSystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
1644         }
1645 
1646         mDirty |= DIRTY_SETTINGS;
1647     }
1648 
1649     @VisibleForTesting
1650     @GuardedBy("mLock")
1651     void handleSettingsChangedLocked() {
1652         updateSettingsLocked();
1653         updatePowerStateLocked();
1654     }
1655 
1656     @GuardedBy("mLock")
1657     private void updateDeviceConfigLocked() {
1658         mDisableScreenWakeLocksWhileCached = mDeviceConfigProvider
1659                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
1660     }
1661 
1662     @RequiresPermission(value = android.Manifest.permission.TURN_SCREEN_ON, conditional = true)
1663     private void acquireWakeLockInternal(IBinder lock, int displayId, int flags, String tag,
1664             String packageName, WorkSource ws, String historyTag, int uid, int pid,
1665             @Nullable IWakeLockCallback callback) {
1666         synchronized (mLock) {
1667             if (displayId != Display.INVALID_DISPLAY) {
1668                 final DisplayInfo displayInfo =
1669                         mSystemReady ? mDisplayManagerInternal.getDisplayInfo(displayId) : null;
1670                 if (displayInfo == null) {
1671                     Slog.wtf(TAG, "Tried to acquire wake lock for invalid display: " + displayId);
1672                     return;
1673                 } else if (!displayInfo.hasAccess(uid)) {
1674                     throw new SecurityException("Caller does not have access to display");
1675                 }
1676             }
1677 
1678             if (DEBUG_SPEW) {
1679                 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1680                         + ", flags=0x" + Integer.toHexString(flags)
1681                         + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
1682             }
1683 
1684             WakeLock wakeLock;
1685             int index = findWakeLockIndexLocked(lock);
1686             boolean notifyAcquire;
1687             if (index >= 0) {
1688                 wakeLock = mWakeLocks.get(index);
1689                 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid, callback)) {
1690                     // Update existing wake lock.  This shouldn't happen but is harmless.
1691                     notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1692                             uid, pid, ws, historyTag, callback);
1693                     wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid,
1694                             callback);
1695                 }
1696                 notifyAcquire = false;
1697             } else {
1698                 UidState state = mUidState.get(uid);
1699                 if (state == null) {
1700                     state = new UidState(uid);
1701                     state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1702                     mUidState.put(uid, state);
1703                 }
1704                 state.mNumWakeLocks++;
1705                 wakeLock = new WakeLock(lock, displayId, flags, tag, packageName, ws, historyTag,
1706                         uid, pid, state, callback);
1707                 mWakeLocks.add(wakeLock);
1708                 setWakeLockDisabledStateLocked(wakeLock);
1709                 notifyAcquire = true;
1710             }
1711 
1712             applyWakeLockFlagsOnAcquireLocked(wakeLock);
1713             mDirty |= DIRTY_WAKE_LOCKS;
1714             updatePowerStateLocked();
1715             if (notifyAcquire) {
1716                 // This needs to be done last so we are sure we have acquired the
1717                 // kernel wake lock.  Otherwise we have a race where the system may
1718                 // go to sleep between the time we start the accounting in battery
1719                 // stats and when we actually get around to telling the kernel to
1720                 // stay awake.
1721                 notifyWakeLockAcquiredLocked(wakeLock);
1722             }
1723         }
1724     }
1725 
1726     private static boolean isScreenLock(final WakeLock wakeLock) {
1727         return isScreenLock(wakeLock.mFlags);
1728     }
1729 
1730     /**
1731      * Returns if a wakelock flag corresponds to a screen wake lock.
1732      */
1733     @SuppressWarnings("deprecation")
1734     public static boolean isScreenLock(int flags) {
1735         switch (flags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1736             case PowerManager.FULL_WAKE_LOCK:
1737             case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1738             case PowerManager.SCREEN_DIM_WAKE_LOCK:
1739                 return true;
1740         }
1741         return false;
1742     }
1743 
1744     private static WorkChain getFirstNonEmptyWorkChain(WorkSource workSource) {
1745         if (workSource.getWorkChains() == null) {
1746             return null;
1747         }
1748 
1749         for (WorkChain workChain: workSource.getWorkChains()) {
1750             if (workChain.getSize() > 0) {
1751                 return workChain;
1752             }
1753         }
1754 
1755         return null;
1756     }
1757 
1758     @RequiresPermission(value = android.Manifest.permission.TURN_SCREEN_ON, conditional = true)
1759     private boolean isAcquireCausesWakeupFlagAllowed(String opPackageName, int opUid, int opPid) {
1760         if (opPackageName == null) {
1761             return false;
1762         }
1763         if (PermissionChecker.PERMISSION_GRANTED
1764                 == mPermissionCheckerWrapper.checkPermissionForDataDelivery(mContext,
1765                 android.Manifest.permission.TURN_SCREEN_ON, opPid,
1766                 new AttributionSource(opUid, opPackageName, /* attributionTag= */ null),
1767                 /* message= */ "ACQUIRE_CAUSES_WAKEUP for " + opPackageName)) {
1768             Slog.i(TAG, "Allowing device wake-up from app " + opPackageName);
1769             return true;
1770         }
1771         // CompatChanges#isChangeEnabled() returns false for apps with targetSdk < UDC and ensures
1772         // backwards compatibility.
1773         // waive_target_sdk_check_for_turn_screen_on() returns false by default and may be set to
1774         // true on form factors with a more strict policy (e.g. TV)
1775         if (!CompatChanges.isChangeEnabled(REQUIRE_TURN_SCREEN_ON_PERMISSION, opUid)
1776                 && !mPowerPropertiesWrapper.waive_target_sdk_check_for_turn_screen_on()) {
1777             Slog.i(TAG, "Allowing device wake-up without android.permission.TURN_SCREEN_ON for "
1778                     + opPackageName);
1779             return true;
1780         }
1781         if (mPowerPropertiesWrapper.permissionless_turn_screen_on()) {
1782             Slog.d(TAG, "Device wake-up allowed by debug.power.permissionless_turn_screen_on");
1783             return true;
1784         }
1785         Slog.w(TAG, "Not allowing device wake-up for " + opPackageName);
1786         return false;
1787     }
1788 
1789     @GuardedBy("mLock")
1790     @RequiresPermission(value = android.Manifest.permission.TURN_SCREEN_ON, conditional = true)
1791     private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) {
1792         if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1793                 && isScreenLock(wakeLock)) {
1794             String opPackageName;
1795             int opUid;
1796             int opPid = PermissionChecker.PID_UNKNOWN;
1797             if (wakeLock.mWorkSource != null && !wakeLock.mWorkSource.isEmpty()) {
1798                 WorkSource workSource = wakeLock.mWorkSource;
1799                 WorkChain workChain = getFirstNonEmptyWorkChain(workSource);
1800                 if (workChain != null) {
1801                     opPackageName = workChain.getAttributionTag();
1802                     opUid = workChain.getAttributionUid();
1803                 } else {
1804                     opPackageName = workSource.getPackageName(0) != null
1805                             ? workSource.getPackageName(0) : wakeLock.mPackageName;
1806                     opUid = workSource.getUid(0);
1807                 }
1808             } else {
1809                 opPackageName = wakeLock.mPackageName;
1810                 opUid = wakeLock.mOwnerUid;
1811                 opPid = wakeLock.mOwnerPid;
1812             }
1813             Integer powerGroupId = wakeLock.getPowerGroupId();
1814             // powerGroupId is null if the wakelock associated display is no longer available
1815             if (powerGroupId != null
1816                     && isAcquireCausesWakeupFlagAllowed(opPackageName, opUid, opPid)) {
1817                 if (powerGroupId == Display.INVALID_DISPLAY_GROUP) {
1818                     // wake up all display groups
1819                     if (DEBUG_SPEW) {
1820                         Slog.d(TAG, "Waking up all power groups");
1821                     }
1822                     for (int idx = 0; idx < mPowerGroups.size(); idx++) {
1823                         wakePowerGroupLocked(mPowerGroups.valueAt(idx), mClock.uptimeMillis(),
1824                                 PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag, opUid,
1825                                 opPackageName, opUid);
1826                     }
1827                     return;
1828                 }
1829                 if (mPowerGroups.contains(powerGroupId)) {
1830                     if (DEBUG_SPEW) {
1831                         Slog.d(TAG, "Waking up power group " + powerGroupId);
1832                     }
1833                     wakePowerGroupLocked(mPowerGroups.get(powerGroupId), mClock.uptimeMillis(),
1834                             PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag, opUid,
1835                             opPackageName, opUid);
1836                 }
1837             }
1838         }
1839     }
1840 
1841     private void releaseWakeLockInternal(IBinder lock, int flags) {
1842         synchronized (mLock) {
1843             int index = findWakeLockIndexLocked(lock);
1844             if (index < 0) {
1845                 if (DEBUG_SPEW) {
1846                     Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1847                             + " [not found], flags=0x" + Integer.toHexString(flags));
1848                 }
1849                 return;
1850             }
1851 
1852             WakeLock wakeLock = mWakeLocks.get(index);
1853             if (DEBUG_SPEW) {
1854                 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1855                         + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1856             }
1857 
1858             if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
1859                 mRequestWaitForNegativeProximity = true;
1860             }
1861 
1862             wakeLock.unlinkToDeath();
1863             wakeLock.setDisabled(true);
1864             removeWakeLockLocked(wakeLock, index);
1865         }
1866     }
1867 
1868     private void handleWakeLockDeath(WakeLock wakeLock) {
1869         synchronized (mLock) {
1870             if (DEBUG_SPEW) {
1871                 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1872                         + " [" + wakeLock.mTag + "]");
1873             }
1874 
1875             int index = mWakeLocks.indexOf(wakeLock);
1876             if (index < 0) {
1877                 return;
1878             }
1879 
1880             removeWakeLockDeathLocked(wakeLock, index);
1881         }
1882     }
1883 
1884     @GuardedBy("mLock")
1885     private void removeWakeLockNoUpdateLocked(WakeLock wakeLock, int index) {
1886         removeWakeLockNoUpdateLocked(wakeLock, index,
1887                 ScreenTimeoutOverridePolicy.RELEASE_REASON_UNKNOWN);
1888     }
1889 
1890     @GuardedBy("mLock")
1891     private void removeWakeLockNoUpdateLocked(WakeLock wakeLock, int index, int releaseReason) {
1892         mWakeLocks.remove(index);
1893         UidState state = wakeLock.mUidState;
1894         state.mNumWakeLocks--;
1895         if (state.mNumWakeLocks <= 0 &&
1896                 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1897             mUidState.remove(state.mUid);
1898         }
1899 
1900         notifyWakeLockReleasedLocked(wakeLock, releaseReason);
1901         applyWakeLockFlagsOnReleaseLocked(wakeLock);
1902         mDirty |= DIRTY_WAKE_LOCKS;
1903     }
1904 
1905     @GuardedBy("mLock")
1906     private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1907         removeWakeLockNoUpdateLocked(wakeLock, index);
1908         updatePowerStateLocked();
1909     }
1910 
1911     @GuardedBy("mLock")
1912     private void removeWakeLockDeathLocked(WakeLock wakeLock, int index) {
1913         removeWakeLockNoUpdateLocked(wakeLock, index, RELEASE_REASON_WAKE_LOCK_DEATH);
1914         updatePowerStateLocked();
1915     }
1916 
1917     @GuardedBy("mLock")
1918     private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
1919         if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1920                 && isScreenLock(wakeLock)) {
1921             userActivityNoUpdateLocked(mClock.uptimeMillis(),
1922                     PowerManager.USER_ACTIVITY_EVENT_OTHER,
1923                     PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1924                     wakeLock.mOwnerUid);
1925         }
1926     }
1927 
1928     private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1929             int callingUid) {
1930         synchronized (mLock) {
1931             int index = findWakeLockIndexLocked(lock);
1932             if (index < 0) {
1933                 if (DEBUG_SPEW) {
1934                     Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1935                             + " [not found], ws=" + ws);
1936                 }
1937                 throw new IllegalArgumentException("Wake lock not active: " + lock
1938                         + " from uid " + callingUid);
1939             }
1940 
1941             WakeLock wakeLock = mWakeLocks.get(index);
1942             if (DEBUG_SPEW) {
1943                 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1944                         + " [" + wakeLock.mTag + "], ws=" + ws);
1945             }
1946 
1947             if (!wakeLock.hasSameWorkSource(ws)) {
1948                 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1949                         wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1950                         ws, historyTag, null);
1951                 wakeLock.mHistoryTag = historyTag;
1952                 wakeLock.updateWorkSource(ws);
1953             }
1954         }
1955     }
1956 
1957     private void updateWakeLockCallbackInternal(IBinder lock, IWakeLockCallback callback,
1958             int callingUid) {
1959         synchronized (mLock) {
1960             int index = findWakeLockIndexLocked(lock);
1961             if (index < 0) {
1962                 if (DEBUG_SPEW) {
1963                     Slog.d(TAG, "updateWakeLockCallbackInternal: lock=" + Objects.hashCode(lock)
1964                             + " [not found]");
1965                 }
1966                 throw new IllegalArgumentException("Wake lock not active: " + lock
1967                         + " from uid " + callingUid);
1968             }
1969 
1970             WakeLock wakeLock = mWakeLocks.get(index);
1971             if (DEBUG_SPEW) {
1972                 Slog.d(TAG, "updateWakeLockCallbackInternal: lock=" + Objects.hashCode(lock)
1973                         + " [" + wakeLock.mTag + "]");
1974             }
1975 
1976             if (!isSameCallback(callback, wakeLock.mCallback)) {
1977                 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1978                         wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1979                         wakeLock.mWorkSource, wakeLock.mHistoryTag, callback);
1980                 wakeLock.mCallback = callback;
1981             }
1982         }
1983     }
1984 
1985     @GuardedBy("mLock")
1986     private int findWakeLockIndexLocked(IBinder lock) {
1987         final int count = mWakeLocks.size();
1988         for (int i = 0; i < count; i++) {
1989             if (mWakeLocks.get(i).mLock == lock) {
1990                 return i;
1991             }
1992         }
1993         return -1;
1994     }
1995 
1996     @GuardedBy("mLock")
1997     @VisibleForTesting
1998     WakeLock findWakeLockLocked(IBinder lock) {
1999         int index = findWakeLockIndexLocked(lock);
2000         if (index == -1) {
2001             return null;
2002         }
2003         return mWakeLocks.get(index);
2004     }
2005 
2006     @GuardedBy("mLock")
2007     private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
2008         if (mSystemReady && !wakeLock.mDisabled) {
2009             wakeLock.mNotifiedAcquired = true;
2010             mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
2011                     wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
2012                     wakeLock.mHistoryTag, wakeLock.mCallback);
2013             restartNofifyLongTimerLocked(wakeLock);
2014         }
2015     }
2016 
2017     @GuardedBy("mLock")
2018     private void enqueueNotifyLongMsgLocked(long time) {
2019         mNotifyLongScheduled = time;
2020         Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
2021         msg.setAsynchronous(true);
2022         mHandler.sendMessageAtTime(msg, time);
2023     }
2024 
2025     @GuardedBy("mLock")
2026     private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
2027         wakeLock.mAcquireTime = mClock.uptimeMillis();
2028         if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
2029                 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
2030             enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
2031         }
2032     }
2033 
2034     @GuardedBy("mLock")
2035     private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
2036         if (mSystemReady && !wakeLock.mDisabled) {
2037             wakeLock.mNotifiedLong = true;
2038             mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
2039                     wakeLock.mWorkSource, wakeLock.mHistoryTag);
2040         }
2041     }
2042 
2043     @GuardedBy("mLock")
2044     private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
2045         if (wakeLock.mNotifiedLong) {
2046             wakeLock.mNotifiedLong = false;
2047             mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
2048                     wakeLock.mWorkSource, wakeLock.mHistoryTag);
2049         }
2050     }
2051 
2052     @GuardedBy("mLock")
2053     private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
2054             String packageName, int uid, int pid, WorkSource ws, String historyTag,
2055             IWakeLockCallback callback) {
2056         if (mSystemReady && wakeLock.mNotifiedAcquired) {
2057             mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
2058                     wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
2059                     wakeLock.mHistoryTag, wakeLock.mCallback, flags, tag, packageName, uid, pid, ws,
2060                     historyTag, callback);
2061             notifyWakeLockLongFinishedLocked(wakeLock);
2062             // Changing the wake lock will count as releasing the old wake lock(s) and
2063             // acquiring the new ones...  we do this because otherwise once a wakelock
2064             // becomes long, if we just continued to treat it as long we can get in to
2065             // situations where we spam battery stats with every following change to it.
2066             restartNofifyLongTimerLocked(wakeLock);
2067         }
2068     }
2069 
2070     @GuardedBy("mLock")
2071     private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
2072         notifyWakeLockReleasedLocked(wakeLock, RELEASE_REASON_UNKNOWN);
2073     }
2074 
2075     @GuardedBy("mLock")
2076     private void notifyWakeLockReleasedLocked(WakeLock wakeLock, int releaseReason) {
2077         if (mSystemReady && wakeLock.mNotifiedAcquired) {
2078             wakeLock.mNotifiedAcquired = false;
2079             wakeLock.mAcquireTime = 0;
2080             mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
2081                     wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
2082                     wakeLock.mWorkSource, wakeLock.mHistoryTag, wakeLock.mCallback, releaseReason);
2083             notifyWakeLockLongFinishedLocked(wakeLock);
2084         }
2085     }
2086 
2087     @SuppressWarnings("deprecation")
2088     private boolean isWakeLockLevelSupportedInternal(int level, int displayId) {
2089         synchronized (mLock) {
2090             switch (level) {
2091                 case PowerManager.PARTIAL_WAKE_LOCK:
2092                 case PowerManager.SCREEN_DIM_WAKE_LOCK:
2093                 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2094                 case PowerManager.FULL_WAKE_LOCK:
2095                 case PowerManager.DOZE_WAKE_LOCK:
2096                 case PowerManager.DRAW_WAKE_LOCK:
2097                     return true;
2098 
2099                 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2100                     return mSystemReady
2101                             && mDisplayManagerInternal.isProximitySensorAvailable(displayId);
2102                 case PowerManager.SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK:
2103                     return mSystemReady && mFeatureFlags.isEarlyScreenTimeoutDetectorEnabled()
2104                             && mScreenTimeoutOverridePolicy != null;
2105                 default:
2106                     return false;
2107             }
2108         }
2109     }
2110 
2111     // Called from native code.
2112     @SuppressWarnings("unused")
2113     private void userActivityFromNative(long eventTime, @PowerManager.UserActivityEvent int event,
2114             int displayId, int flags) {
2115         userActivityInternal(displayId, eventTime, event, flags, Process.SYSTEM_UID);
2116     }
2117 
2118     private void userActivityInternal(int displayId, long eventTime,
2119             @PowerManager.UserActivityEvent int event, int flags, int uid) {
2120         synchronized (mLock) {
2121             if (displayId == Display.INVALID_DISPLAY) {
2122                 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
2123                     updatePowerStateLocked();
2124                 }
2125                 return;
2126             }
2127 
2128             final DisplayInfo displayInfo = mDisplayManagerInternal.getDisplayInfo(displayId);
2129             if (displayInfo == null) {
2130                 return;
2131             }
2132             final int groupId = displayInfo.displayGroupId;
2133             if (groupId == Display.INVALID_DISPLAY_GROUP) {
2134                 return;
2135             }
2136             if (userActivityNoUpdateLocked(mPowerGroups.get(groupId), eventTime, event, flags,
2137                     uid)) {
2138                 updatePowerStateLocked();
2139             }
2140         }
2141     }
2142 
2143     private void napInternal(long eventTime, int uid, boolean allowWake) {
2144         synchronized (mLock) {
2145             dreamPowerGroupLocked(mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP),
2146                     eventTime, uid, allowWake);
2147         }
2148     }
2149 
2150     private void onUserAttention() {
2151         synchronized (mLock) {
2152             if (userActivityNoUpdateLocked(mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP),
2153                     mClock.uptimeMillis(),
2154                     PowerManager.USER_ACTIVITY_EVENT_ATTENTION,
2155                     /* flags= */ 0,
2156                     Process.SYSTEM_UID)) {
2157                 updatePowerStateLocked();
2158             }
2159         }
2160     }
2161 
2162     @GuardedBy("mLock")
2163     private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
2164         boolean updatePowerState = false;
2165         for (int idx = 0; idx < mPowerGroups.size(); idx++) {
2166             if (userActivityNoUpdateLocked(mPowerGroups.valueAt(idx), eventTime, event, flags,
2167                     uid)) {
2168                 updatePowerState = true;
2169             }
2170         }
2171 
2172         return updatePowerState;
2173     }
2174 
2175     @GuardedBy("mLock")
2176     private boolean userActivityNoUpdateLocked(final PowerGroup powerGroup, long eventTime,
2177             @PowerManager.UserActivityEvent int event, int flags, int uid) {
2178         final int groupId = powerGroup.getGroupId();
2179         if (DEBUG_SPEW) {
2180             Slog.d(TAG, "userActivityNoUpdateLocked: groupId=" + groupId
2181                     + ", eventTime=" + eventTime
2182                     + ", event=" + PowerManager.userActivityEventToString(event)
2183                     + ", flags=0x" + Integer.toHexString(flags) + ", uid=" + uid);
2184         }
2185 
2186         if (eventTime < powerGroup.getLastSleepTimeLocked()
2187                 || eventTime < powerGroup.getLastWakeTimeLocked() || !mSystemReady) {
2188             return false;
2189         }
2190 
2191         Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
2192         try {
2193             if (eventTime > mLastInteractivePowerHintTime) {
2194                 setPowerBoostInternal(Boost.INTERACTION, 0);
2195                 mLastInteractivePowerHintTime = eventTime;
2196             }
2197 
2198             mNotifier.onUserActivity(powerGroup.getGroupId(), event, uid);
2199             mAttentionDetector.onUserActivity(eventTime, event);
2200 
2201             if (mScreenTimeoutOverridePolicy != null) {
2202                 mScreenTimeoutOverridePolicy.onUserActivity(mWakeLockSummary, event);
2203             }
2204 
2205             if (mUserInactiveOverrideFromWindowManager) {
2206                 mUserInactiveOverrideFromWindowManager = false;
2207                 mOverriddenTimeout = -1;
2208             }
2209             final int wakefulness = powerGroup.getWakefulnessLocked();
2210             if (wakefulness == WAKEFULNESS_ASLEEP
2211                     || wakefulness == WAKEFULNESS_DOZING
2212                     || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
2213                 return false;
2214             }
2215 
2216             maybeUpdateForegroundProfileLastActivityLocked(eventTime);
2217 
2218             if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
2219                 if (eventTime > powerGroup.getLastUserActivityTimeNoChangeLightsLocked()
2220                         && eventTime > powerGroup.getLastUserActivityTimeLocked()) {
2221                     powerGroup.setLastUserActivityTimeNoChangeLightsLocked(eventTime, event);
2222                     mDirty |= DIRTY_USER_ACTIVITY;
2223                     if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
2224                         mDirty |= DIRTY_QUIESCENT;
2225                     }
2226 
2227                     return true;
2228                 }
2229             } else {
2230                 if (eventTime > powerGroup.getLastUserActivityTimeLocked()) {
2231                     powerGroup.setLastUserActivityTimeLocked(eventTime, event);
2232                     mDirty |= DIRTY_USER_ACTIVITY;
2233                     if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
2234                         mDirty |= DIRTY_QUIESCENT;
2235                     }
2236                     return true;
2237                 }
2238             }
2239         } finally {
2240             Trace.traceEnd(Trace.TRACE_TAG_POWER);
2241         }
2242         return false;
2243     }
2244 
2245     @GuardedBy("mLock")
2246     private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
2247         final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
2248         if (profile != null && eventTime > profile.mLastUserActivityTime) {
2249             profile.mLastUserActivityTime = eventTime;
2250         }
2251     }
2252 
2253     @GuardedBy("mLock")
2254     private void wakePowerGroupLocked(final PowerGroup powerGroup, long eventTime,
2255             @WakeReason int reason, String details, int uid, String opPackageName, int opUid) {
2256         if (DEBUG_SPEW) {
2257             Slog.d(TAG, "wakePowerGroupLocked: eventTime=" + eventTime
2258                     + ", groupId=" + powerGroup.getGroupId()
2259                     + ", reason=" + PowerManager.wakeReasonToString(reason) + ", uid=" + uid);
2260         }
2261         if (mForceSuspendActive || !mSystemReady || (powerGroup == null)) {
2262             return;
2263         }
2264         powerGroup.wakeUpLocked(eventTime, reason, details, uid, opPackageName, opUid,
2265                 LatencyTracker.getInstance(mContext));
2266     }
2267 
2268     @GuardedBy("mLock")
2269     private boolean dreamPowerGroupLocked(PowerGroup powerGroup, long eventTime, int uid,
2270             boolean allowWake) {
2271         if (DEBUG_SPEW) {
2272             Slog.d(TAG, "dreamPowerGroup: groupId=" + powerGroup.getGroupId() + ", eventTime="
2273                     + eventTime + ", uid=" + uid);
2274         }
2275         if (!mBootCompleted || !mSystemReady) {
2276             return false;
2277         }
2278         return powerGroup.dreamLocked(eventTime, uid, allowWake);
2279     }
2280 
2281     @GuardedBy("mLock")
2282     private boolean dozePowerGroupLocked(final PowerGroup powerGroup, long eventTime,
2283             @GoToSleepReason int reason, int uid) {
2284         if (DEBUG_SPEW) {
2285             Slog.d(TAG, "dozePowerGroup: eventTime=" + eventTime
2286                     + ", groupId=" + powerGroup.getGroupId()
2287                     + ", reason=" + PowerManager.sleepReasonToString(reason) + ", uid=" + uid);
2288         }
2289 
2290         if (!mSystemReady || !mBootCompleted) {
2291             return false;
2292         }
2293 
2294         return powerGroup.dozeLocked(eventTime, uid, reason);
2295     }
2296 
2297     @GuardedBy("mLock")
2298     private boolean sleepPowerGroupLocked(final PowerGroup powerGroup, long eventTime,
2299             @GoToSleepReason int reason, int uid) {
2300         if (DEBUG_SPEW) {
2301             Slog.d(TAG, "sleepPowerGroup: eventTime=" + eventTime
2302                     + ", groupId=" + powerGroup.getGroupId()
2303                     + ", reason=" + PowerManager.sleepReasonToString(reason) + ", uid=" + uid);
2304         }
2305         if (!mBootCompleted || !mSystemReady) {
2306             return false;
2307         }
2308 
2309         return powerGroup.sleepLocked(eventTime, uid, reason);
2310     }
2311 
2312     @VisibleForTesting
2313     @GuardedBy("mLock")
2314     void setWakefulnessLocked(int groupId, int wakefulness, long eventTime, int uid, int reason,
2315             int opUid, String opPackageName, String details) {
2316         mPowerGroups.get(groupId).setWakefulnessLocked(wakefulness, eventTime, uid, reason, opUid,
2317                 opPackageName, details);
2318     }
2319 
2320     @SuppressWarnings("deprecation")
2321     @GuardedBy("mLock")
2322     private void updateGlobalWakefulnessLocked(long eventTime, int reason, int uid,
2323             int opUid, String opPackageName, String details) {
2324         int newWakefulness = recalculateGlobalWakefulnessLocked();
2325         int currentWakefulness = getGlobalWakefulnessLocked();
2326         if (currentWakefulness == newWakefulness) {
2327             return;
2328         }
2329 
2330         // Phase 1: Handle pre-wakefulness change bookkeeping.
2331         final String traceMethodName;
2332         switch (newWakefulness) {
2333             case WAKEFULNESS_ASLEEP:
2334                 traceMethodName = "reallyGoToSleep";
2335                 Slog.i(TAG, "Sleeping (uid " + uid + ")...");
2336                 // TODO(b/215518989): Remove this once transactions are in place
2337                 if (currentWakefulness != WAKEFULNESS_DOZING) {
2338                     // in case we are going to sleep without dozing before
2339                     mLastGlobalSleepTime = eventTime;
2340                     mLastGlobalSleepReason = reason;
2341                 }
2342                 break;
2343 
2344             case WAKEFULNESS_AWAKE:
2345                 traceMethodName = "wakeUp";
2346                 Slog.i(TAG, "Waking up from "
2347                         + PowerManagerInternal.wakefulnessToString(currentWakefulness)
2348                         + " (uid=" + uid
2349                         + ", reason=" + PowerManager.wakeReasonToString(reason)
2350                         + ", details=" + details
2351                         + ")...");
2352                 mLastGlobalWakeTime = eventTime;
2353                 mLastGlobalWakeReason = reason;
2354                 mLastGlobalWakeTimeRealtime = mClock.elapsedRealtime();
2355                 break;
2356 
2357             case WAKEFULNESS_DREAMING:
2358                 traceMethodName = "nap";
2359                 Slog.i(TAG, "Nap time (uid " + uid + ")...");
2360                 break;
2361 
2362             case WAKEFULNESS_DOZING:
2363                 traceMethodName = "goToSleep";
2364                 Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
2365                         + " (uid " + uid + ", screenOffTimeout=" + mScreenOffTimeoutSetting
2366                         + ", activityTimeoutWM=" + mUserActivityTimeoutOverrideFromWindowManager
2367                         + ", maxDimRatio=" + mMaximumScreenDimRatioConfig
2368                         + ", maxDimDur=" + mMaximumScreenDimDurationConfig + ")...");
2369                 mLastGlobalSleepTime = eventTime;
2370                 mLastGlobalSleepReason = reason;
2371                 mLastGlobalSleepTimeRealtime = mClock.elapsedRealtime();
2372                 mDozeStartInProgress = true;
2373                 break;
2374 
2375             default:
2376                 throw new IllegalArgumentException("Unexpected wakefulness: " + newWakefulness);
2377         }
2378 
2379         Trace.traceBegin(Trace.TRACE_TAG_POWER, traceMethodName);
2380         try {
2381             // Phase 2: Handle wakefulness change and bookkeeping.
2382             // Under lock, invalidate before set ensures caches won't return stale values.
2383             mInjector.invalidateIsInteractiveCaches();
2384             mWakefulnessRaw = newWakefulness;
2385             mWakefulnessChanging = true;
2386             mDirty |= DIRTY_WAKEFULNESS;
2387 
2388             // This is only valid while we are in wakefulness dozing. Set to false otherwise.
2389             mDozeStartInProgress &= (newWakefulness == WAKEFULNESS_DOZING);
2390 
2391             if (mNotifier != null) {
2392                 mNotifier.onGlobalWakefulnessChangeStarted(newWakefulness, reason, eventTime);
2393             }
2394             mAttentionDetector.onWakefulnessChangeStarted(newWakefulness);
2395 
2396             // Phase 3: Handle post-wakefulness change bookkeeping.
2397             switch (newWakefulness) {
2398                 case WAKEFULNESS_AWAKE:
2399                     mNotifier.onWakeUp(reason, details, uid, opPackageName, opUid);
2400                     if (sQuiescent) {
2401                         mDirty |= DIRTY_QUIESCENT;
2402                     }
2403                     break;
2404 
2405                 case WAKEFULNESS_ASLEEP:
2406                     // fallthrough
2407                 case WAKEFULNESS_DOZING:
2408                     if (!isInteractive(currentWakefulness)) {
2409                         // TODO(b/215518989): remove this once transactions are in place
2410                         break;
2411                     }
2412                     // Report the number of wake locks that will be cleared by going to sleep.
2413                     int numWakeLocksCleared = 0;
2414                     final int numWakeLocks = mWakeLocks.size();
2415                     for (int i = 0; i < numWakeLocks; i++) {
2416                         final WakeLock wakeLock = mWakeLocks.get(i);
2417                         switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2418                             case PowerManager.FULL_WAKE_LOCK:
2419                             case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2420                             case PowerManager.SCREEN_DIM_WAKE_LOCK:
2421                                 numWakeLocksCleared += 1;
2422                                 break;
2423                         }
2424                     }
2425                     EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
2426                     break;
2427             }
2428         } finally {
2429             Trace.traceEnd(Trace.TRACE_TAG_POWER);
2430         }
2431     }
2432 
2433     @VisibleForTesting
2434     @GuardedBy("mLock")
2435     int getGlobalWakefulnessLocked() {
2436         return mWakefulnessRaw;
2437     }
2438 
2439     @VisibleForTesting
2440     @GuardedBy("mLock")
2441     int getWakefulnessLocked(int groupId) {
2442         return mPowerGroups.get(groupId).getWakefulnessLocked();
2443     }
2444 
2445     /**
2446      * Returns the amalgamated wakefulness of all {@link PowerGroup PowerGroups}.
2447      *
2448      * <p>This will be the highest wakeful state of all {@link PowerGroup PowerGroups}; ordered
2449      * from highest to lowest:
2450      * <ol>
2451      *     <li>{@link PowerManagerInternal#WAKEFULNESS_AWAKE}
2452      *     <li>{@link PowerManagerInternal#WAKEFULNESS_DREAMING}
2453      *     <li>{@link PowerManagerInternal#WAKEFULNESS_DOZING}
2454      *     <li>{@link PowerManagerInternal#WAKEFULNESS_ASLEEP}
2455      * </ol>
2456      */
2457     @GuardedBy("mLock")
2458     int recalculateGlobalWakefulnessLocked() {
2459         int deviceWakefulness = WAKEFULNESS_ASLEEP;
2460         for (int i = 0; i < mPowerGroups.size(); i++) {
2461             final int wakefulness = mPowerGroups.valueAt(i).getWakefulnessLocked();
2462             if (wakefulness == WAKEFULNESS_AWAKE) {
2463                 return WAKEFULNESS_AWAKE;
2464             } else if (wakefulness == WAKEFULNESS_DREAMING
2465                     && (deviceWakefulness == WAKEFULNESS_ASLEEP
2466                     || deviceWakefulness == WAKEFULNESS_DOZING)) {
2467                 deviceWakefulness = WAKEFULNESS_DREAMING;
2468             } else if (wakefulness == WAKEFULNESS_DOZING
2469                     && deviceWakefulness == WAKEFULNESS_ASLEEP) {
2470                 deviceWakefulness = WAKEFULNESS_DOZING;
2471             }
2472         }
2473 
2474         return deviceWakefulness;
2475     }
2476 
2477     @GuardedBy("mLock")
2478     void onPowerGroupEventLocked(int event, PowerGroup powerGroup) {
2479         mWakefulnessChanging = true;
2480         mDirty |= DIRTY_WAKEFULNESS;
2481         final int groupId = powerGroup.getGroupId();
2482         if (event == DisplayGroupPowerChangeListener.DISPLAY_GROUP_REMOVED) {
2483             mPowerGroups.delete(groupId);
2484         }
2485         final int oldWakefulness = getGlobalWakefulnessLocked();
2486         final int newWakefulness = recalculateGlobalWakefulnessLocked();
2487 
2488         if (event == DisplayGroupPowerChangeListener.DISPLAY_GROUP_ADDED
2489                 && newWakefulness == WAKEFULNESS_AWAKE) {
2490             // Kick user activity to prevent newly added group from timing out instantly.
2491             userActivityNoUpdateLocked(powerGroup, mClock.uptimeMillis(),
2492                     PowerManager.USER_ACTIVITY_EVENT_OTHER, /* flags= */ 0, Process.SYSTEM_UID);
2493             mNotifier.onGroupWakefulnessChangeStarted(groupId,
2494                     powerGroup.getWakefulnessLocked(), WAKE_REASON_DISPLAY_GROUP_ADDED,
2495                     mClock.uptimeMillis());
2496         } else if (event == DisplayGroupPowerChangeListener.DISPLAY_GROUP_REMOVED) {
2497             mNotifier.onGroupRemoved(groupId);
2498         } else if (event == DisplayGroupPowerChangeListener.DISPLAY_GROUP_CHANGED) {
2499             mNotifier.onGroupChanged();
2500         }
2501 
2502         if (oldWakefulness != newWakefulness) {
2503             final int reason;
2504             switch (newWakefulness) {
2505                 case WAKEFULNESS_AWAKE:
2506                     reason = event == DisplayGroupPowerChangeListener.DISPLAY_GROUP_ADDED
2507                             ? WAKE_REASON_DISPLAY_GROUP_ADDED
2508                             : WAKE_REASON_DISPLAY_GROUP_TURNED_ON;
2509                     break;
2510                 case WAKEFULNESS_DOZING:
2511                     reason = event == DisplayGroupPowerChangeListener.DISPLAY_GROUP_REMOVED
2512                             ? GO_TO_SLEEP_REASON_DISPLAY_GROUP_REMOVED
2513                             : GO_TO_SLEEP_REASON_DISPLAY_GROUPS_TURNED_OFF;
2514                     break;
2515                 default:
2516                     reason = 0;
2517             }
2518             updateGlobalWakefulnessLocked(mClock.uptimeMillis(), reason, Process.SYSTEM_UID,
2519                     Process.SYSTEM_UID, mContext.getOpPackageName(), "groupId: " + groupId);
2520         }
2521         mDirty |= DIRTY_DISPLAY_GROUP_WAKEFULNESS;
2522         updatePowerStateLocked();
2523     }
2524 
2525     /**
2526      * Logs the time the device would have spent awake before user activity timeout,
2527      * had the system not been told the user was inactive.
2528      */
2529     @GuardedBy("mLock")
2530     private void logSleepTimeoutRecapturedLocked() {
2531         final long now = mClock.uptimeMillis();
2532         final long savedWakeTimeMs = mOverriddenTimeout - now;
2533         if (savedWakeTimeMs >= 0) {
2534             EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
2535             mOverriddenTimeout = -1;
2536         }
2537     }
2538 
2539     @GuardedBy("mLock")
2540     private void finishWakefulnessChangeIfNeededLocked() {
2541         if (mWakefulnessChanging && areAllPowerGroupsReadyLocked()) {
2542             if (getGlobalWakefulnessLocked() == WAKEFULNESS_DOZING
2543                     && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
2544                 return; // wait until dream has enabled dozing
2545             } else {
2546                 // Doze wakelock acquired (doze started) or device is no longer dozing.
2547                 mDozeStartInProgress = false;
2548             }
2549             if (getGlobalWakefulnessLocked() == WAKEFULNESS_DOZING
2550                     || getGlobalWakefulnessLocked() == WAKEFULNESS_ASLEEP) {
2551                 logSleepTimeoutRecapturedLocked();
2552             }
2553             mWakefulnessChanging = false;
2554             mNotifier.onWakefulnessChangeFinished();
2555         }
2556     }
2557 
2558     /**
2559      * Returns {@code true} if all {@link PowerGroup}s are ready, i.e. every display has its
2560      * requested state matching its actual state.
2561      */
2562     @GuardedBy("mLock")
2563     private boolean areAllPowerGroupsReadyLocked() {
2564         final int size = mPowerGroups.size();
2565         for (int i = 0; i < size; i++) {
2566             if (!mPowerGroups.valueAt(i).isReadyLocked()) {
2567                 return false;
2568             }
2569         }
2570 
2571         return true;
2572     }
2573 
2574     /**
2575      * Updates the global power state based on dirty bits recorded in mDirty.
2576      *
2577      * This is the main function that performs power state transitions.
2578      * We centralize them here so that we can recompute the power state completely
2579      * each time something important changes, and ensure that we do it the same
2580      * way each time.  The point is to gather all of the transition logic here.
2581      */
2582     @GuardedBy("mLock")
2583     private void updatePowerStateLocked() {
2584         if (!mSystemReady || mDirty == 0 || mUpdatePowerStateInProgress) {
2585             return;
2586         }
2587         if (!Thread.holdsLock(mLock)) {
2588             Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
2589         }
2590 
2591         Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
2592         mUpdatePowerStateInProgress = true;
2593         try {
2594             // Phase 0: Basic state updates.
2595             updateIsPoweredLocked(mDirty);
2596             updateStayOnLocked(mDirty);
2597             updateScreenBrightnessBoostLocked(mDirty);
2598 
2599             // Phase 1: Update wakefulness.
2600             // Loop because the wake lock and user activity computations are influenced
2601             // by changes in wakefulness.
2602             final long now = mClock.uptimeMillis();
2603             int dirtyPhase2 = 0;
2604             for (;;) {
2605                 int dirtyPhase1 = mDirty;
2606                 dirtyPhase2 |= dirtyPhase1;
2607                 mDirty = 0;
2608 
2609                 updateWakeLockSummaryLocked(dirtyPhase1);
2610                 updateUserActivitySummaryLocked(now, dirtyPhase1);
2611                 updateAttentiveStateLocked(now, dirtyPhase1);
2612                 if (!updateWakefulnessLocked(dirtyPhase1)) {
2613                     break;
2614                 }
2615             }
2616 
2617             // Phase 2: Lock profiles that became inactive/not kept awake.
2618             updateProfilesLocked(now);
2619 
2620             // Phase 3: Update power state of all PowerGroups.
2621             final boolean powerGroupsBecameReady = updatePowerGroupsLocked(dirtyPhase2);
2622 
2623             // Phase 4: Update dream state (depends on power group ready signal).
2624             updateDreamLocked(dirtyPhase2, powerGroupsBecameReady);
2625 
2626             // Phase 5: Send notifications, if needed.
2627             finishWakefulnessChangeIfNeededLocked();
2628 
2629             // Phase 6: Notify screen timeout policy changes if needed
2630             notifyScreenTimeoutPolicyChangesLocked();
2631 
2632             // Phase 7: Update suspend blocker.
2633             // Because we might release the last suspend blocker here, we need to make sure
2634             // we finished everything else first!
2635             updateSuspendBlockerLocked();
2636         } finally {
2637             Trace.traceEnd(Trace.TRACE_TAG_POWER);
2638             mUpdatePowerStateInProgress = false;
2639         }
2640     }
2641 
2642     /**
2643      * Check profile timeouts and notify profiles that should be locked.
2644      */
2645     @GuardedBy("mLock")
2646     private void updateProfilesLocked(long now) {
2647         final int numProfiles = mProfilePowerState.size();
2648         for (int i = 0; i < numProfiles; i++) {
2649             final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2650             if (isProfileBeingKeptAwakeLocked(profile, now)) {
2651                 profile.mLockingNotified = false;
2652             } else if (!profile.mLockingNotified) {
2653                 profile.mLockingNotified = true;
2654                 mNotifier.onProfileTimeout(profile.mUserId);
2655             }
2656         }
2657     }
2658 
2659     @GuardedBy("mLock")
2660     private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
2661         return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
2662                 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
2663                 || (mProximityPositive &&
2664                     (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
2665     }
2666 
2667     /**
2668      * Updates the value of mIsPowered.
2669      * Sets DIRTY_IS_POWERED if a change occurred.
2670      */
2671     @GuardedBy("mLock")
2672     private void updateIsPoweredLocked(int dirty) {
2673         if ((dirty & DIRTY_BATTERY_STATE) != 0) {
2674             final boolean wasPowered = mIsPowered;
2675             final int oldPlugType = mPlugType;
2676             mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
2677             mPlugType = mBatteryManagerInternal.getPlugType();
2678             final int oldBatteryLevel = mBatteryLevel;
2679             mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
2680             mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
2681             final boolean isOverheat = mBatteryManagerInternal.getBatteryHealth()
2682                     == BatteryManager.BATTERY_HEALTH_OVERHEAT;
2683 
2684             if (DEBUG_SPEW) {
2685                 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
2686                         + ", mIsPowered=" + mIsPowered
2687                         + ", oldPlugType=" + oldPlugType
2688                         + ", mPlugType=" + mPlugType
2689                         + ", oldBatteryLevel=" + oldBatteryLevel
2690                         + ", mBatteryLevel=" + mBatteryLevel
2691                         + ", isOverheat=" + isOverheat);
2692             }
2693 
2694             if (!isOverheat && oldBatteryLevel > 0
2695                     && getGlobalWakefulnessLocked() == WAKEFULNESS_DREAMING) {
2696                 mDreamsBatteryLevelDrain += (oldBatteryLevel - mBatteryLevel);
2697             }
2698 
2699             if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
2700                 mDirty |= DIRTY_IS_POWERED;
2701 
2702                 // Update wireless dock detection state.
2703                 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
2704                         mIsPowered, mPlugType);
2705 
2706                 // Treat plugging and unplugging the devices as a user activity.
2707                 // Users find it disconcerting when they plug or unplug the device
2708                 // and it shuts off right away.
2709                 // Some devices also wake the device when plugged or unplugged because
2710                 // they don't have a charging LED.
2711                 final long now = mClock.uptimeMillis();
2712                 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
2713                         dockedOnWirelessCharger)) {
2714                     wakePowerGroupLocked(mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP),
2715                             now, PowerManager.WAKE_REASON_PLUGGED_IN,
2716                             "android.server.power:PLUGGED:" + mIsPowered, Process.SYSTEM_UID,
2717                             mContext.getOpPackageName(), Process.SYSTEM_UID);
2718                 }
2719 
2720                 userActivityNoUpdateLocked(mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP), now,
2721                         PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2722 
2723                 // only play charging sounds if boot is completed so charging sounds don't play
2724                 // with potential notification sounds
2725                 if (mBootCompleted) {
2726                     if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
2727                             && BatteryManager.isPlugWired(mPlugType)) {
2728                         mNotifier.onWiredChargingStarted(mUserId);
2729                     } else if (dockedOnWirelessCharger) {
2730                         mNotifier.onWirelessChargingStarted(mBatteryLevel, mUserId);
2731                     }
2732                 }
2733             }
2734 
2735             if (mBatterySaverSupported) {
2736                 mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel,
2737                         mBatteryLevelLow);
2738             }
2739         }
2740     }
2741 
2742     @GuardedBy("mLock")
2743     private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
2744             boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
2745         // Don't wake when powered unless configured to do so.
2746         if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
2747             return false;
2748         }
2749 
2750         // Don't wake when unplugging while dreaming if configured not to.
2751         if (mKeepDreamingWhenUnplugging
2752                 && getGlobalWakefulnessLocked() == WAKEFULNESS_DREAMING
2753                 && wasPowered && !mIsPowered) {
2754             return false;
2755         }
2756         // Don't wake when undocked from wireless charger.
2757         // See WirelessChargerDetector for justification.
2758         if (wasPowered && !mIsPowered
2759                 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
2760             return false;
2761         }
2762 
2763         // Don't wake when docked on wireless charger unless we are certain of it.
2764         // See WirelessChargerDetector for justification.
2765         if (!wasPowered && mIsPowered
2766                 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
2767                 && !dockedOnWirelessCharger) {
2768             return false;
2769         }
2770 
2771         // If already dreaming and becoming powered, then don't wake.
2772         if (mIsPowered && getGlobalWakefulnessLocked() == WAKEFULNESS_DREAMING) {
2773             return false;
2774         }
2775 
2776         // Don't wake while theater mode is enabled.
2777         if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
2778             return false;
2779         }
2780 
2781         // On Always On Display, SystemUI shows the charging indicator
2782         if (mAlwaysOnEnabled && getGlobalWakefulnessLocked() == WAKEFULNESS_DOZING) {
2783             return false;
2784         }
2785 
2786         // Otherwise wake up!
2787         return true;
2788     }
2789 
2790     /**
2791      * Updates the value of mStayOn.
2792      * Sets DIRTY_STAY_ON if a change occurred.
2793      */
2794     @GuardedBy("mLock")
2795     private void updateStayOnLocked(int dirty) {
2796         if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
2797             final boolean wasStayOn = mStayOn;
2798             if (mStayOnWhilePluggedInSetting != 0
2799                     && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2800                 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
2801             } else {
2802                 mStayOn = false;
2803             }
2804 
2805             if (mStayOn != wasStayOn) {
2806                 mDirty |= DIRTY_STAY_ON;
2807             }
2808         }
2809     }
2810 
2811     /**
2812      * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
2813      * Note that most wake-locks are ignored when the system is asleep.
2814      *
2815      * This function must have no other side effects.
2816      */
2817     @GuardedBy("mLock")
2818     private void updateWakeLockSummaryLocked(int dirty) {
2819         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS | DIRTY_DISPLAY_GROUP_WAKEFULNESS))
2820                 != 0) {
2821 
2822             mWakeLockSummary = 0;
2823 
2824             final int numProfiles = mProfilePowerState.size();
2825             for (int i = 0; i < numProfiles; i++) {
2826                 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
2827             }
2828 
2829             for (int idx = 0; idx < mPowerGroups.size(); idx++) {
2830                 mPowerGroups.valueAt(idx).setWakeLockSummaryLocked(0);
2831             }
2832 
2833             int invalidGroupWakeLockSummary = 0;
2834             final int numWakeLocks = mWakeLocks.size();
2835             for (int i = 0; i < numWakeLocks; i++) {
2836                 final WakeLock wakeLock = mWakeLocks.get(i);
2837                 final Integer groupId = wakeLock.getPowerGroupId();
2838                 // a wakelock with an invalid group ID should affect all groups
2839                 if (groupId == null || (groupId != Display.INVALID_DISPLAY_GROUP
2840                         && !mPowerGroups.contains(groupId))) {
2841                     continue;
2842                 }
2843 
2844                 final PowerGroup powerGroup = mPowerGroups.get(groupId);
2845                 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
2846                 mWakeLockSummary |= wakeLockFlags;
2847 
2848                 if (groupId != Display.INVALID_DISPLAY_GROUP) {
2849                     int wakeLockSummary = powerGroup.getWakeLockSummaryLocked();
2850                     wakeLockSummary |= wakeLockFlags;
2851                     powerGroup.setWakeLockSummaryLocked(wakeLockSummary);
2852                 } else {
2853                     invalidGroupWakeLockSummary |= wakeLockFlags;
2854                 }
2855 
2856                 for (int j = 0; j < numProfiles; j++) {
2857                     final ProfilePowerState profile = mProfilePowerState.valueAt(j);
2858                     if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
2859                         profile.mWakeLockSummary |= wakeLockFlags;
2860                     }
2861                 }
2862             }
2863 
2864             // Screen wake lock or non-interactive will release all override wake locks.
2865             if (mScreenTimeoutOverridePolicy != null) {
2866                 mScreenTimeoutOverridePolicy.checkScreenWakeLock(mWakeLockSummary);
2867             }
2868 
2869             for (int idx = 0; idx < mPowerGroups.size(); idx++) {
2870                 final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
2871                 final int wakeLockSummary = adjustWakeLockSummary(powerGroup.getWakefulnessLocked(),
2872                         invalidGroupWakeLockSummary | powerGroup.getWakeLockSummaryLocked());
2873                 powerGroup.setWakeLockSummaryLocked(wakeLockSummary);
2874             }
2875 
2876             mWakeLockSummary = adjustWakeLockSummary(getGlobalWakefulnessLocked(),
2877                     mWakeLockSummary);
2878 
2879             for (int i = 0; i < numProfiles; i++) {
2880                 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2881                 profile.mWakeLockSummary = adjustWakeLockSummary(getGlobalWakefulnessLocked(),
2882                         profile.mWakeLockSummary);
2883             }
2884 
2885             if (DEBUG_SPEW) {
2886                 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
2887                         + PowerManagerInternal.wakefulnessToString(getGlobalWakefulnessLocked())
2888                         + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
2889             }
2890         }
2891     }
2892 
2893     private static int adjustWakeLockSummary(int wakefulness, int wakeLockSummary) {
2894         // Cancel wake locks that make no sense based on the current state.
2895         if (wakefulness != WAKEFULNESS_DOZING) {
2896             wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
2897         }
2898         if (wakefulness == WAKEFULNESS_ASLEEP
2899                 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2900             wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
2901                     | WAKE_LOCK_BUTTON_BRIGHT);
2902             if (wakefulness == WAKEFULNESS_ASLEEP) {
2903                 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
2904             }
2905         }
2906 
2907         // Infer implied wake locks where necessary based on the current state.
2908         if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
2909             if (wakefulness == WAKEFULNESS_AWAKE) {
2910                 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
2911             } else if (wakefulness == WAKEFULNESS_DREAMING) {
2912                 wakeLockSummary |= WAKE_LOCK_CPU;
2913             }
2914         }
2915         if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
2916             wakeLockSummary |= WAKE_LOCK_CPU;
2917         }
2918 
2919         return wakeLockSummary;
2920     }
2921 
2922     /** Get wake lock summary flags that correspond to the given wake lock. */
2923     @SuppressWarnings("deprecation")
2924     private int getWakeLockSummaryFlags(WakeLock wakeLock) {
2925         if (wakeLock.mDisabled) {
2926             // We only respect this if the wake lock is not disabled.
2927             return 0;
2928         }
2929         switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2930             case PowerManager.PARTIAL_WAKE_LOCK:
2931                 return WAKE_LOCK_CPU;
2932             case PowerManager.FULL_WAKE_LOCK:
2933                 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
2934             case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2935                 return WAKE_LOCK_SCREEN_BRIGHT;
2936             case PowerManager.SCREEN_DIM_WAKE_LOCK:
2937                 return WAKE_LOCK_SCREEN_DIM;
2938             case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2939                 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
2940             case PowerManager.DOZE_WAKE_LOCK:
2941                 return WAKE_LOCK_DOZE;
2942             case PowerManager.DRAW_WAKE_LOCK:
2943                 return WAKE_LOCK_DRAW;
2944             case PowerManager.SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK:
2945                 return WAKE_LOCK_SCREEN_TIMEOUT_OVERRIDE;
2946         }
2947         return 0;
2948     }
2949 
2950     private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
2951         if (wakeLock.mWorkSource != null) {
2952             for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
2953                 final int uid = wakeLock.mWorkSource.getUid(k);
2954                 if (userId == UserHandle.getUserId(uid)) {
2955                     return true;
2956                 }
2957             }
2958 
2959             final List<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
2960             if (workChains != null) {
2961                 for (int k = 0; k < workChains.size(); k++) {
2962                     final int uid = workChains.get(k).getAttributionUid();
2963                     if (userId == UserHandle.getUserId(uid)) {
2964                         return true;
2965                     }
2966                 }
2967             }
2968         }
2969         return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
2970     }
2971 
2972     void checkForLongWakeLocks() {
2973         synchronized (mLock) {
2974             final long now = mClock.uptimeMillis();
2975             mNotifyLongDispatched = now;
2976             final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
2977             long nextCheckTime = Long.MAX_VALUE;
2978             final int numWakeLocks = mWakeLocks.size();
2979             for (int i = 0; i < numWakeLocks; i++) {
2980                 final WakeLock wakeLock = mWakeLocks.get(i);
2981                 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
2982                         == PowerManager.PARTIAL_WAKE_LOCK) {
2983                     if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
2984                         if (wakeLock.mAcquireTime < when) {
2985                             // This wake lock has exceeded the long acquire time, report!
2986                             notifyWakeLockLongStartedLocked(wakeLock);
2987                         } else {
2988                             // This wake lock could still become a long one, at this time.
2989                             long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
2990                             if (checkTime < nextCheckTime) {
2991                                 nextCheckTime = checkTime;
2992                             }
2993                         }
2994                     }
2995                 }
2996             }
2997             mNotifyLongScheduled = 0;
2998             mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
2999             if (nextCheckTime != Long.MAX_VALUE) {
3000                 mNotifyLongNextCheck = nextCheckTime;
3001                 enqueueNotifyLongMsgLocked(nextCheckTime);
3002             } else {
3003                 mNotifyLongNextCheck = 0;
3004             }
3005         }
3006     }
3007 
3008     /**
3009      * Updates the value of mUserActivitySummary to summarize the user requested
3010      * state of the system such as whether the screen should be bright or dim.
3011      * Note that user activity is ignored when the system is asleep.
3012      *
3013      * This function must have no other side-effects.
3014      */
3015     @GuardedBy("mLock")
3016     private void updateUserActivitySummaryLocked(long now, int dirty) {
3017         // Update the status of the user activity timeout timer.
3018         if ((dirty & (DIRTY_DISPLAY_GROUP_WAKEFULNESS | DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
3019                 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS | DIRTY_ATTENTIVE)) == 0) {
3020             return;
3021         }
3022         mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
3023 
3024         final long attentiveTimeout = getAttentiveTimeoutLocked();
3025         final long defaultSleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
3026         final long defaultScreenOffTimeout = getScreenOffTimeoutLocked(defaultSleepTimeout,
3027                 attentiveTimeout);
3028         final long defaultScreenDimDuration = getScreenDimDurationLocked(defaultScreenOffTimeout);
3029 
3030         final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
3031         long nextTimeout = -1;
3032         boolean hasUserActivitySummary = false;
3033         for (int idx = 0; idx < mPowerGroups.size(); idx++) {
3034             int groupUserActivitySummary = 0;
3035             long groupNextTimeout = 0;
3036             final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
3037             final int wakefulness = powerGroup.getWakefulnessLocked();
3038 
3039             // The timeouts could be overridden by the power group policy.
3040             long screenOffTimeout = defaultScreenOffTimeout;
3041             long screenDimDuration = defaultScreenDimDuration;
3042             long sleepTimeout = defaultSleepTimeout;
3043             // TODO(b/376211497): Consolidate the timeout logic for all power groups.
3044             if (powerGroup.getGroupId() == Display.DEFAULT_DISPLAY_GROUP) {
3045                 screenOffTimeout =
3046                         getDefaultGroupScreenOffTimeoutOverrideLocked(screenOffTimeout,
3047                                 screenDimDuration);
3048                 screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
3049             } else {
3050                 screenOffTimeout = powerGroup.getScreenOffTimeoutOverrideLocked(screenOffTimeout);
3051                 screenDimDuration =
3052                         powerGroup.getScreenDimDurationOverrideLocked(screenDimDuration);
3053                 if (sleepTimeout > 0 && screenOffTimeout > 0) {
3054                     // If both sleep and screen off timeouts are set, make sure that the sleep
3055                     // timeout is not smaller than the screen off one.
3056                     sleepTimeout = Math.max(sleepTimeout, screenOffTimeout);
3057                 }
3058             }
3059 
3060             if (wakefulness != WAKEFULNESS_ASLEEP) {
3061                 final long lastUserActivityTime = powerGroup.getLastUserActivityTimeLocked();
3062                 final long lastUserActivityTimeNoChangeLights =
3063                         powerGroup.getLastUserActivityTimeNoChangeLightsLocked();
3064                 if (lastUserActivityTime >= powerGroup.getLastWakeTimeLocked()) {
3065                     groupNextTimeout = lastUserActivityTime + screenOffTimeout - screenDimDuration;
3066                     if (now < groupNextTimeout) {
3067                         groupUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
3068                     } else {
3069                         groupNextTimeout = lastUserActivityTime + screenOffTimeout;
3070                         if (now < groupNextTimeout) {
3071                             groupUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
3072                         }
3073                     }
3074                 }
3075                 if (groupUserActivitySummary == 0 && lastUserActivityTimeNoChangeLights
3076                         >= powerGroup.getLastWakeTimeLocked()) {
3077                     groupNextTimeout = lastUserActivityTimeNoChangeLights + screenOffTimeout;
3078                     if (now < groupNextTimeout) {
3079                         if (powerGroup.isPolicyBrightLocked()) {
3080                             groupUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
3081                         } else if (powerGroup.isPolicyDimLocked()) {
3082                             groupUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
3083                         }
3084                     }
3085                 }
3086 
3087                 if (groupUserActivitySummary == 0) {
3088                     if (sleepTimeout >= 0) {
3089                         final long anyUserActivity = Math.max(lastUserActivityTime,
3090                                 lastUserActivityTimeNoChangeLights);
3091                         if (anyUserActivity >= powerGroup.getLastWakeTimeLocked()) {
3092                             groupNextTimeout = anyUserActivity + sleepTimeout;
3093                             if (now < groupNextTimeout) {
3094                                 groupUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
3095                             }
3096                         }
3097                     } else {
3098                         groupUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
3099                         groupNextTimeout = -1;
3100                     }
3101                 }
3102 
3103                 if (groupUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM
3104                         && userInactiveOverride) {
3105                     if ((groupUserActivitySummary &
3106                             (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
3107                         // Device is being kept awake by recent user activity
3108                         if (mOverriddenTimeout == -1) {
3109                             // Save when the next timeout would have occurred
3110                             mOverriddenTimeout = groupNextTimeout;
3111                         }
3112                     }
3113                     groupUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
3114                     groupNextTimeout = -1;
3115                 }
3116 
3117                 if ((groupUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
3118                         && (powerGroup.getWakeLockSummaryLocked()
3119                         & WAKE_LOCK_STAY_AWAKE) == 0) {
3120                     groupNextTimeout = mAttentionDetector.updateUserActivity(groupNextTimeout,
3121                             screenDimDuration);
3122                 }
3123 
3124                 if (isAttentiveTimeoutExpired(powerGroup, now)) {
3125                     groupUserActivitySummary = 0;
3126                     groupNextTimeout = -1;
3127                 }
3128 
3129                 hasUserActivitySummary |= groupUserActivitySummary != 0;
3130 
3131                 if (nextTimeout == -1) {
3132                     nextTimeout = groupNextTimeout;
3133                 } else if (groupNextTimeout != -1) {
3134                     nextTimeout = Math.min(nextTimeout, groupNextTimeout);
3135                 }
3136             }
3137 
3138             powerGroup.setUserActivitySummaryLocked(groupUserActivitySummary);
3139 
3140             if (DEBUG_SPEW) {
3141                 Slog.d(TAG, "updateUserActivitySummaryLocked: groupId=" + powerGroup.getGroupId()
3142                         + ", mWakefulness=" + wakefulnessToString(wakefulness)
3143                         + ", mUserActivitySummary=0x" + Integer.toHexString(
3144                         groupUserActivitySummary)
3145                         + ", nextTimeout=" + TimeUtils.formatUptime(groupNextTimeout));
3146             }
3147         }
3148 
3149         final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
3150         if (nextProfileTimeout > 0) {
3151             nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
3152         }
3153 
3154         if (hasUserActivitySummary && nextTimeout >= 0) {
3155             scheduleUserInactivityTimeout(nextTimeout);
3156         }
3157     }
3158 
3159     private void scheduleUserInactivityTimeout(long timeMs) {
3160         final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
3161         msg.setAsynchronous(true);
3162         mHandler.sendMessageAtTime(msg, timeMs);
3163     }
3164 
3165     private void scheduleAttentiveTimeout(long timeMs) {
3166         final Message msg = mHandler.obtainMessage(MSG_ATTENTIVE_TIMEOUT);
3167         msg.setAsynchronous(true);
3168         mHandler.sendMessageAtTime(msg, timeMs);
3169     }
3170 
3171     /**
3172      * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
3173      */
3174     @GuardedBy("mLock")
3175     private long getNextProfileTimeoutLocked(long now) {
3176         long nextTimeout = -1;
3177         final int numProfiles = mProfilePowerState.size();
3178         for (int i = 0; i < numProfiles; i++) {
3179             final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3180             final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
3181             if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
3182                 nextTimeout = timeout;
3183             }
3184         }
3185         return nextTimeout;
3186     }
3187 
3188     @GuardedBy("mLock")
3189     private void updateAttentiveStateLocked(long now, int dirty) {
3190         long attentiveTimeout = getAttentiveTimeoutLocked();
3191         // Attentive state only applies to the default display group.
3192         long goToSleepTime = mPowerGroups.get(
3193                 Display.DEFAULT_DISPLAY_GROUP).getLastUserActivityTimeLocked() + attentiveTimeout;
3194         long showWarningTime = goToSleepTime - mAttentiveWarningDurationConfig;
3195 
3196         boolean warningDismissed = maybeHideInattentiveSleepWarningLocked(now, showWarningTime);
3197 
3198         if (attentiveTimeout >= 0 && (warningDismissed
3199                 || (dirty & (DIRTY_ATTENTIVE | DIRTY_STAY_ON | DIRTY_SCREEN_BRIGHTNESS_BOOST
3200                 | DIRTY_PROXIMITY_POSITIVE | DIRTY_WAKEFULNESS | DIRTY_BOOT_COMPLETED
3201                 | DIRTY_SETTINGS)) != 0)) {
3202             if (DEBUG_SPEW) {
3203                 Slog.d(TAG, "Updating attentive state");
3204             }
3205 
3206             mHandler.removeMessages(MSG_ATTENTIVE_TIMEOUT);
3207 
3208             if (getGlobalWakefulnessLocked() == WAKEFULNESS_ASLEEP
3209                     || isBeingKeptFromInattentiveSleepLocked()) {
3210                 return;
3211             }
3212 
3213             long nextTimeout = -1;
3214 
3215             if (now < showWarningTime) {
3216                 nextTimeout = showWarningTime;
3217             } else if (now < goToSleepTime) {
3218                 if (DEBUG) {
3219                     long timeToSleep = goToSleepTime - now;
3220                     Slog.d(TAG, "Going to sleep in " + timeToSleep
3221                             + "ms if there is no user activity");
3222                 }
3223                 mInattentiveSleepWarningOverlayController.show();
3224                 nextTimeout = goToSleepTime;
3225             }
3226 
3227             if (nextTimeout >= 0) {
3228                 scheduleAttentiveTimeout(nextTimeout);
3229             }
3230         }
3231     }
3232 
3233     @GuardedBy("mLock")
3234     private boolean maybeHideInattentiveSleepWarningLocked(long now, long showWarningTime) {
3235         long attentiveTimeout = getAttentiveTimeoutLocked();
3236 
3237         if (!mInattentiveSleepWarningOverlayController.isShown()) {
3238             return false;
3239         }
3240 
3241         if (getGlobalWakefulnessLocked() == WAKEFULNESS_ASLEEP) {
3242             mInattentiveSleepWarningOverlayController.dismiss(false);
3243             return true;
3244         } else if (attentiveTimeout < 0 || isBeingKeptFromInattentiveSleepLocked()
3245                 || now < showWarningTime) {
3246             mInattentiveSleepWarningOverlayController.dismiss(true);
3247             return true;
3248         }
3249 
3250         return false;
3251     }
3252 
3253     @GuardedBy("mLock")
3254     private boolean isAttentiveTimeoutExpired(final PowerGroup powerGroup, long now) {
3255         long attentiveTimeout = getAttentiveTimeoutLocked();
3256         // Attentive state only applies to the default display group.
3257         return powerGroup.getGroupId() == Display.DEFAULT_DISPLAY_GROUP && attentiveTimeout >= 0
3258                 && now >= powerGroup.getLastUserActivityTimeLocked() + attentiveTimeout;
3259     }
3260 
3261     /**
3262      * Called when a user activity timeout has occurred.
3263      * Simply indicates that something about user activity has changed so that the new
3264      * state can be recomputed when the power state is updated.
3265      *
3266      * This function must have no other side-effects besides setting the dirty
3267      * bit and calling update power state.  Wakefulness transitions are handled elsewhere.
3268      */
3269     private void handleUserActivityTimeout() { // runs on handler thread
3270         synchronized (mLock) {
3271             if (DEBUG_SPEW) {
3272                 Slog.d(TAG, "handleUserActivityTimeout");
3273             }
3274 
3275             mDirty |= DIRTY_USER_ACTIVITY;
3276             updatePowerStateLocked();
3277         }
3278     }
3279 
3280     private void handleAttentiveTimeout() { // runs on handler thread
3281         synchronized (mLock) {
3282             if (DEBUG_SPEW) {
3283                 Slog.d(TAG, "handleAttentiveTimeout");
3284             }
3285 
3286             mDirty |= DIRTY_ATTENTIVE;
3287             updatePowerStateLocked();
3288         }
3289     }
3290 
3291     @GuardedBy("mLock")
3292     private long getAttentiveTimeoutLocked() {
3293         long timeout = mAttentiveTimeoutSetting;
3294         if (timeout <= 0) {
3295             return -1;
3296         }
3297 
3298         return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
3299     }
3300 
3301     @GuardedBy("mLock")
3302     private long getSleepTimeoutLocked(long attentiveTimeout) {
3303         long timeout = mSleepTimeoutSetting;
3304         if (timeout <= 0) {
3305             return -1;
3306         }
3307         if (attentiveTimeout >= 0) {
3308             timeout = Math.min(timeout, attentiveTimeout);
3309         }
3310         return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
3311     }
3312 
3313     @GuardedBy("mLock")
3314     private long getScreenOffTimeoutLocked(long sleepTimeout, long attentiveTimeout) {
3315         long timeout = mScreenOffTimeoutSetting;
3316         if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
3317             timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
3318         }
3319         if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
3320             timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
3321         }
3322         if (sleepTimeout >= 0) {
3323             timeout = Math.min(timeout, sleepTimeout);
3324         }
3325         if (attentiveTimeout >= 0) {
3326             timeout = Math.min(timeout, attentiveTimeout);
3327         }
3328         return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
3329     }
3330 
3331     @GuardedBy("mLock")
3332     private long getScreenDimDurationLocked(long screenOffTimeout) {
3333         return Math.min(mMaximumScreenDimDurationConfig,
3334                 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
3335     }
3336 
3337     @VisibleForTesting
3338     @GuardedBy("mLock")
3339     long getDefaultGroupScreenOffTimeoutOverrideLocked(long screenOffTimeout,
3340             long screenDimDuration) {
3341         long shortestScreenOffTimeout = screenOffTimeout;
3342         if (mScreenTimeoutOverridePolicy != null) {
3343             shortestScreenOffTimeout =
3344                     mScreenTimeoutOverridePolicy.getScreenTimeoutOverrideLocked(
3345                             mWakeLockSummary, screenOffTimeout);
3346         }
3347         if (mIsFaceDown) {
3348             shortestScreenOffTimeout = Math.min(screenDimDuration, shortestScreenOffTimeout);
3349         }
3350 
3351         return shortestScreenOffTimeout;
3352     }
3353 
3354     /**
3355      * Updates the wakefulness of the device.
3356      *
3357      * This is the function that decides whether the device should start dreaming
3358      * based on the current wake locks and user activity state.  It may modify mDirty
3359      * if the wakefulness changes.
3360      *
3361      * Returns true if the wakefulness changed and we need to restart power state calculation.
3362      */
3363     @GuardedBy("mLock")
3364     private boolean updateWakefulnessLocked(int dirty) {
3365         boolean changed = false;
3366         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
3367                 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
3368                 | DIRTY_DOCK_STATE | DIRTY_ATTENTIVE | DIRTY_SETTINGS
3369                 | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_POSTURED_STATE)) == 0) {
3370             return changed;
3371         }
3372         final long time = mClock.uptimeMillis();
3373         for (int idx = 0; idx < mPowerGroups.size(); idx++) {
3374             final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
3375             if (!(powerGroup.getWakefulnessLocked() == WAKEFULNESS_AWAKE
3376                     && isItBedTimeYetLocked(powerGroup))) {
3377                 continue;
3378             }
3379             if (DEBUG_SPEW) {
3380                 Slog.d(TAG, "updateWakefulnessLocked: Bed time for group "
3381                         + powerGroup.getGroupId());
3382             }
3383             if (isAttentiveTimeoutExpired(powerGroup, time)) {
3384                 if (DEBUG) {
3385                     Slog.i(TAG, "Going to sleep now due to long user inactivity");
3386                 }
3387                 changed = sleepPowerGroupLocked(powerGroup, time,
3388                         PowerManager.GO_TO_SLEEP_REASON_INATTENTIVE, Process.SYSTEM_UID);
3389             } else if (shouldNapAtBedTimeLocked(powerGroup)) {
3390                 changed = dreamPowerGroupLocked(powerGroup, time,
3391                         Process.SYSTEM_UID, /* allowWake= */ false);
3392             } else {
3393                 changed = dozePowerGroupLocked(powerGroup, time,
3394                         PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, Process.SYSTEM_UID);
3395             }
3396         }
3397         return changed;
3398     }
3399 
3400     /**
3401      * Returns true if the device should automatically nap and start dreaming when the user
3402      * activity timeout has expired and it's bedtime.
3403      */
3404     @GuardedBy("mLock")
3405     private boolean shouldNapAtBedTimeLocked(PowerGroup powerGroup) {
3406         if (!powerGroup.supportsSandmanLocked()) {
3407             return false;
3408         }
3409         return mDreamsActivateOnSleepSetting
3410                 || (mDreamsActivateOnDockSetting
3411                         && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED)
3412                 || (mDreamsActivateWhilePosturedSetting && mDevicePostured);
3413     }
3414 
3415     /**
3416      * Returns true if the provided {@link PowerGroup} should go to sleep now.
3417      * Also used when exiting a dream to determine whether we should go back to being fully awake or
3418      * else go to sleep for good.
3419      */
3420     @GuardedBy("mLock")
3421     private boolean isItBedTimeYetLocked(PowerGroup powerGroup) {
3422         if (!mBootCompleted) {
3423             return false;
3424         }
3425 
3426         long now = mClock.uptimeMillis();
3427         if (isAttentiveTimeoutExpired(powerGroup, now)) {
3428             return !isBeingKeptFromInattentiveSleepLocked();
3429         } else {
3430             return !isBeingKeptAwakeLocked(powerGroup);
3431         }
3432     }
3433 
3434     /**
3435      * Returns true if the provided {@link PowerGroup} is being kept awake by a wake lock, user
3436      * activity or the stay on while powered setting.  We also keep the phone awake when the
3437      * proximity sensor returns a positive result so that the device does not lock while in a phone
3438      * call. This function only controls whether the device will go to sleep or dream which is
3439      * independent of whether it will be allowed to suspend.
3440      */
3441     @GuardedBy("mLock")
3442     private boolean isBeingKeptAwakeLocked(final PowerGroup powerGroup) {
3443         return mStayOn
3444                 || mProximityPositive
3445                 || (powerGroup.getWakeLockSummaryLocked() & WAKE_LOCK_STAY_AWAKE) != 0
3446                 || (powerGroup.getUserActivitySummaryLocked() & (
3447                         USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0
3448                 || mScreenBrightnessBoostInProgress;
3449     }
3450 
3451     /**
3452      * Returns true if the device is prevented from going into inattentive sleep. We also keep the
3453      * device awake when the proximity sensor returns a positive result so that the device does not
3454      * lock while in a phone call. This function only controls whether the device will go to sleep
3455      * which is independent of whether it will be allowed to suspend.
3456      */
3457     @GuardedBy("mLock")
3458     private boolean isBeingKeptFromInattentiveSleepLocked() {
3459         return mStayOn || mScreenBrightnessBoostInProgress || mProximityPositive || !mBootCompleted;
3460     }
3461 
3462     /**
3463      * Determines whether to post a message to the sandman to update the dream state.
3464      */
3465     @GuardedBy("mLock")
3466     private void updateDreamLocked(int dirty, boolean powerGroupBecameReady) {
3467         if ((dirty & (DIRTY_WAKEFULNESS
3468                 | DIRTY_USER_ACTIVITY
3469                 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED
3470                 | DIRTY_ATTENTIVE
3471                 | DIRTY_WAKE_LOCKS
3472                 | DIRTY_BOOT_COMPLETED
3473                 | DIRTY_SETTINGS
3474                 | DIRTY_IS_POWERED
3475                 | DIRTY_STAY_ON
3476                 | DIRTY_PROXIMITY_POSITIVE
3477                 | DIRTY_BATTERY_STATE)) != 0 || powerGroupBecameReady) {
3478             if (areAllPowerGroupsReadyLocked()) {
3479                 scheduleSandmanLocked();
3480             }
3481         }
3482     }
3483 
3484     @GuardedBy("mLock")
3485     private void scheduleSandmanLocked() {
3486         if (!mSandmanScheduled) {
3487             mSandmanScheduled = true;
3488             for (int idx = 0; idx < mPowerGroups.size(); idx++) {
3489                 final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
3490                 if (powerGroup.supportsSandmanLocked()) {
3491                     Message msg = mHandler.obtainMessage(MSG_SANDMAN);
3492                     msg.arg1 = powerGroup.getGroupId();
3493                     msg.setAsynchronous(true);
3494                     mHandler.sendMessageAtTime(msg, mClock.uptimeMillis());
3495                 }
3496             }
3497         }
3498     }
3499 
3500     /**
3501      * Called when the device enters or exits a dreaming or dozing state.
3502      *
3503      * We do this asynchronously because we must call out of the power manager to start
3504      * the dream and we don't want to hold our lock while doing so.  There is a risk that
3505      * the device will wake or go to sleep in the meantime so we have to handle that case.
3506      */
3507     private void handleSandman(int groupId) { // runs on handler thread
3508         // Handle preconditions.
3509         final boolean startDreaming;
3510         final int wakefulness;
3511         synchronized (mLock) {
3512             mSandmanScheduled = false;
3513             if (!mPowerGroups.contains(groupId)) {
3514                 // Group has been removed.
3515                 return;
3516             }
3517             final PowerGroup powerGroup = mPowerGroups.get(groupId);
3518             wakefulness = powerGroup.getWakefulnessLocked();
3519             if (powerGroup.isSandmanSummonedLocked() && powerGroup.isReadyLocked()) {
3520                 startDreaming = canDreamLocked(powerGroup) || canDozeLocked(powerGroup);
3521                 powerGroup.setSandmanSummonedLocked(/* isSandmanSummoned= */ false);
3522             } else {
3523                 startDreaming = false;
3524             }
3525         }
3526 
3527         // Start dreaming if needed.
3528         // We only control the dream on the handler thread, so we don't need to worry about
3529         // concurrent attempts to start or stop the dream.
3530         final boolean isDreaming;
3531         if (mDreamManager != null) {
3532             // Restart the dream whenever the sandman is summoned.
3533             if (startDreaming) {
3534                 mDreamManager.stopDream(/* immediate= */ false,
3535                         "power manager request before starting dream" /*reason*/);
3536                 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING,
3537                         "power manager request" /*reason*/);
3538             }
3539             isDreaming = mDreamManager.isDreaming();
3540         } else {
3541             isDreaming = false;
3542         }
3543 
3544         // At this point, we either attempted to start the dream or no attempt will be made,
3545         // so stop holding the display suspend blocker for Doze.
3546         mDozeStartInProgress = false;
3547 
3548         // Update dream state.
3549         synchronized (mLock) {
3550             if (!mPowerGroups.contains(groupId)) {
3551                 // Group has been removed.
3552                 return;
3553             }
3554 
3555             // Remember the initial battery level when the dream started.
3556             if (startDreaming && isDreaming) {
3557                 mDreamsBatteryLevelDrain = 0;
3558                 if (wakefulness == WAKEFULNESS_DOZING) {
3559                     Slog.i(TAG, "Dozing...");
3560                 } else {
3561                     Slog.i(TAG, "Dreaming...");
3562                 }
3563             }
3564 
3565             // If preconditions changed, wait for the next iteration to determine
3566             // whether the dream should continue (or be restarted).
3567             final PowerGroup powerGroup = mPowerGroups.get(groupId);
3568             if (powerGroup.isSandmanSummonedLocked()
3569                     || powerGroup.getWakefulnessLocked() != wakefulness) {
3570                 return; // wait for next cycle
3571             }
3572 
3573             // Determine whether the dream should continue.
3574             long now = mClock.uptimeMillis();
3575             if (wakefulness == WAKEFULNESS_DREAMING) {
3576                 if (isDreaming && canDreamLocked(powerGroup)) {
3577                     if (mDreamsBatteryLevelDrainCutoffConfig >= 0
3578                             && mDreamsBatteryLevelDrain > mDreamsBatteryLevelDrainCutoffConfig
3579                             && !isBeingKeptAwakeLocked(powerGroup)) {
3580                         // If the user activity timeout expired and the battery appears
3581                         // to be draining faster than it is charging then stop dreaming
3582                         // and go to sleep.
3583                         Slog.i(TAG, "Stopping dream because the battery appears to "
3584                                 + "be draining faster than it is charging.  "
3585                                 + "Battery level drained while dreaming: "
3586                                 + mDreamsBatteryLevelDrain + "%.  "
3587                                 + "Battery level now: " + mBatteryLevel + "%.");
3588                     } else {
3589                         return; // continue dreaming
3590                     }
3591                 }
3592 
3593                 // Dream has ended or will be stopped.  Update the power state.
3594                 if (isItBedTimeYetLocked(powerGroup)) {
3595                     if (isAttentiveTimeoutExpired(powerGroup, now)) {
3596                         sleepPowerGroupLocked(powerGroup, now,
3597                                 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, Process.SYSTEM_UID);
3598                     } else {
3599                         dozePowerGroupLocked(powerGroup, now,
3600                                 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, Process.SYSTEM_UID);
3601                     }
3602                 } else {
3603                     wakePowerGroupLocked(powerGroup, now,
3604                             PowerManager.WAKE_REASON_DREAM_FINISHED,
3605                             "android.server.power:DREAM_FINISHED", Process.SYSTEM_UID,
3606                             mContext.getOpPackageName(), Process.SYSTEM_UID);
3607                 }
3608             } else if (wakefulness == WAKEFULNESS_DOZING) {
3609                 if (isDreaming) {
3610                     return; // continue dozing
3611                 }
3612 
3613                 // Doze has ended or will be stopped.  Update the power state.
3614                 sleepPowerGroupLocked(powerGroup, now, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
3615                         Process.SYSTEM_UID);
3616             }
3617         }
3618 
3619         // Stop dream.
3620         if (isDreaming && mDreamManager != null) {
3621             mDreamManager.stopDream(/* immediate= */ false, "power manager request" /*reason*/);
3622         }
3623     }
3624 
3625     @GuardedBy("mLock")
3626     private void onDreamSuppressionChangedLocked(final boolean isSuppressed) {
3627         if (!mDreamsDisabledByAmbientModeSuppressionConfig) {
3628             return;
3629         }
3630         final PowerGroup defaultPowerGroup = mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP);
3631         if (!isSuppressed && mIsPowered && mDreamsSupportedConfig && mDreamsEnabledSetting
3632                 && shouldNapAtBedTimeLocked(defaultPowerGroup)
3633                 && isItBedTimeYetLocked(defaultPowerGroup)) {
3634             napInternal(SystemClock.uptimeMillis(), Process.SYSTEM_UID, /* allowWake= */ true);
3635         } else if (isSuppressed) {
3636             mDirty |= DIRTY_SETTINGS;
3637             updatePowerStateLocked();
3638         }
3639     }
3640 
3641 
3642     /**
3643      * Returns true if the {@code groupId} is allowed to dream in its current state.
3644      */
3645     @GuardedBy("mLock")
3646     private boolean canDreamLocked(final PowerGroup powerGroup) {
3647         final boolean dreamsSuppressed = mDreamsDisabledByAmbientModeSuppressionConfig
3648                 && mAmbientDisplaySuppressionController.isSuppressed();
3649 
3650         if (!mBootCompleted
3651                 || dreamsSuppressed
3652                 || getGlobalWakefulnessLocked() != WAKEFULNESS_DREAMING
3653                 || !mDreamsSupportedConfig
3654                 || !mDreamsEnabledSetting
3655                 || !(powerGroup.isBrightOrDimLocked())
3656                 || (powerGroup.getUserActivitySummaryLocked() & (USER_ACTIVITY_SCREEN_BRIGHT
3657                 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0) {
3658             return false;
3659         }
3660         if (!isBeingKeptAwakeLocked(powerGroup)) {
3661             if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
3662                 return false;
3663             }
3664             if (!mIsPowered
3665                     && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
3666                     && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
3667                 return false;
3668             }
3669             return !mIsPowered
3670                     || mDreamsBatteryLevelMinimumWhenPoweredConfig < 0
3671                     || mBatteryLevel >= mDreamsBatteryLevelMinimumWhenPoweredConfig;
3672         }
3673         return true;
3674     }
3675 
3676     /**
3677      * Returns true if the device is allowed to doze in its current state.
3678      */
3679     @GuardedBy("mLock")
3680     private boolean canDozeLocked(PowerGroup powerGroup) {
3681         return powerGroup.supportsSandmanLocked()
3682                 && powerGroup.getWakefulnessLocked() == WAKEFULNESS_DOZING;
3683     }
3684 
3685     /**
3686      * Updates the state of all {@link PowerGroup}s asynchronously.
3687      * When the update is finished, the ready state of the {@link PowerGroup} will be updated.
3688      * The display controllers post a message to tell us when the actual display power state
3689      * has been updated so we come back here to double-check and finish up.
3690      *
3691      * This function recalculates the {@link PowerGroup} state each time.
3692      *
3693      * @return {@code true} if all {@link PowerGroup}s became ready; {@code false} otherwise
3694      */
3695     @GuardedBy("mLock")
3696     private boolean updatePowerGroupsLocked(int dirty) {
3697         final boolean oldPowerGroupsReady = areAllPowerGroupsReadyLocked();
3698         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
3699                 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
3700                 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST
3701                 | DIRTY_QUIESCENT | DIRTY_DISPLAY_GROUP_WAKEFULNESS)) != 0) {
3702             if ((dirty & DIRTY_QUIESCENT) != 0) {
3703                 if (areAllPowerGroupsReadyLocked()) {
3704                     sQuiescent = false;
3705                 } else {
3706                     mDirty |= DIRTY_QUIESCENT;
3707                 }
3708             }
3709 
3710             for (int idx = 0; idx < mPowerGroups.size(); idx++) {
3711                 final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
3712                 final int groupId = powerGroup.getGroupId();
3713 
3714                 // Determine appropriate screen brightness.
3715                 final float screenBrightnessOverride;
3716                 CharSequence overrideTag = null;
3717                 if (!mBootCompleted) {
3718                     // Keep the brightness steady during boot. This requires the
3719                     // bootloader brightness and the default brightness to be identical.
3720                     screenBrightnessOverride = mScreenBrightnessDefault;
3721                     overrideTag = "boot";
3722                 } else {
3723                     screenBrightnessOverride = PowerManager.BRIGHTNESS_INVALID_FLOAT;
3724                 }
3725                 boolean ready = powerGroup.updateLocked(screenBrightnessOverride, overrideTag,
3726                         shouldUseProximitySensorLocked(), shouldBoostScreenBrightness(),
3727                         mDozeScreenStateOverrideFromDreamManager,
3728                         mDozeScreenStateOverrideReasonFromDreamManager,
3729                         mDozeScreenBrightnessOverrideFromDreamManagerFloat,
3730                         mUseNormalBrightnessForDoze,
3731                         mDrawWakeLockOverrideFromSidekick,
3732                         mBatterySaverSupported
3733                                 ?
3734                                 mBatterySaverStateMachine.getBatterySaverPolicy()
3735                                         .getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS)
3736                                 : new PowerSaveState.Builder().build(),
3737                         sQuiescent, mDozeAfterScreenOff, mBootCompleted,
3738                         mScreenBrightnessBoostInProgress, mRequestWaitForNegativeProximity,
3739                         mBrightWhenDozingConfig);
3740                 int wakefulness = powerGroup.getWakefulnessLocked();
3741                 if (DEBUG_SPEW) {
3742                     Slog.d(TAG, "updatePowerGroupsLocked: displayReady=" + ready
3743                             + ", groupId=" + groupId
3744                             + ", policy=" + policyToString(powerGroup.getPolicyLocked())
3745                             + ", mWakefulness="
3746                             + PowerManagerInternal.wakefulnessToString(wakefulness)
3747                             + ", mWakeLockSummary=0x" + Integer.toHexString(
3748                             powerGroup.getWakeLockSummaryLocked())
3749                             + ", mUserActivitySummary=0x" + Integer.toHexString(
3750                             powerGroup.getUserActivitySummaryLocked())
3751                             + ", mBootCompleted=" + mBootCompleted
3752                             + ", screenBrightnessOverride=" + screenBrightnessOverride
3753                             + ", mScreenBrightnessBoostInProgress="
3754                             + mScreenBrightnessBoostInProgress
3755                             + ", sQuiescent=" + sQuiescent);
3756                 }
3757 
3758                 final boolean displayReadyStateChanged = powerGroup.setReadyLocked(ready);
3759                 final boolean poweringOn = powerGroup.isPoweringOnLocked();
3760                 if (ready && displayReadyStateChanged && poweringOn
3761                         && wakefulness == WAKEFULNESS_AWAKE) {
3762                     powerGroup.setIsPoweringOnLocked(false);
3763                     LatencyTracker.getInstance(mContext).onActionEnd(ACTION_TURN_ON_SCREEN);
3764                     Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, groupId);
3765                     final int latencyMs = (int) (mClock.uptimeMillis()
3766                             - powerGroup.getLastPowerOnTimeLocked());
3767                     if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
3768                         Slog.w(TAG, "Screen on took " + latencyMs + " ms");
3769                     }
3770                 }
3771             }
3772             mRequestWaitForNegativeProximity = false;
3773         }
3774 
3775         return areAllPowerGroupsReadyLocked() && !oldPowerGroupsReady;
3776     }
3777 
3778     @GuardedBy("mLock")
3779     private void updateScreenBrightnessBoostLocked(int dirty) {
3780         if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
3781             if (mScreenBrightnessBoostInProgress) {
3782                 final long now = mClock.uptimeMillis();
3783                 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
3784                 if (mLastScreenBrightnessBoostTime > mLastGlobalSleepTime) {
3785                     final long boostTimeout = mLastScreenBrightnessBoostTime +
3786                             SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
3787                     if (boostTimeout > now) {
3788                         Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
3789                         msg.setAsynchronous(true);
3790                         mHandler.sendMessageAtTime(msg, boostTimeout);
3791                         return;
3792                     }
3793                 }
3794                 mScreenBrightnessBoostInProgress = false;
3795                 userActivityNoUpdateLocked(now,
3796                         PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
3797             }
3798         }
3799     }
3800 
3801     private boolean shouldBoostScreenBrightness() {
3802         return mScreenBrightnessBoostInProgress;
3803     }
3804 
3805     private static boolean isValidBrightness(float value) {
3806         return value >= PowerManager.BRIGHTNESS_MIN && value <= PowerManager.BRIGHTNESS_MAX;
3807     }
3808 
3809     @VisibleForTesting
3810     int getDreamsBatteryLevelDrain() {
3811         return mDreamsBatteryLevelDrain;
3812     }
3813 
3814     private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
3815             new DisplayManagerInternal.DisplayPowerCallbacks() {
3816 
3817         @Override
3818         public void onStateChanged() {
3819             synchronized (mLock) {
3820                 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
3821                 updatePowerStateLocked();
3822             }
3823         }
3824 
3825         @Override
3826         public void onProximityPositive() {
3827             synchronized (mLock) {
3828                 mProximityPositive = true;
3829                 mDirty |= DIRTY_PROXIMITY_POSITIVE;
3830                 updatePowerStateLocked();
3831             }
3832         }
3833 
3834         @Override
3835         public void onProximityNegative() {
3836             synchronized (mLock) {
3837                 mProximityPositive = false;
3838                 mInterceptedPowerKeyForProximity = false;
3839                 mDirty |= DIRTY_PROXIMITY_POSITIVE;
3840                 userActivityNoUpdateLocked(mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP),
3841                         mClock.uptimeMillis(), PowerManager.USER_ACTIVITY_EVENT_OTHER,
3842                         /* flags= */ 0, Process.SYSTEM_UID);
3843                 updatePowerStateLocked();
3844             }
3845         }
3846 
3847         @Override
3848         public void onDisplayStateChange(boolean allInactive, boolean allOff) {
3849             // This method is only needed to support legacy display blanking behavior
3850             // where the display's power state is coupled to suspend or to the power HAL.
3851             // The order of operations matters here.
3852             synchronized (mLock) {
3853                 setPowerModeInternal(MODE_DISPLAY_INACTIVE, allInactive);
3854                 if (allOff) {
3855                     if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
3856                         setHalInteractiveModeLocked(false);
3857                     }
3858                     if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
3859                         setHalAutoSuspendModeLocked(true);
3860                     }
3861                 } else {
3862                     if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
3863                         setHalAutoSuspendModeLocked(false);
3864                     }
3865                     if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
3866                         setHalInteractiveModeLocked(true);
3867                     }
3868                 }
3869             }
3870         }
3871 
3872         @Override
3873         public void acquireSuspendBlocker(String name) {
3874             mDisplaySuspendBlocker.acquire(name);
3875         }
3876 
3877         @Override
3878         public void releaseSuspendBlocker(String name) {
3879             mDisplaySuspendBlocker.release(name);
3880         }
3881     };
3882 
3883     @GuardedBy("mLock")
3884     private boolean shouldUseProximitySensorLocked() {
3885         // Use default display group for proximity sensor.
3886         return (mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP).getWakeLockSummaryLocked()
3887                         & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
3888     }
3889 
3890     @GuardedBy("mLock")
3891     private void notifyScreenTimeoutPolicyChangesLocked() {
3892         if (!mFeatureFlags.isScreenTimeoutPolicyListenerApiEnabled()) {
3893             return;
3894         }
3895 
3896         for (int idx = 0; idx < mPowerGroups.size(); idx++) {
3897             final int powerGroupId = mPowerGroups.keyAt(idx);
3898             final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
3899             final int screenTimeoutPolicy = powerGroup.getScreenTimeoutPolicy();
3900             mNotifier.notifyScreenTimeoutPolicyChanges(powerGroupId, screenTimeoutPolicy);
3901         }
3902     }
3903 
3904     /**
3905      * Updates the suspend blocker that keeps the CPU alive.
3906      *
3907      * This function must have no other side-effects.
3908      */
3909     @GuardedBy("mLock")
3910     private void updateSuspendBlockerLocked() {
3911         final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3912         final boolean needDisplaySuspendBlocker = needSuspendBlockerLocked();
3913         final boolean autoSuspend = !needDisplaySuspendBlocker;
3914         boolean interactive = false;
3915         for (int idx = 0; idx < mPowerGroups.size() && !interactive; idx++) {
3916             interactive = mPowerGroups.valueAt(idx).isBrightOrDimLocked();
3917         }
3918 
3919         // Disable auto-suspend if needed.
3920         // FIXME We should consider just leaving auto-suspend enabled forever since
3921         // we already hold the necessary wakelocks.
3922         if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
3923             setHalAutoSuspendModeLocked(false);
3924         }
3925 
3926         // First acquire suspend blockers if needed.
3927         if (!mBootCompleted && !mHoldingBootingSuspendBlocker) {
3928             mBootingSuspendBlocker.acquire();
3929             mHoldingBootingSuspendBlocker = true;
3930         }
3931         if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
3932             mWakeLockSuspendBlocker.acquire();
3933             mHoldingWakeLockSuspendBlocker = true;
3934         }
3935         if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
3936             mDisplaySuspendBlocker.acquire(HOLDING_DISPLAY_SUSPEND_BLOCKER);
3937             mHoldingDisplaySuspendBlocker = true;
3938         }
3939 
3940         // Inform the power HAL about interactive mode.
3941         // Although we could set interactive strictly based on the wakefulness
3942         // as reported by isInteractive(), it is actually more desirable to track
3943         // the display policy state instead so that the interactive state observed
3944         // by the HAL more accurately tracks transitions between AWAKE and DOZING.
3945         // Refer to getDesiredScreenPolicyLocked() for details.
3946         if (mDecoupleHalInteractiveModeFromDisplayConfig) {
3947             // When becoming non-interactive, we want to defer sending this signal
3948             // until the display is actually ready so that all transitions have
3949             // completed.  This is probably a good sign that things have gotten
3950             // too tangled over here...
3951             if (interactive || areAllPowerGroupsReadyLocked()) {
3952                 setHalInteractiveModeLocked(interactive);
3953             }
3954         }
3955 
3956         // Then release suspend blockers if needed.
3957         if (mBootCompleted && mHoldingBootingSuspendBlocker) {
3958             mBootingSuspendBlocker.release();
3959             mHoldingBootingSuspendBlocker = false;
3960         }
3961         if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
3962             mWakeLockSuspendBlocker.release();
3963             mHoldingWakeLockSuspendBlocker = false;
3964         }
3965         if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
3966             mDisplaySuspendBlocker.release(HOLDING_DISPLAY_SUSPEND_BLOCKER);
3967             mHoldingDisplaySuspendBlocker = false;
3968         }
3969 
3970         // Enable auto-suspend if needed.
3971         if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
3972             setHalAutoSuspendModeLocked(true);
3973         }
3974     }
3975 
3976     /**
3977      * Return true if we must keep a suspend blocker active on behalf of a power group.
3978      */
3979     @GuardedBy("mLock")
3980     private boolean needSuspendBlockerLocked() {
3981         if (!areAllPowerGroupsReadyLocked()) {
3982             return true;
3983         }
3984 
3985         if (mScreenBrightnessBoostInProgress) {
3986             return true;
3987         }
3988 
3989         // When we transition to DOZING, we have to keep the display suspend blocker
3990         // up until the Doze service has a change to acquire the DOZE wakelock.
3991         // Here we wait for mWakefulnessChanging to become false since the wakefulness
3992         // transition to DOZING isn't considered "changed" until the doze wake lock is
3993         // acquired.
3994         if (getGlobalWakefulnessLocked() == WAKEFULNESS_DOZING && mDozeStartInProgress) {
3995             return true;
3996         }
3997 
3998         for (int idx = 0; idx < mPowerGroups.size(); idx++) {
3999             final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
4000             if (powerGroup.needSuspendBlockerLocked(mProximityPositive,
4001                     mSuspendWhenScreenOffDueToProximityConfig)) {
4002                 return true;
4003             }
4004         }
4005 
4006         // Let the system suspend if the screen is off or dozing.
4007         return false;
4008     }
4009 
4010     @GuardedBy("mLock")
4011     private void setHalAutoSuspendModeLocked(boolean enable) {
4012         if (!mUseAutoSuspend) {
4013             return;
4014         }
4015         if (enable != mHalAutoSuspendModeEnabled) {
4016             if (DEBUG) {
4017                 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
4018             }
4019             mHalAutoSuspendModeEnabled = enable;
4020             Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
4021             try {
4022                 mNativeWrapper.nativeSetAutoSuspend(enable);
4023             } finally {
4024                 Trace.traceEnd(Trace.TRACE_TAG_POWER);
4025             }
4026         }
4027     }
4028 
4029     @GuardedBy("mLock")
4030     private void setHalInteractiveModeLocked(boolean enable) {
4031         if (enable != mHalInteractiveModeEnabled) {
4032             if (DEBUG) {
4033                 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
4034             }
4035             mHalInteractiveModeEnabled = enable;
4036             Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
4037             try {
4038                 mNativeWrapper.nativeSetPowerMode(Mode.INTERACTIVE, enable);
4039             } finally {
4040                 Trace.traceEnd(Trace.TRACE_TAG_POWER);
4041             }
4042         }
4043     }
4044 
4045     private boolean isGloballyInteractiveInternal() {
4046         synchronized (mLock) {
4047             return PowerManagerInternal.isInteractive(getGlobalWakefulnessLocked());
4048         }
4049     }
4050 
4051     private boolean isInteractiveInternal(int displayId, int uid) {
4052         synchronized (mLock) {
4053             if (!mSystemReady) {
4054                 return isGloballyInteractiveInternal();
4055             }
4056             DisplayInfo displayInfo = mDisplayManagerInternal.getDisplayInfo(displayId);
4057             if (displayInfo == null) {
4058                 Slog.w(TAG, "Did not find DisplayInfo for displayId " + displayId);
4059                 return false;
4060             }
4061             if (!displayInfo.hasAccess(uid)) {
4062                 throw new SecurityException(
4063                         "uid " + uid + " does not have access to display " + displayId);
4064             }
4065             PowerGroup powerGroup = mPowerGroups.get(displayInfo.displayGroupId);
4066             if (powerGroup == null) {
4067                 Slog.w(TAG, "Did not find PowerGroup for displayId " + displayId);
4068                 return false;
4069             }
4070             return PowerManagerInternal.isInteractive(powerGroup.getWakefulnessLocked());
4071         }
4072     }
4073 
4074     private boolean setLowPowerModeInternal(boolean enabled) {
4075         synchronized (mLock) {
4076             if (DEBUG) {
4077                 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
4078             }
4079             if (mIsPowered || !mBatterySaverSupported) {
4080                 return false;
4081             }
4082 
4083             mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
4084 
4085             return true;
4086         }
4087     }
4088 
4089     boolean isDeviceIdleModeInternal() {
4090         synchronized (mLock) {
4091             return mDeviceIdleMode;
4092         }
4093     }
4094 
4095     boolean isLightDeviceIdleModeInternal() {
4096         synchronized (mLock) {
4097             return mLightDeviceIdleMode;
4098         }
4099     }
4100 
4101     @GuardedBy("mLock")
4102     private void handleBatteryStateChangedLocked() {
4103         mDirty |= DIRTY_BATTERY_STATE;
4104         updatePowerStateLocked();
4105     }
4106 
4107     private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
4108             @Nullable final String reason, boolean wait) {
4109         if (PowerManager.REBOOT_USERSPACE.equals(reason)) {
4110             if (!PowerManager.isRebootingUserspaceSupportedImpl()) {
4111                 throw new UnsupportedOperationException(
4112                         "Attempted userspace reboot on a device that doesn't support it");
4113             }
4114         }
4115         if (mHandler == null || !mSystemReady) {
4116             if (PackageWatchdog.isRecoveryTriggeredReboot()) {
4117                 // If we're stuck in a really low-level reboot loop, and a
4118                 // rescue party is trying to prompt the user for a factory data
4119                 // reset, we must GET TO DA CHOPPA!
4120                 // No check point from ShutdownCheckPoints will be dumped at this state.
4121                 PowerManagerService.lowLevelReboot(reason);
4122             } else {
4123                 throw new IllegalStateException("Too early to call shutdown() or reboot()");
4124             }
4125         }
4126 
4127         Runnable runnable = new Runnable() {
4128             @Override
4129             public void run() {
4130                 synchronized (this) {
4131                     if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
4132                         ShutdownThread.rebootSafeMode(getUiContext(), confirm);
4133                     } else if (haltMode == HALT_MODE_REBOOT) {
4134                         ShutdownThread.reboot(getUiContext(), reason, confirm);
4135                     } else {
4136                         ShutdownThread.shutdown(getUiContext(), reason, confirm);
4137                     }
4138                 }
4139             }
4140         };
4141 
4142         // ShutdownThread must run on a looper capable of displaying the UI.
4143         Message msg = Message.obtain(UiThread.getHandler(), runnable);
4144         msg.setAsynchronous(true);
4145         UiThread.getHandler().sendMessage(msg);
4146 
4147         // PowerManager.reboot() is documented not to return so just wait for the inevitable.
4148         if (wait) {
4149             synchronized (runnable) {
4150                 while (true) {
4151                     try {
4152                         runnable.wait();
4153                     } catch (InterruptedException e) {
4154                     }
4155                 }
4156             }
4157         }
4158     }
4159 
4160     private void crashInternal(final String message) {
4161         Thread t = new Thread("PowerManagerService.crash()") {
4162             @Override
4163             public void run() {
4164                 throw new RuntimeException(message);
4165             }
4166         };
4167         try {
4168             t.start();
4169             t.join();
4170         } catch (InterruptedException e) {
4171             Slog.wtf(TAG, e);
4172         }
4173     }
4174 
4175     void setStayOnSettingInternal(int val) {
4176         Settings.Global.putInt(mContext.getContentResolver(),
4177                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
4178     }
4179 
4180     void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
4181         if (userId < 0) {
4182             Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
4183             return;
4184         }
4185         synchronized (mLock) {
4186             // System-wide timeout
4187             if (userId == UserHandle.USER_SYSTEM) {
4188                 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
4189             } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
4190                 mProfilePowerState.delete(userId);
4191             } else {
4192                 final ProfilePowerState profile = mProfilePowerState.get(userId);
4193                 if (profile != null) {
4194                     profile.mScreenOffTimeout = timeMs;
4195                 } else {
4196                     mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs,
4197                             mClock.uptimeMillis()));
4198                     // We need to recalculate wake locks for the new profile state.
4199                     mDirty |= DIRTY_WAKE_LOCKS;
4200                 }
4201             }
4202             mDirty |= DIRTY_SETTINGS;
4203             updatePowerStateLocked();
4204         }
4205     }
4206 
4207     boolean setDeviceIdleModeInternal(boolean enabled) {
4208         synchronized (mLock) {
4209             if (mDeviceIdleMode == enabled) {
4210                 return false;
4211             }
4212             mDeviceIdleMode = enabled;
4213             updateWakeLockDisabledStatesLocked();
4214             setPowerModeInternal(MODE_DEVICE_IDLE, mDeviceIdleMode || mLightDeviceIdleMode);
4215         }
4216         if (enabled) {
4217             EventLogTags.writeDeviceIdleOnPhase("power");
4218         } else {
4219             EventLogTags.writeDeviceIdleOffPhase("power");
4220         }
4221         return true;
4222     }
4223 
4224     boolean setLightDeviceIdleModeInternal(boolean enabled) {
4225         synchronized (mLock) {
4226             if (mLightDeviceIdleMode != enabled) {
4227                 mLightDeviceIdleMode = enabled;
4228                 if (!mDeviceIdleMode && disableWakelocksInLightIdle()) {
4229                     updateWakeLockDisabledStatesLocked();
4230                 }
4231                 setPowerModeInternal(MODE_DEVICE_IDLE, mDeviceIdleMode || mLightDeviceIdleMode);
4232                 return true;
4233             }
4234             return false;
4235         }
4236     }
4237 
4238     void setDeviceIdleWhitelistInternal(int[] appids) {
4239         synchronized (mLock) {
4240             mDeviceIdleWhitelist = appids;
4241             if (doesIdleStateBlockWakeLocksLocked()) {
4242                 updateWakeLockDisabledStatesLocked();
4243             }
4244         }
4245     }
4246 
4247     void setDeviceIdleTempWhitelistInternal(int[] appids) {
4248         synchronized (mLock) {
4249             mDeviceIdleTempWhitelist = appids;
4250             if (doesIdleStateBlockWakeLocksLocked()) {
4251                 updateWakeLockDisabledStatesLocked();
4252             }
4253         }
4254     }
4255 
4256     void setLowPowerStandbyAllowlistInternal(int[] uids) {
4257         synchronized (mLock) {
4258             mLowPowerStandbyAllowlist = uids;
4259             if (mLowPowerStandbyActive) {
4260                 updateWakeLockDisabledStatesLocked();
4261             }
4262         }
4263     }
4264 
4265     void setLowPowerStandbyActiveInternal(boolean active) {
4266         synchronized (mLock) {
4267             if (mLowPowerStandbyActive != active) {
4268                 mLowPowerStandbyActive = active;
4269                 updateWakeLockDisabledStatesLocked();
4270             }
4271         }
4272     }
4273 
4274     void startUidChangesInternal() {
4275         synchronized (mLock) {
4276             mUidsChanging = true;
4277         }
4278     }
4279 
4280     void finishUidChangesInternal() {
4281         synchronized (mLock) {
4282             mUidsChanging = false;
4283             if (mUidsChanged) {
4284                 updateWakeLockDisabledStatesLocked();
4285                 mUidsChanged = false;
4286             }
4287         }
4288     }
4289 
4290     @GuardedBy("mLock")
4291     private void handleUidStateChangeLocked() {
4292         if (mUidsChanging) {
4293             mUidsChanged = true;
4294         } else {
4295             updateWakeLockDisabledStatesLocked();
4296         }
4297     }
4298 
4299     void updateUidProcStateInternal(int uid, int procState) {
4300         synchronized (mLock) {
4301             UidState state = mUidState.get(uid);
4302             if (state == null) {
4303                 state = new UidState(uid);
4304                 mUidState.put(uid, state);
4305             }
4306             final boolean oldShouldAllow = state.mProcState
4307                     <= ActivityManager.PROCESS_STATE_RECEIVER;
4308             state.mProcState = procState;
4309             if (state.mNumWakeLocks > 0) {
4310                 if (doesIdleStateBlockWakeLocksLocked() || mLowPowerStandbyActive) {
4311                     handleUidStateChangeLocked();
4312                 } else if (!state.mActive && oldShouldAllow !=
4313                         (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
4314                     // If this uid is not active, but the process state has changed such
4315                     // that we may still want to allow it to hold a wake lock, then take care of it.
4316                     handleUidStateChangeLocked();
4317                 }
4318             }
4319         }
4320     }
4321 
4322     void uidGoneInternal(int uid) {
4323         synchronized (mLock) {
4324             final int index = mUidState.indexOfKey(uid);
4325             if (index >= 0) {
4326                 UidState state = mUidState.valueAt(index);
4327                 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
4328                 state.mActive = false;
4329                 mUidState.removeAt(index);
4330                 if ((doesIdleStateBlockWakeLocksLocked() || mLowPowerStandbyActive)
4331                         && state.mNumWakeLocks > 0) {
4332                     handleUidStateChangeLocked();
4333                 }
4334             }
4335         }
4336     }
4337 
4338     void uidActiveInternal(int uid) {
4339         synchronized (mLock) {
4340             UidState state = mUidState.get(uid);
4341             if (state == null) {
4342                 state = new UidState(uid);
4343                 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
4344                 mUidState.put(uid, state);
4345             }
4346             state.mActive = true;
4347             if (state.mNumWakeLocks > 0) {
4348                 handleUidStateChangeLocked();
4349             }
4350         }
4351     }
4352 
4353     void uidIdleInternal(int uid) {
4354         synchronized (mLock) {
4355             UidState state = mUidState.get(uid);
4356             if (state != null) {
4357                 state.mActive = false;
4358                 if (state.mNumWakeLocks > 0) {
4359                     handleUidStateChangeLocked();
4360                 }
4361             }
4362         }
4363     }
4364 
4365     @GuardedBy("mLock")
4366     private boolean doesIdleStateBlockWakeLocksLocked() {
4367         return mDeviceIdleMode || (mLightDeviceIdleMode && disableWakelocksInLightIdle());
4368     }
4369 
4370     @GuardedBy("mLock")
4371     private void updateWakeLockDisabledStatesLocked() {
4372         boolean changed = false;
4373         final int numWakeLocks = mWakeLocks.size();
4374         for (int i = 0; i < numWakeLocks; i++) {
4375             final WakeLock wakeLock = mWakeLocks.get(i);
4376             if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
4377                     == PowerManager.PARTIAL_WAKE_LOCK || isScreenLock(wakeLock)) {
4378                 if (setWakeLockDisabledStateLocked(wakeLock)) {
4379                     changed = true;
4380                     if (wakeLock.mDisabled) {
4381                         // This wake lock is no longer being respected.
4382                         notifyWakeLockReleasedLocked(wakeLock);
4383                     } else {
4384                         notifyWakeLockAcquiredLocked(wakeLock);
4385                     }
4386                 }
4387             }
4388         }
4389         if (changed) {
4390             mDirty |= DIRTY_WAKE_LOCKS;
4391             updatePowerStateLocked();
4392         }
4393     }
4394 
4395     @GuardedBy("mLock")
4396     private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
4397         if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
4398                 == PowerManager.PARTIAL_WAKE_LOCK) {
4399             boolean disabled = false;
4400             final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
4401             if (appid >= Process.FIRST_APPLICATION_UID) {
4402                 // Cached inactive processes are never allowed to hold wake locks.
4403                 if (mConstants.NO_CACHED_WAKE_LOCKS) {
4404                     disabled = mForceSuspendActive
4405                             || (!wakeLock.mUidState.mActive && wakeLock.mUidState.mProcState
4406                                     != ActivityManager.PROCESS_STATE_NONEXISTENT &&
4407                             wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER);
4408                 }
4409                 if (doesIdleStateBlockWakeLocksLocked()) {
4410                     // If we are in idle mode, we will also ignore all partial wake locks that are
4411                     // for application uids that are not allowlisted.
4412                     final UidState state = wakeLock.mUidState;
4413                     if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
4414                             Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
4415                             state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
4416                             state.mProcState >
4417                                     ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
4418                         disabled = true;
4419                     }
4420                 }
4421                 if (mLowPowerStandbyActive) {
4422                     final UidState state = wakeLock.mUidState;
4423                     if (Arrays.binarySearch(mLowPowerStandbyAllowlist, wakeLock.mOwnerUid) < 0
4424                             && state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT
4425                             && state.mProcState > ActivityManager.PROCESS_STATE_BOUND_TOP) {
4426                         disabled = true;
4427                     }
4428                 }
4429             }
4430             return wakeLock.setDisabled(disabled);
4431         } else if (mDisableScreenWakeLocksWhileCached && isScreenLock(wakeLock)) {
4432             boolean disabled = false;
4433             final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
4434             final UidState state = wakeLock.mUidState;
4435             // Cached inactive processes are never allowed to hold wake locks.
4436             if (mConstants.NO_CACHED_WAKE_LOCKS
4437                     && appid >= Process.FIRST_APPLICATION_UID
4438                     && !state.mActive
4439                     && state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT
4440                     && state.mProcState >= ActivityManager.PROCESS_STATE_TOP_SLEEPING) {
4441                 if (DEBUG_SPEW) {
4442                     Slog.d(TAG, "disabling full wakelock " + wakeLock);
4443                 }
4444                 disabled = true;
4445             }
4446             return wakeLock.setDisabled(disabled);
4447         }
4448         return false;
4449     }
4450 
4451     @GuardedBy("mLock")
4452     private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
4453         return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
4454                 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
4455     }
4456 
4457     private void setAttentionLightInternal(boolean on, int color) {
4458         LogicalLight light;
4459         synchronized (mLock) {
4460             if (!mSystemReady) {
4461                 return;
4462             }
4463             light = mAttentionLight;
4464         }
4465 
4466         // Control light outside of lock.
4467         if (light != null) {
4468             light.setFlashing(color, LogicalLight.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
4469         }
4470     }
4471 
4472     private void setDozeAfterScreenOffInternal(boolean on) {
4473         synchronized (mLock) {
4474             mDozeAfterScreenOff = on;
4475         }
4476     }
4477 
4478     private void boostScreenBrightnessInternal(long eventTime, int uid) {
4479         synchronized (mLock) {
4480             if (!mSystemReady || getGlobalWakefulnessLocked() == WAKEFULNESS_ASLEEP
4481                     || eventTime < mLastScreenBrightnessBoostTime) {
4482                 return;
4483             }
4484 
4485             Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
4486             mLastScreenBrightnessBoostTime = eventTime;
4487             mScreenBrightnessBoostInProgress = true;
4488             mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
4489 
4490             userActivityNoUpdateLocked(mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP), eventTime,
4491                     PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
4492             updatePowerStateLocked();
4493         }
4494     }
4495 
4496     private boolean isScreenBrightnessBoostedInternal() {
4497         synchronized (mLock) {
4498             return mScreenBrightnessBoostInProgress;
4499         }
4500     }
4501 
4502     /**
4503      * Called when a screen brightness boost timeout has occurred.
4504      *
4505      * This function must have no other side-effects besides setting the dirty
4506      * bit and calling update power state.
4507      */
4508     private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
4509         synchronized (mLock) {
4510             if (DEBUG_SPEW) {
4511                 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
4512             }
4513 
4514             mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
4515             updatePowerStateLocked();
4516         }
4517     }
4518 
4519     private void setUserInactiveOverrideFromWindowManagerInternal() {
4520         synchronized (mLock) {
4521             mUserInactiveOverrideFromWindowManager = true;
4522             mDirty |= DIRTY_USER_ACTIVITY;
4523             updatePowerStateLocked();
4524         }
4525     }
4526 
4527     private void setDevicePosturedInternal(boolean isPostured) {
4528         if (!allowDreamWhenPostured()) {
4529             return;
4530         }
4531         synchronized (mLock) {
4532             mDevicePostured = isPostured;
4533             mDirty |= DIRTY_POSTURED_STATE;
4534             updatePowerStateLocked();
4535         }
4536     }
4537 
4538     private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
4539         synchronized (mLock) {
4540             if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
4541                 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
4542                 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
4543                 mDirty |= DIRTY_SETTINGS;
4544                 updatePowerStateLocked();
4545             }
4546         }
4547     }
4548 
4549     private void setDozeOverrideFromDreamManagerInternal(
4550             int screenState, @Display.StateReason int reason, float screenBrightnessFloat,
4551             int screenBrightnessInt, boolean useNormalBrightnessForDoze) {
4552         synchronized (mLock) {
4553             if (mDozeScreenStateOverrideFromDreamManager != screenState
4554                     || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightnessInt
4555                     || !BrightnessSynchronizer.floatEquals(
4556                     mDozeScreenBrightnessOverrideFromDreamManagerFloat, screenBrightnessFloat)
4557                     || mUseNormalBrightnessForDoze != useNormalBrightnessForDoze) {
4558                 mDozeScreenStateOverrideFromDreamManager = screenState;
4559                 mDozeScreenStateOverrideReasonFromDreamManager = reason;
4560                 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightnessInt;
4561                 mDozeScreenBrightnessOverrideFromDreamManagerFloat =
4562                         isValidBrightnessValue(screenBrightnessFloat)
4563                                 ? screenBrightnessFloat
4564                                 : BrightnessSynchronizer.brightnessIntToFloat(screenBrightnessInt);
4565                 mUseNormalBrightnessForDoze = useNormalBrightnessForDoze;
4566                 mDirty |= DIRTY_SETTINGS;
4567                 updatePowerStateLocked();
4568             }
4569         }
4570     }
4571 
4572     private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
4573         synchronized (mLock) {
4574             if (mDrawWakeLockOverrideFromSidekick != keepState) {
4575                 mDrawWakeLockOverrideFromSidekick = keepState;
4576                 mDirty |= DIRTY_SETTINGS;
4577                 updatePowerStateLocked();
4578             }
4579         }
4580     }
4581 
4582     private void setPowerBoostInternal(int boost, int durationMs) {
4583         // Maybe filter the event.
4584         mNativeWrapper.nativeSetPowerBoost(boost, durationMs);
4585     }
4586 
4587     private boolean setPowerModeInternal(int mode, boolean enabled) {
4588         // Maybe filter the event.
4589         if (mode == Mode.LAUNCH && enabled && mBatterySaverStateMachine != null
4590                 && mBatterySaverStateMachine.getBatterySaverController().isLaunchBoostDisabled()) {
4591             return false;
4592         }
4593         return mNativeWrapper.nativeSetPowerMode(mode, enabled);
4594     }
4595 
4596     @VisibleForTesting
4597     boolean wasDeviceIdleForInternal(long ms) {
4598         synchronized (mLock) {
4599             return mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP).getLastUserActivityTimeLocked()
4600                     + ms < mClock.uptimeMillis();
4601         }
4602     }
4603 
4604     @VisibleForTesting
4605     void onUserActivity() {
4606         synchronized (mLock) {
4607             mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP).setLastUserActivityTimeLocked(
4608                     mClock.uptimeMillis(), PowerManager.USER_ACTIVITY_EVENT_OTHER);
4609         }
4610     }
4611 
4612     private boolean forceSuspendInternal(int uid) {
4613         synchronized (mLock) {
4614             try {
4615                 mForceSuspendActive = true;
4616                 // Place the system in an non-interactive state
4617                 for (int idx = 0; idx < mPowerGroups.size(); idx++) {
4618                     sleepPowerGroupLocked(mPowerGroups.valueAt(idx), mClock.uptimeMillis(),
4619                             PowerManager.GO_TO_SLEEP_REASON_FORCE_SUSPEND, uid);
4620                 }
4621 
4622                 // Disable all the partial wake locks as well
4623                 updateWakeLockDisabledStatesLocked();
4624 
4625                 Slog.i(TAG, "Force-Suspending (uid " + uid + ")...");
4626                 boolean success = mNativeWrapper.nativeForceSuspend();
4627                 if (!success) {
4628                     Slog.i(TAG, "Force-Suspending failed in native.");
4629                 }
4630                 return success;
4631             } finally {
4632                 mForceSuspendActive = false;
4633                 // Re-enable wake locks once again.
4634                 updateWakeLockDisabledStatesLocked();
4635             }
4636         }
4637     }
4638 
4639     @GuardedBy("mLock")
4640     private void addPowerGroupsForNonDefaultDisplayGroupLocked() {
4641         IntArray displayGroupIds = mDisplayManagerInternal.getDisplayGroupIds();
4642         if (displayGroupIds == null) {
4643             return;
4644         }
4645 
4646         for (int i = 0; i < displayGroupIds.size(); i++) {
4647             int displayGroupId = displayGroupIds.get(i);
4648             if (displayGroupId == Display.DEFAULT_DISPLAY_GROUP) {
4649                 // Power group for the default display group is already added.
4650                 continue;
4651             }
4652             if (mPowerGroups.contains(displayGroupId)) {
4653                 Slog.e(TAG, "Tried to add already existing group:" + displayGroupId);
4654                 continue;
4655             }
4656             PowerGroup powerGroup = new PowerGroup(
4657                     displayGroupId,
4658                     mPowerGroupWakefulnessChangeListener,
4659                     mNotifier,
4660                     mDisplayManagerInternal,
4661                     WAKEFULNESS_AWAKE,
4662                     /* ready= */ false,
4663                     /* supportsSandman= */ false,
4664                     mClock.uptimeMillis(),
4665                     mFeatureFlags);
4666             mPowerGroups.append(displayGroupId, powerGroup);
4667         }
4668         mDirty |= DIRTY_DISPLAY_GROUP_WAKEFULNESS;
4669     }
4670 
4671     /**
4672      * Low-level function turn the device off immediately, without trying
4673      * to be clean.  Most people should use {@link ShutdownThread} for a clean shutdown.
4674      *
4675      * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
4676      */
4677     public static void lowLevelShutdown(String reason) {
4678         if (reason == null) {
4679             reason = "";
4680         }
4681         SystemProperties.set("sys.powerctl", "shutdown," + reason);
4682     }
4683 
4684     /**
4685      * Low-level function to reboot the device. On success, this
4686      * function doesn't return. If more than 20 seconds passes from
4687      * the time a reboot is requested, this method returns.
4688      *
4689      * @param reason code to pass to the kernel (e.g. "recovery"), or null.
4690      */
4691     public static void lowLevelReboot(String reason) {
4692         if (reason == null) {
4693             reason = "";
4694         }
4695 
4696         // If the reason is "quiescent", it means that the boot process should proceed
4697         // without turning on the screen/lights.
4698         // The "quiescent" property is sticky, meaning that any number
4699         // of subsequent reboots should honor the property until it is reset.
4700         if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
4701             sQuiescent = true;
4702             reason = "";
4703         } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
4704             sQuiescent = true;
4705             reason = reason.substring(0,
4706                     reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
4707         }
4708 
4709         if (reason.equals(PowerManager.REBOOT_RECOVERY)
4710                 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
4711             reason = "recovery";
4712         }
4713 
4714         if (sQuiescent) {
4715             // Pass the optional "quiescent" argument to the bootloader to let it know
4716             // that it should not turn the screen/lights on.
4717             if (!"".equals(reason)) {
4718                 reason += ",";
4719             }
4720             reason = reason + "quiescent";
4721         }
4722 
4723         SystemProperties.set("sys.powerctl", "reboot," + reason);
4724         try {
4725             Thread.sleep(20 * 1000L);
4726         } catch (InterruptedException e) {
4727             Thread.currentThread().interrupt();
4728         }
4729         Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
4730     }
4731 
4732     @Override // Watchdog.Monitor implementation
4733     public void monitor() {
4734         // Grab and release lock for watchdog monitor to detect deadlocks.
4735         synchronized (mLock) {
4736         }
4737     }
4738 
4739     @NeverCompile // Avoid size overhead of debugging code.
4740     private void dumpInternal(PrintWriter pw) {
4741         pw.println("POWER MANAGER (dumpsys power)\n");
4742 
4743         final WirelessChargerDetector wcd;
4744         final LowPowerStandbyController lowPowerStandbyController;
4745         synchronized (mLock) {
4746             pw.println("Power Manager State:");
4747             mConstants.dump(pw);
4748             pw.println("  mDirty=0x" + Integer.toHexString(mDirty));
4749             pw.println("  mWakefulness="
4750                     + PowerManagerInternal.wakefulnessToString(getGlobalWakefulnessLocked()));
4751             pw.println("  mWakefulnessChanging=" + mWakefulnessChanging);
4752             pw.println("  mIsPowered=" + mIsPowered);
4753             pw.println("  mPlugType=" + mPlugType);
4754             pw.println("  mBatteryLevel=" + mBatteryLevel);
4755             pw.println("  mDreamsBatteryLevelDrain=" + mDreamsBatteryLevelDrain);
4756             pw.println("  mDockState=" + mDockState);
4757             pw.println("  mStayOn=" + mStayOn);
4758             pw.println("  mProximityPositive=" + mProximityPositive);
4759             pw.println("  mBootCompleted=" + mBootCompleted);
4760             pw.println("  mSystemReady=" + mSystemReady);
4761             synchronized (mEnhancedDischargeTimeLock) {
4762                 pw.println("  mEnhancedDischargeTimeElapsed=" + mEnhancedDischargeTimeElapsed);
4763                 pw.println("  mLastEnhancedDischargeTimeUpdatedElapsed="
4764                         + mLastEnhancedDischargeTimeUpdatedElapsed);
4765                 pw.println("  mEnhancedDischargePredictionIsPersonalized="
4766                         + mEnhancedDischargePredictionIsPersonalized);
4767             }
4768             pw.println("  mUseAutoSuspend=" + mUseAutoSuspend);
4769             pw.println("  mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
4770             pw.println("  mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
4771             pw.println("  mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
4772             pw.print("  mNotifyLongScheduled=");
4773             if (mNotifyLongScheduled == 0) {
4774                 pw.print("(none)");
4775             } else {
4776                 TimeUtils.formatDuration(mNotifyLongScheduled, mClock.uptimeMillis(), pw);
4777             }
4778             pw.println();
4779             pw.print("  mNotifyLongDispatched=");
4780             if (mNotifyLongDispatched == 0) {
4781                 pw.print("(none)");
4782             } else {
4783                 TimeUtils.formatDuration(mNotifyLongDispatched, mClock.uptimeMillis(), pw);
4784             }
4785             pw.println();
4786             pw.print("  mNotifyLongNextCheck=");
4787             if (mNotifyLongNextCheck == 0) {
4788                 pw.print("(none)");
4789             } else {
4790                 TimeUtils.formatDuration(mNotifyLongNextCheck, mClock.uptimeMillis(), pw);
4791             }
4792             pw.println();
4793             pw.println("  mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
4794             pw.println("  mInterceptedPowerKeyForProximity="
4795                     + mInterceptedPowerKeyForProximity);
4796             pw.println("  mSandmanScheduled=" + mSandmanScheduled);
4797             pw.println("  mBatteryLevelLow=" + mBatteryLevelLow);
4798             pw.println("  mLightDeviceIdleMode=" + mLightDeviceIdleMode);
4799             pw.println("  mDeviceIdleMode=" + mDeviceIdleMode);
4800             pw.println("  mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
4801             pw.println("  mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
4802             pw.println("  mLowPowerStandbyActive=" + mLowPowerStandbyActive);
4803             pw.println("  mLastWakeTime=" + TimeUtils.formatUptime(mLastGlobalWakeTime));
4804             pw.println("  mLastSleepTime=" + TimeUtils.formatUptime(mLastGlobalSleepTime));
4805             pw.println("  mLastSleepReason=" + PowerManager.sleepReasonToString(
4806                     mLastGlobalSleepReason));
4807             pw.println("  mLastGlobalWakeTimeRealtime="
4808                     + TimeUtils.formatUptime(mLastGlobalWakeTimeRealtime));
4809             pw.println("  mLastGlobalSleepTimeRealtime="
4810                     + TimeUtils.formatUptime(mLastGlobalSleepTimeRealtime));
4811             pw.println("  mLastInteractivePowerHintTime="
4812                     + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
4813             pw.println("  mLastScreenBrightnessBoostTime="
4814                     + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
4815             pw.println("  mScreenBrightnessBoostInProgress="
4816                     + mScreenBrightnessBoostInProgress);
4817             pw.println("  mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
4818             pw.println("  mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
4819             pw.println("  mLastFlipTime=" + mLastFlipTime);
4820             pw.println("  mIsFaceDown=" + mIsFaceDown);
4821 
4822             pw.println();
4823             pw.println("Settings and Configuration:");
4824             pw.println("  mDecoupleHalAutoSuspendModeFromDisplayConfig="
4825                     + mDecoupleHalAutoSuspendModeFromDisplayConfig);
4826             pw.println("  mDecoupleHalInteractiveModeFromDisplayConfig="
4827                     + mDecoupleHalInteractiveModeFromDisplayConfig);
4828             pw.println("  mWakeUpWhenPluggedOrUnpluggedConfig="
4829                     + mWakeUpWhenPluggedOrUnpluggedConfig);
4830             pw.println("  mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
4831                     + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
4832             pw.println("  mTheaterModeEnabled="
4833                     + mTheaterModeEnabled);
4834             pw.println("  mKeepDreamingWhenUnplugging=" + mKeepDreamingWhenUnplugging);
4835             pw.println("  mSuspendWhenScreenOffDueToProximityConfig="
4836                     + mSuspendWhenScreenOffDueToProximityConfig);
4837             pw.println("  mDreamsSupportedConfig=" + mDreamsSupportedConfig);
4838             pw.println("  mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
4839             pw.println("  mDreamsActivatedOnSleepByDefaultConfig="
4840                     + mDreamsActivatedOnSleepByDefaultConfig);
4841             pw.println("  mDreamsActivatedOnDockByDefaultConfig="
4842                     + mDreamsActivatedOnDockByDefaultConfig);
4843             pw.println("  mDreamsActivatedWhilePosturedByDefaultConfig="
4844                     + mDreamsActivatedWhilePosturedByDefaultConfig);
4845             pw.println("  mDreamsEnabledOnBatteryConfig="
4846                     + mDreamsEnabledOnBatteryConfig);
4847             pw.println("  mDreamsBatteryLevelMinimumWhenPoweredConfig="
4848                     + mDreamsBatteryLevelMinimumWhenPoweredConfig);
4849             pw.println("  mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
4850                     + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
4851             pw.println("  mDreamsBatteryLevelDrainCutoffConfig="
4852                     + mDreamsBatteryLevelDrainCutoffConfig);
4853             pw.println("  mDreamsEnabledSetting=" + mDreamsEnabledSetting);
4854             pw.println("  mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
4855             pw.println("  mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
4856             pw.println("  mDreamsActivateWhilePosturedSetting="
4857                     + mDreamsActivateWhilePosturedSetting);
4858             pw.println("  mDozeAfterScreenOff=" + mDozeAfterScreenOff);
4859             pw.println("  mBrightWhenDozingConfig=" + mBrightWhenDozingConfig);
4860             pw.println("  mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
4861             pw.println("  mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
4862             pw.println("  mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
4863             pw.println("  mAttentiveTimeoutConfig=" + mAttentiveTimeoutConfig);
4864             pw.println("  mAttentiveTimeoutSetting=" + mAttentiveTimeoutSetting);
4865             pw.println("  mAttentiveWarningDurationConfig=" + mAttentiveWarningDurationConfig);
4866             pw.println("  mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
4867             pw.println("  mSleepTimeoutSetting=" + mSleepTimeoutSetting);
4868             pw.println("  mMaximumScreenOffTimeoutFromDeviceAdmin="
4869                     + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
4870                     + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
4871             pw.println("  mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
4872             pw.println("  mUserActivityTimeoutOverrideFromWindowManager="
4873                     + mUserActivityTimeoutOverrideFromWindowManager);
4874             pw.println("  mUserInactiveOverrideFromWindowManager="
4875                     + mUserInactiveOverrideFromWindowManager);
4876             pw.println("  mDozeScreenStateOverrideFromDreamManager="
4877                     + mDozeScreenStateOverrideFromDreamManager);
4878             pw.println("  mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
4879             pw.println("  mDozeScreenBrightnessOverrideFromDreamManager="
4880                     + mDozeScreenBrightnessOverrideFromDreamManager);
4881             pw.println("  mUseNormalBrightnessForDoze=" + mUseNormalBrightnessForDoze);
4882             pw.println("  mScreenBrightnessMinimum=" + mScreenBrightnessMinimum);
4883             pw.println("  mScreenBrightnessMaximum=" + mScreenBrightnessMaximum);
4884             pw.println("  mScreenBrightnessDefault=" + mScreenBrightnessDefault);
4885             pw.println("  mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
4886             pw.println("  mForegroundProfile=" + mForegroundProfile);
4887             pw.println("  mUserId=" + mUserId);
4888 
4889             final long attentiveTimeout = getAttentiveTimeoutLocked();
4890             final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
4891             final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, attentiveTimeout);
4892             final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
4893             pw.println();
4894             pw.println("Attentive timeout: " + attentiveTimeout + " ms");
4895             pw.println("Sleep timeout: " + sleepTimeout + " ms");
4896             pw.println("Screen off timeout: " + screenOffTimeout + " ms");
4897             pw.println("Screen dim duration: " + screenDimDuration + " ms");
4898 
4899             pw.println();
4900             pw.print("UID states (changing=");
4901             pw.print(mUidsChanging);
4902             pw.print(" changed=");
4903             pw.print(mUidsChanged);
4904             pw.println("):");
4905             for (int i=0; i<mUidState.size(); i++) {
4906                 final UidState state = mUidState.valueAt(i);
4907                 pw.print("  UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
4908                 pw.print(": ");
4909                 if (state.mActive) pw.print("  ACTIVE ");
4910                 else pw.print("INACTIVE ");
4911                 pw.print(" count=");
4912                 pw.print(state.mNumWakeLocks);
4913                 pw.print(" state=");
4914                 pw.println(state.mProcState);
4915             }
4916 
4917             pw.println();
4918             pw.println("Looper state:");
4919             mHandler.getLooper().dump(new PrintWriterPrinter(pw), "  ");
4920 
4921             pw.println();
4922             pw.println("Wake Locks: size=" + mWakeLocks.size());
4923             for (WakeLock wl : mWakeLocks) {
4924                 pw.println("  " + wl);
4925             }
4926 
4927             pw.println();
4928             pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
4929             for (SuspendBlocker sb : mSuspendBlockers) {
4930                 pw.println("  " + sb);
4931             }
4932 
4933             pw.println();
4934             pw.println("Display Power: " + mDisplayPowerCallbacks);
4935 
4936             if (mBatterySaverSupported) {
4937                 mBatterySaverStateMachine.getBatterySaverPolicy().dump(pw);
4938                 mBatterySaverStateMachine.dump(pw);
4939             } else {
4940                 pw.println("Battery Saver: DISABLED");
4941             }
4942             mAttentionDetector.dump(pw);
4943 
4944             pw.println();
4945             final int numProfiles = mProfilePowerState.size();
4946             pw.println("Profile power states: size=" + numProfiles);
4947             for (int i = 0; i < numProfiles; i++) {
4948                 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
4949                 pw.print("  mUserId=");
4950                 pw.print(profile.mUserId);
4951                 pw.print(" mScreenOffTimeout=");
4952                 pw.print(profile.mScreenOffTimeout);
4953                 pw.print(" mWakeLockSummary=");
4954                 pw.print(profile.mWakeLockSummary);
4955                 pw.print(" mLastUserActivityTime=");
4956                 pw.print(profile.mLastUserActivityTime);
4957                 pw.print(" mLockingNotified=");
4958                 pw.println(profile.mLockingNotified);
4959             }
4960 
4961             pw.println("Display Group User Activity:");
4962             for (int idx = 0; idx < mPowerGroups.size(); idx++) {
4963                 final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
4964                 pw.println("  displayGroupId=" + powerGroup.getGroupId());
4965                 pw.println("  userActivitySummary=0x" + Integer.toHexString(
4966                         powerGroup.getUserActivitySummaryLocked()));
4967                 pw.println("  lastUserActivityTime=" + TimeUtils.formatUptime(
4968                         powerGroup.getLastUserActivityTimeLocked()));
4969                 pw.println("  lastUserActivityTimeNoChangeLights=" + TimeUtils.formatUptime(
4970                         powerGroup.getLastUserActivityTimeNoChangeLightsLocked()));
4971                 pw.println("  mWakeLockSummary=0x" + Integer.toHexString(
4972                         powerGroup.getWakeLockSummaryLocked()));
4973             }
4974 
4975             wcd = mWirelessChargerDetector;
4976         }
4977 
4978         if (wcd != null) {
4979             wcd.dump(pw);
4980         }
4981 
4982         if (mNotifier != null) {
4983             mNotifier.dump(pw);
4984         }
4985 
4986         mFaceDownDetector.dump(pw);
4987 
4988         mAmbientDisplaySuppressionController.dump(pw);
4989 
4990         mLowPowerStandbyController.dump(pw);
4991 
4992         synchronized (mLock) {
4993             if (mScreenTimeoutOverridePolicy != null) {
4994                 mScreenTimeoutOverridePolicy.dump(pw);
4995             }
4996         }
4997 
4998         mFeatureFlags.dump(pw);
4999     }
5000 
5001     private void dumpProto(FileDescriptor fd) {
5002         final WirelessChargerDetector wcd;
5003         final LowPowerStandbyController lowPowerStandbyController;
5004         final ProtoOutputStream proto = new ProtoOutputStream(fd);
5005 
5006         synchronized (mLock) {
5007             mConstants.dumpProto(proto);
5008             proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
5009             proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, getGlobalWakefulnessLocked());
5010             proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
5011             proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
5012             proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
5013             proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
5014             proto.write(
5015                     PowerManagerServiceDumpProto.BATTERY_LEVEL_DRAINED_WHILE_DREAMING,
5016                     mDreamsBatteryLevelDrain);
5017             proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
5018             proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
5019             proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
5020             proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
5021             proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
5022             synchronized (mEnhancedDischargeTimeLock) {
5023                 proto.write(PowerManagerServiceDumpProto.ENHANCED_DISCHARGE_TIME_ELAPSED,
5024                         mEnhancedDischargeTimeElapsed);
5025                 proto.write(
5026                         PowerManagerServiceDumpProto.LAST_ENHANCED_DISCHARGE_TIME_UPDATED_ELAPSED,
5027                         mLastEnhancedDischargeTimeUpdatedElapsed);
5028                 proto.write(
5029                         PowerManagerServiceDumpProto.IS_ENHANCED_DISCHARGE_PREDICTION_PERSONALIZED,
5030                         mEnhancedDischargePredictionIsPersonalized);
5031             }
5032             proto.write(
5033                     PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
5034                     mHalAutoSuspendModeEnabled);
5035             proto.write(
5036                     PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
5037                     mHalInteractiveModeEnabled);
5038 
5039             final long activeWakeLocksToken = proto.start(
5040                     PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
5041             proto.write(
5042                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
5043                     (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
5044             proto.write(
5045                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
5046                     (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
5047             proto.write(
5048                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
5049                     (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
5050             proto.write(
5051                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
5052                     (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
5053             proto.write(
5054                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
5055                     (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
5056             proto.write(
5057                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
5058                     (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
5059             proto.write(
5060                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
5061                     (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
5062             proto.write(
5063                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
5064                     (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
5065             proto.end(activeWakeLocksToken);
5066 
5067             proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
5068             proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
5069             proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
5070 
5071             for (int idx = 0; idx < mPowerGroups.size(); idx++) {
5072                 final PowerGroup powerGroup = mPowerGroups.valueAt(idx);
5073                 final long userActivityToken = proto.start(
5074                         PowerManagerServiceDumpProto.USER_ACTIVITY);
5075                 proto.write(PowerManagerServiceDumpProto.UserActivityProto.DISPLAY_GROUP_ID,
5076                         powerGroup.getGroupId());
5077                 final long userActivitySummary = powerGroup.getUserActivitySummaryLocked();
5078                 proto.write(PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
5079                         (userActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
5080                 proto.write(PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
5081                         (userActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
5082                 proto.write(PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
5083                         (userActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
5084                 proto.write(
5085                         PowerManagerServiceDumpProto.UserActivityProto.LAST_USER_ACTIVITY_TIME_MS,
5086                         powerGroup.getLastUserActivityTimeLocked());
5087                 proto.write(
5088                         PowerManagerServiceDumpProto.UserActivityProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
5089                         powerGroup.getLastUserActivityTimeNoChangeLightsLocked());
5090                 proto.end(userActivityToken);
5091             }
5092 
5093             proto.write(
5094                     PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
5095                     mRequestWaitForNegativeProximity);
5096             proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
5097             proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
5098             proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
5099             proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
5100 
5101             for (int id : mDeviceIdleWhitelist) {
5102                 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
5103             }
5104             for (int id : mDeviceIdleTempWhitelist) {
5105                 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
5106             }
5107 
5108             proto.write(PowerManagerServiceDumpProto.IS_LOW_POWER_STANDBY_ACTIVE,
5109                     mLowPowerStandbyActive);
5110 
5111             proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastGlobalWakeTime);
5112             proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastGlobalSleepTime);
5113             proto.write(
5114                     PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
5115                     mLastInteractivePowerHintTime);
5116             proto.write(
5117                     PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
5118                     mLastScreenBrightnessBoostTime);
5119             proto.write(
5120                     PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
5121                     mScreenBrightnessBoostInProgress);
5122             proto.write(
5123                     PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
5124                     mHoldingWakeLockSuspendBlocker);
5125             proto.write(
5126                     PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
5127                     mHoldingDisplaySuspendBlocker);
5128 
5129             final long settingsAndConfigurationToken =
5130                     proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
5131             proto.write(
5132                     PowerServiceSettingsAndConfigurationDumpProto
5133                             .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
5134                     mDecoupleHalAutoSuspendModeFromDisplayConfig);
5135             proto.write(
5136                     PowerServiceSettingsAndConfigurationDumpProto
5137                             .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
5138                     mDecoupleHalInteractiveModeFromDisplayConfig);
5139             proto.write(
5140                     PowerServiceSettingsAndConfigurationDumpProto
5141                             .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
5142                     mWakeUpWhenPluggedOrUnpluggedConfig);
5143             proto.write(
5144                     PowerServiceSettingsAndConfigurationDumpProto
5145                             .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
5146                     mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
5147             proto.write(
5148                     PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
5149                     mTheaterModeEnabled);
5150             proto.write(
5151                     PowerServiceSettingsAndConfigurationDumpProto
5152                             .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
5153                     mSuspendWhenScreenOffDueToProximityConfig);
5154             proto.write(
5155                     PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
5156                     mDreamsSupportedConfig);
5157             proto.write(
5158                     PowerServiceSettingsAndConfigurationDumpProto
5159                             .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
5160                     mDreamsEnabledByDefaultConfig);
5161             proto.write(
5162                     PowerServiceSettingsAndConfigurationDumpProto
5163                             .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
5164                     mDreamsActivatedOnSleepByDefaultConfig);
5165             proto.write(
5166                     PowerServiceSettingsAndConfigurationDumpProto
5167                             .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
5168                     mDreamsActivatedOnDockByDefaultConfig);
5169             proto.write(
5170                     PowerServiceSettingsAndConfigurationDumpProto
5171                             .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
5172                     mDreamsEnabledOnBatteryConfig);
5173             proto.write(
5174                     PowerServiceSettingsAndConfigurationDumpProto
5175                             .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
5176                     mDreamsBatteryLevelMinimumWhenPoweredConfig);
5177             proto.write(
5178                     PowerServiceSettingsAndConfigurationDumpProto
5179                             .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
5180                     mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
5181             proto.write(
5182                     PowerServiceSettingsAndConfigurationDumpProto
5183                             .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
5184                     mDreamsBatteryLevelDrainCutoffConfig);
5185             proto.write(
5186                     PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
5187                     mDreamsEnabledSetting);
5188             proto.write(
5189                     PowerServiceSettingsAndConfigurationDumpProto
5190                             .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
5191                     mDreamsActivateOnSleepSetting);
5192             proto.write(
5193                     PowerServiceSettingsAndConfigurationDumpProto
5194                             .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
5195                     mDreamsActivateOnDockSetting);
5196             proto.write(
5197                     PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
5198                     mDozeAfterScreenOff);
5199             proto.write(
5200                     PowerServiceSettingsAndConfigurationDumpProto
5201                             .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
5202                     mMinimumScreenOffTimeoutConfig);
5203             proto.write(
5204                     PowerServiceSettingsAndConfigurationDumpProto
5205                             .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
5206                     mMaximumScreenDimDurationConfig);
5207             proto.write(
5208                     PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
5209                     mMaximumScreenDimRatioConfig);
5210             proto.write(
5211                     PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
5212                     mScreenOffTimeoutSetting);
5213             proto.write(
5214                     PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
5215                     mSleepTimeoutSetting);
5216             proto.write(
5217                     PowerServiceSettingsAndConfigurationDumpProto.ATTENTIVE_TIMEOUT_SETTING_MS,
5218                     mAttentiveTimeoutSetting);
5219             proto.write(
5220                     PowerServiceSettingsAndConfigurationDumpProto.ATTENTIVE_TIMEOUT_CONFIG_MS,
5221                     mAttentiveTimeoutConfig);
5222             proto.write(
5223                     PowerServiceSettingsAndConfigurationDumpProto
5224                             .ATTENTIVE_WARNING_DURATION_CONFIG_MS,
5225                     mAttentiveWarningDurationConfig);
5226             proto.write(
5227                     PowerServiceSettingsAndConfigurationDumpProto
5228                             .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
5229                     // Clamp to int32
5230                     Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
5231             proto.write(
5232                     PowerServiceSettingsAndConfigurationDumpProto
5233                             .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
5234                     isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
5235 
5236             final long stayOnWhilePluggedInToken =
5237                     proto.start(
5238                             PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
5239             proto.write(
5240                     PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
5241                             .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
5242                     ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
5243             proto.write(
5244                     PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
5245                             .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
5246                     ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
5247             proto.write(
5248                     PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
5249                             .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
5250                     ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
5251                             != 0));
5252             proto.write(
5253                     PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
5254                             .IS_STAY_ON_WHILE_PLUGGED_IN_DOCK,
5255                     ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_DOCK)
5256                             != 0));
5257             proto.end(stayOnWhilePluggedInToken);
5258 
5259             proto.write(
5260                     PowerServiceSettingsAndConfigurationDumpProto
5261                             .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
5262                     mUserActivityTimeoutOverrideFromWindowManager);
5263             proto.write(
5264                     PowerServiceSettingsAndConfigurationDumpProto
5265                             .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
5266                     mUserInactiveOverrideFromWindowManager);
5267             proto.write(
5268                     PowerServiceSettingsAndConfigurationDumpProto
5269                             .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
5270                     mDozeScreenStateOverrideFromDreamManager);
5271             proto.write(
5272                     PowerServiceSettingsAndConfigurationDumpProto
5273                             .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
5274                     mDrawWakeLockOverrideFromSidekick);
5275             proto.write(
5276                     PowerServiceSettingsAndConfigurationDumpProto
5277                             .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
5278                     mDozeScreenBrightnessOverrideFromDreamManager);
5279 
5280             final long screenBrightnessSettingLimitsToken =
5281                     proto.start(
5282                             PowerServiceSettingsAndConfigurationDumpProto
5283                                     .SCREEN_BRIGHTNESS_SETTING_LIMITS);
5284             proto.write(
5285                     PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
5286                             .SETTING_MINIMUM_FLOAT,
5287                     mScreenBrightnessMinimum);
5288             proto.write(
5289                     PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
5290                             .SETTING_MAXIMUM_FLOAT,
5291                     mScreenBrightnessMaximum);
5292             proto.write(
5293                     PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
5294                             .SETTING_DEFAULT_FLOAT,
5295                     mScreenBrightnessDefault);
5296             proto.end(screenBrightnessSettingLimitsToken);
5297 
5298             proto.write(
5299                     PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
5300                     mDoubleTapWakeEnabled);
5301             proto.end(settingsAndConfigurationToken);
5302 
5303             final long attentiveTimeout = getAttentiveTimeoutLocked();
5304             final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
5305             final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, attentiveTimeout);
5306             final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
5307             proto.write(PowerManagerServiceDumpProto.ATTENTIVE_TIMEOUT_MS, attentiveTimeout);
5308             proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
5309             proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
5310             proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
5311             proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
5312             proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
5313 
5314             for (int i = 0; i < mUidState.size(); i++) {
5315                 final UidState state = mUidState.valueAt(i);
5316                 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
5317                 final int uid = mUidState.keyAt(i);
5318                 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
5319                 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
5320                 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
5321                 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
5322                 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
5323                         ActivityManager.processStateAmToProto(state.mProcState));
5324                 proto.end(uIDToken);
5325             }
5326 
5327             if (mBatterySaverSupported) {
5328                 mBatterySaverStateMachine.dumpProto(proto,
5329                         PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
5330             }
5331 
5332             mHandler.getLooper().dumpDebug(proto, PowerManagerServiceDumpProto.LOOPER);
5333 
5334             for (WakeLock wl : mWakeLocks) {
5335                 wl.dumpDebug(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
5336             }
5337 
5338             for (SuspendBlocker sb : mSuspendBlockers) {
5339                 sb.dumpDebug(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
5340             }
5341 
5342             wcd = mWirelessChargerDetector;
5343         }
5344 
5345         if (wcd != null) {
5346             wcd.dumpDebug(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
5347         }
5348 
5349         mLowPowerStandbyController.dumpProto(proto,
5350                 PowerManagerServiceDumpProto.LOW_POWER_STANDBY_CONTROLLER);
5351 
5352         proto.flush();
5353     }
5354 
5355     private void incrementBootCount() {
5356         synchronized (mLock) {
5357             int count;
5358             try {
5359                 count = Settings.Global.getInt(
5360                         getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
5361             } catch (SettingNotFoundException e) {
5362                 count = 0;
5363             }
5364             Settings.Global.putInt(
5365                     getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
5366         }
5367     }
5368 
5369     private static WorkSource copyWorkSource(WorkSource workSource) {
5370         return workSource != null ? new WorkSource(workSource) : null;
5371     }
5372 
5373     @VisibleForTesting
5374     final class BatteryReceiver extends BroadcastReceiver {
5375         @Override
5376         public void onReceive(Context context, Intent intent) {
5377             synchronized (mLock) {
5378                 handleBatteryStateChangedLocked();
5379             }
5380         }
5381     }
5382 
5383     private final class DreamReceiver extends BroadcastReceiver {
5384         @Override
5385         public void onReceive(Context context, Intent intent) {
5386             synchronized (mLock) {
5387                 scheduleSandmanLocked();
5388             }
5389         }
5390     }
5391 
5392     @VisibleForTesting
5393     final class UserSwitchedReceiver extends BroadcastReceiver {
5394         @Override
5395         public void onReceive(Context context, Intent intent) {
5396             synchronized (mLock) {
5397                 handleSettingsChangedLocked();
5398             }
5399         }
5400     }
5401 
5402     private final class DockReceiver extends BroadcastReceiver {
5403         @Override
5404         public void onReceive(Context context, Intent intent) {
5405             synchronized (mLock) {
5406                 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
5407                         Intent.EXTRA_DOCK_STATE_UNDOCKED);
5408                 if (mDockState != dockState) {
5409                     FrameworkStatsLog.write(FrameworkStatsLog.DOCK_STATE_CHANGED, dockState);
5410                     mDockState = dockState;
5411                     mDirty |= DIRTY_DOCK_STATE;
5412                     updatePowerStateLocked();
5413                 }
5414             }
5415         }
5416     }
5417 
5418     private final class SettingsObserver extends ContentObserver {
5419         public SettingsObserver(Handler handler) {
5420             super(handler);
5421         }
5422 
5423         @Override
5424         public void onChange(boolean selfChange, Uri uri) {
5425             synchronized (mLock) {
5426                 handleSettingsChangedLocked();
5427             }
5428         }
5429     }
5430 
5431     private final AmbientDisplaySuppressionChangedCallback mAmbientSuppressionChangedCallback =
5432             new AmbientDisplaySuppressionChangedCallback() {
5433                 @Override
5434                 public void onSuppressionChanged(boolean isSuppressed) {
5435                     synchronized (mLock) {
5436                         onDreamSuppressionChangedLocked(isSuppressed);
5437                     }
5438                 }
5439             };
5440 
5441     /**
5442      * Callback for asynchronous operations performed by the power manager.
5443      */
5444     private final class PowerManagerHandlerCallback implements Handler.Callback {
5445         @Override
5446         public boolean handleMessage(Message msg) {
5447             switch (msg.what) {
5448                 case MSG_USER_ACTIVITY_TIMEOUT:
5449                     handleUserActivityTimeout();
5450                     break;
5451                 case MSG_SANDMAN:
5452                     handleSandman(msg.arg1);
5453                     break;
5454                 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
5455                     handleScreenBrightnessBoostTimeout();
5456                     break;
5457                 case MSG_CHECK_FOR_LONG_WAKELOCKS:
5458                     checkForLongWakeLocks();
5459                     break;
5460                 case MSG_ATTENTIVE_TIMEOUT:
5461                     handleAttentiveTimeout();
5462                     break;
5463                 case MSG_RELEASE_ALL_OVERRIDE_WAKE_LOCKS:
5464                     releaseAllOverrideWakeLocks(msg.arg1);
5465                     break;
5466             }
5467 
5468             return true;
5469         }
5470     }
5471 
5472     /**
5473      * Represents a wake lock that has been acquired by an application.
5474      */
5475     /* package */ final class WakeLock implements IBinder.DeathRecipient {
5476         public final IBinder mLock;
5477         public final int mDisplayId;
5478         public int mFlags;
5479         public String mTag;
5480         public final String mPackageName;
5481         public WorkSource mWorkSource;
5482         public String mHistoryTag;
5483         public final int mOwnerUid;
5484         public final int mOwnerPid;
5485         public final UidState mUidState;
5486         public long mAcquireTime;
5487         public boolean mNotifiedAcquired;
5488         public boolean mNotifiedLong;
5489         public boolean mDisabled;
5490         public IWakeLockCallback mCallback;
5491 
5492         public WakeLock(IBinder lock, int displayId, int flags, String tag, String packageName,
5493                 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
5494                 UidState uidState, @Nullable IWakeLockCallback callback) {
5495             mLock = lock;
5496             mDisplayId = displayId;
5497             mFlags = flags;
5498             mTag = tag;
5499             mPackageName = packageName;
5500             mWorkSource = copyWorkSource(workSource);
5501             mHistoryTag = historyTag;
5502             mOwnerUid = ownerUid;
5503             mOwnerPid = ownerPid;
5504             mUidState = uidState;
5505             mCallback = callback;
5506             linkToDeath();
5507         }
5508 
5509         @Override
5510         public void binderDied() {
5511             unlinkToDeath();
5512             PowerManagerService.this.handleWakeLockDeath(this);
5513         }
5514 
5515         private void linkToDeath() {
5516             try {
5517                 mLock.linkToDeath(this, 0);
5518             } catch (RemoteException e) {
5519                 throw new IllegalArgumentException("Wakelock.mLock is already dead.");
5520             }
5521         }
5522 
5523         @GuardedBy("mLock")
5524         void unlinkToDeath() {
5525             try {
5526                 mLock.unlinkToDeath(this, 0);
5527             } catch (NoSuchElementException e) {
5528                 Slog.wtf(TAG, "Failed to unlink Wakelock.mLock", e);
5529             }
5530         }
5531 
5532         public boolean setDisabled(boolean disabled) {
5533             if (mDisabled != disabled) {
5534                 mDisabled = disabled;
5535                 return true;
5536             } else {
5537                 return false;
5538             }
5539         }
5540         public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
5541                 int ownerUid, int ownerPid, IWakeLockCallback callback) {
5542             return mFlags == flags
5543                     && mTag.equals(tag)
5544                     && hasSameWorkSource(workSource)
5545                     && mOwnerUid == ownerUid
5546                     && mOwnerPid == ownerPid;
5547         }
5548 
5549         public void updateProperties(int flags, String tag, String packageName,
5550                 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
5551                 IWakeLockCallback callback) {
5552             if (!mPackageName.equals(packageName)) {
5553                 throw new IllegalStateException("Existing wake lock package name changed: "
5554                         + mPackageName + " to " + packageName);
5555             }
5556             if (mOwnerUid != ownerUid) {
5557                 throw new IllegalStateException("Existing wake lock uid changed: "
5558                         + mOwnerUid + " to " + ownerUid);
5559             }
5560             if (mOwnerPid != ownerPid) {
5561                 throw new IllegalStateException("Existing wake lock pid changed: "
5562                         + mOwnerPid + " to " + ownerPid);
5563             }
5564             mFlags = flags;
5565             mTag = tag;
5566             updateWorkSource(workSource);
5567             mHistoryTag = historyTag;
5568             mCallback = callback;
5569         }
5570 
5571         public boolean hasSameWorkSource(WorkSource workSource) {
5572             return Objects.equals(mWorkSource, workSource);
5573         }
5574 
5575         public void updateWorkSource(WorkSource workSource) {
5576             mWorkSource = copyWorkSource(workSource);
5577         }
5578 
5579         /** Returns the PowerGroup Id of this wakeLock or {@code null} if info not available.. */
5580         public Integer getPowerGroupId() {
5581             if (!mSystemReady || mDisplayId == Display.INVALID_DISPLAY) {
5582                 return Display.INVALID_DISPLAY_GROUP;
5583             }
5584 
5585             final DisplayInfo displayInfo = mDisplayManagerInternal.getDisplayInfo(mDisplayId);
5586             if (displayInfo != null) {
5587                 return displayInfo.displayGroupId;
5588             }
5589 
5590             return null;
5591         }
5592 
5593         @Override
5594         public String toString() {
5595             StringBuilder sb = new StringBuilder();
5596             sb.append(getLockLevelString());
5597             sb.append(" '");
5598             sb.append(mTag);
5599             sb.append("'");
5600             sb.append(getLockFlagsString());
5601             if (mDisabled) {
5602                 sb.append(" DISABLED");
5603             }
5604             if (mNotifiedAcquired) {
5605                 sb.append(" ACQ=");
5606                 TimeUtils.formatDuration(mAcquireTime-mClock.uptimeMillis(), sb);
5607             }
5608             if (mNotifiedLong) {
5609                 sb.append(" LONG");
5610             }
5611             sb.append(" (uid=");
5612             sb.append(mOwnerUid);
5613             if (mOwnerPid != 0) {
5614                 sb.append(" pid=");
5615                 sb.append(mOwnerPid);
5616             }
5617             if (mWorkSource != null) {
5618                 sb.append(" ws=");
5619                 sb.append(mWorkSource);
5620             }
5621             sb.append(")");
5622             return sb.toString();
5623         }
5624 
5625         public void dumpDebug(ProtoOutputStream proto, long fieldId) {
5626             final long wakeLockToken = proto.start(fieldId);
5627             proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
5628             proto.write(WakeLockProto.TAG, mTag);
5629 
5630             final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
5631             proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
5632                     (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
5633             proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
5634                     (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
5635             proto.write(WakeLockProto.WakeLockFlagsProto.SYSTEM_WAKELOCK,
5636                     (mFlags & PowerManager.SYSTEM_WAKELOCK) != 0);
5637             proto.end(wakeLockFlagsToken);
5638 
5639             proto.write(WakeLockProto.IS_DISABLED, mDisabled);
5640             if (mNotifiedAcquired) {
5641                 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
5642             }
5643             proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
5644             proto.write(WakeLockProto.UID, mOwnerUid);
5645             proto.write(WakeLockProto.PID, mOwnerPid);
5646 
5647             if (mWorkSource != null) {
5648                 mWorkSource.dumpDebug(proto, WakeLockProto.WORK_SOURCE);
5649             }
5650             proto.end(wakeLockToken);
5651         }
5652 
5653         @SuppressWarnings("deprecation")
5654         private String getLockLevelString() {
5655             switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
5656                 case PowerManager.FULL_WAKE_LOCK:
5657                     return "FULL_WAKE_LOCK                   ";
5658                 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
5659                     return "SCREEN_BRIGHT_WAKE_LOCK          ";
5660                 case PowerManager.SCREEN_DIM_WAKE_LOCK:
5661                     return "SCREEN_DIM_WAKE_LOCK             ";
5662                 case PowerManager.PARTIAL_WAKE_LOCK:
5663                     return "PARTIAL_WAKE_LOCK                ";
5664                 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
5665                     return "PROXIMITY_SCREEN_OFF_WAKE_LOCK   ";
5666                 case PowerManager.DOZE_WAKE_LOCK:
5667                     return "DOZE_WAKE_LOCK                   ";
5668                 case PowerManager.DRAW_WAKE_LOCK:
5669                     return "DRAW_WAKE_LOCK                   ";
5670                 case PowerManager.SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK:
5671                     return "SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK";
5672                 default:
5673                     return "???                              ";
5674             }
5675         }
5676 
5677         private String getLockFlagsString() {
5678             String result = "";
5679             if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
5680                 result += " ACQUIRE_CAUSES_WAKEUP";
5681             }
5682             if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
5683                 result += " ON_AFTER_RELEASE";
5684             }
5685             if ((mFlags & PowerManager.SYSTEM_WAKELOCK) != 0) {
5686                 result += " SYSTEM_WAKELOCK";
5687             }
5688             return result;
5689         }
5690     }
5691 
5692     private final class SuspendBlockerImpl implements SuspendBlocker {
5693         private static final String UNKNOWN_ID = "unknown";
5694         private final String mName;
5695         private final int mNameHash;
5696         private int mReferenceCount;
5697 
5698         // Maps suspend blocker IDs to a list (LongArray) of open acquisitions for the suspend
5699         // blocker. Each value is a timestamp of when the acquisition was made.
5700         private final ArrayMap<String, LongArray> mOpenReferenceTimes = new ArrayMap<>();
5701 
5702         public SuspendBlockerImpl(String name) {
5703             mName = name;
5704             mNameHash = mName.hashCode();
5705         }
5706 
5707         @Override
5708         protected void finalize() throws Throwable {
5709             try {
5710                 if (mReferenceCount != 0) {
5711                     Slog.wtf(TAG, "Suspend blocker \"" + mName
5712                             + "\" was finalized without being released!");
5713                     mReferenceCount = 0;
5714                     mNativeWrapper.nativeReleaseSuspendBlocker(mName);
5715                     Trace.asyncTraceForTrackEnd(Trace.TRACE_TAG_POWER,
5716                             "SuspendBlockers", mNameHash);
5717                 }
5718             } finally {
5719                 super.finalize();
5720             }
5721         }
5722 
5723         @Override
5724         public void acquire() {
5725             acquire(UNKNOWN_ID);
5726         }
5727 
5728         @Override
5729         public void acquire(String id) {
5730             synchronized (this) {
5731                 recordReferenceLocked(id);
5732                 mReferenceCount += 1;
5733                 if (mReferenceCount == 1) {
5734                     if (DEBUG_SPEW) {
5735                         Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
5736                     }
5737                     Trace.asyncTraceForTrackBegin(Trace.TRACE_TAG_POWER,
5738                             "SuspendBlockers", mName, mNameHash);
5739                     mNativeWrapper.nativeAcquireSuspendBlocker(mName);
5740                 }
5741             }
5742         }
5743 
5744         @Override
5745         public void release() {
5746             release(UNKNOWN_ID);
5747         }
5748 
5749         @Override
5750         public void release(String id) {
5751             synchronized (this) {
5752                 removeReferenceLocked(id);
5753                 mReferenceCount -= 1;
5754                 if (mReferenceCount == 0) {
5755                     if (DEBUG_SPEW) {
5756                         Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
5757                     }
5758                     mNativeWrapper.nativeReleaseSuspendBlocker(mName);
5759                     if (Trace.isTagEnabled(Trace.TRACE_TAG_POWER)) {
5760                         Trace.asyncTraceForTrackEnd(Trace.TRACE_TAG_POWER,
5761                                 "SuspendBlockers", mNameHash);
5762                     }
5763                 } else if (mReferenceCount < 0) {
5764                     Slog.wtf(TAG, "Suspend blocker \"" + mName
5765                             + "\" was released without being acquired!", new Throwable());
5766                     mReferenceCount = 0;
5767                 }
5768             }
5769         }
5770 
5771         @Override
5772         public String toString() {
5773             synchronized (this) {
5774                 StringBuilder builder = new StringBuilder();
5775                 builder.append(mName);
5776                 builder.append(": ref count=").append(mReferenceCount);
5777                 builder.append(" [");
5778                 int size = mOpenReferenceTimes.size();
5779                 for (int i = 0; i < size; i++) {
5780                     String id = mOpenReferenceTimes.keyAt(i);
5781                     LongArray times = mOpenReferenceTimes.valueAt(i);
5782                     if (times == null || times.size() == 0) {
5783                         continue;
5784                     }
5785 
5786                     if (i > 0) {
5787                         builder.append(", ");
5788                     }
5789                     builder.append(id).append(": (");
5790                     for (int j = 0; j < times.size(); j++) {
5791                         if (j > 0) {
5792                             builder.append(", ");
5793                         }
5794                         builder.append(DATE_FORMAT.format(new Date(times.get(j))));
5795                     }
5796                     builder.append(")");
5797                 }
5798                 builder.append("]");
5799                 return builder.toString();
5800             }
5801         }
5802 
5803         public void dumpDebug(ProtoOutputStream proto, long fieldId) {
5804             final long sbToken = proto.start(fieldId);
5805             synchronized (this) {
5806                 proto.write(SuspendBlockerProto.NAME, mName);
5807                 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
5808             }
5809             proto.end(sbToken);
5810         }
5811 
5812         private void recordReferenceLocked(String id) {
5813             LongArray times = mOpenReferenceTimes.get(id);
5814             if (times == null) {
5815                 times = new LongArray(2);
5816                 mOpenReferenceTimes.put(id, times);
5817             }
5818             times.add(System.currentTimeMillis());
5819         }
5820 
5821         private void removeReferenceLocked(String id) {
5822             LongArray times = mOpenReferenceTimes.get(id);
5823             if (times != null && times.size() > 0) {
5824                 times.remove(times.size() - 1);
5825                 if (times.size() == 0) {
5826                     mOpenReferenceTimes.remove(id);
5827                 }
5828             }
5829         }
5830     }
5831 
5832     static final class UidState {
5833         final int mUid;
5834         int mNumWakeLocks;
5835         int mProcState;
5836         boolean mActive;
5837 
5838         UidState(int uid) {
5839             mUid = uid;
5840         }
5841     }
5842 
5843     @VisibleForTesting
5844     final class BinderService extends IPowerManager.Stub {
5845         private final PowerManagerShellCommand mShellCommand;
5846 
5847         BinderService(Context context) {
5848             mShellCommand = new PowerManagerShellCommand(context, this);
5849         }
5850 
5851         @Override
5852         public void onShellCommand(FileDescriptor in, FileDescriptor out,
5853                 FileDescriptor err, String[] args, ShellCallback callback,
5854                 ResultReceiver resultReceiver) {
5855             mShellCommand.exec(this, in, out, err, args, callback, resultReceiver);
5856         }
5857 
5858         @Override // Binder call
5859         public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
5860                 String packageName, int uid, int displayId, IWakeLockCallback callback) {
5861             if (uid < 0) {
5862                 uid = Binder.getCallingUid();
5863             }
5864             acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null,
5865                     displayId, callback);
5866         }
5867 
5868         @Override // Binder call
5869         public void setPowerBoost(int boost, int durationMs) {
5870             if (!mSystemReady) {
5871                 // Service not ready yet, so who the heck cares about power hints, bah.
5872                 return;
5873             }
5874             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
5875             setPowerBoostInternal(boost, durationMs);
5876         }
5877 
5878         @Override // Binder call
5879         public void setPowerMode(int mode, boolean enabled) {
5880             if (!mSystemReady) {
5881                 // Service not ready yet, so who the heck cares about power hints, bah.
5882                 return;
5883             }
5884             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
5885             setPowerModeInternal(mode, enabled); // Intentionally ignore return value
5886         }
5887 
5888         @Override // Binder call
5889         public boolean setPowerModeChecked(int mode, boolean enabled) {
5890             if (!mSystemReady) {
5891                 // Service not ready yet, so who the heck cares about power hints, bah.
5892                 return false;
5893             }
5894             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
5895             return setPowerModeInternal(mode, enabled);
5896         }
5897 
5898         @Override // Binder call
5899         @RequiresPermission(value = android.Manifest.permission.TURN_SCREEN_ON, conditional = true)
5900         public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
5901                 WorkSource ws, String historyTag, int displayId,
5902                 @Nullable IWakeLockCallback callback) {
5903             if (lock == null) {
5904                 throw new IllegalArgumentException("lock must not be null");
5905             }
5906             if (packageName == null) {
5907                 throw new IllegalArgumentException("packageName must not be null");
5908             }
5909             PowerManager.validateWakeLockParameters(flags, tag);
5910 
5911             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
5912             if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
5913                 mContext.enforceCallingOrSelfPermission(
5914                         android.Manifest.permission.DEVICE_POWER, null);
5915             }
5916 
5917             if ((flags & PowerManager.SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK) != 0) {
5918                 if (!mFeatureFlags.isEarlyScreenTimeoutDetectorEnabled()) {
5919                     throw new IllegalArgumentException("Acquiring an unsupported wake lock:"
5920                             + " flags=" + flags + ", tag=" + tag);
5921                 }
5922 
5923                 mContext.enforceCallingOrSelfPermission(
5924                         android.Manifest.permission.SCREEN_TIMEOUT_OVERRIDE, null);
5925             }
5926 
5927             if (ws != null && !ws.isEmpty()) {
5928                 mContext.enforceCallingOrSelfPermission(
5929                         android.Manifest.permission.UPDATE_DEVICE_STATS, null);
5930             } else {
5931                 ws = null;
5932             }
5933 
5934             int uid = Binder.getCallingUid();
5935             int pid = Binder.getCallingPid();
5936 
5937             if ((flags & PowerManager.SYSTEM_WAKELOCK) != 0) {
5938                 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
5939                         null);
5940                 WorkSource workSource = new WorkSource(Binder.getCallingUid(), packageName);
5941                 if (ws != null && !ws.isEmpty()) {
5942                     workSource.add(ws);
5943                 }
5944                 ws = workSource;
5945 
5946                 uid = Process.myUid();
5947                 pid = Process.myPid();
5948             }
5949 
5950             final long ident = Binder.clearCallingIdentity();
5951             try {
5952                 acquireWakeLockInternal(lock, displayId, flags, tag, packageName, ws, historyTag,
5953                         uid, pid, callback);
5954             } finally {
5955                 Binder.restoreCallingIdentity(ident);
5956             }
5957         }
5958 
5959         @Override // Binder call
5960         public void acquireWakeLockAsync(IBinder lock, int flags, String tag, String packageName,
5961                 WorkSource ws, String historyTag) {
5962             acquireWakeLock(lock, flags, tag, packageName, ws, historyTag, Display.INVALID_DISPLAY,
5963                     null);
5964         }
5965 
5966         @Override // Binder call
5967         public void releaseWakeLock(IBinder lock, int flags) {
5968             if (lock == null) {
5969                 throw new IllegalArgumentException("lock must not be null");
5970             }
5971 
5972             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
5973 
5974             final long ident = Binder.clearCallingIdentity();
5975             try {
5976                 releaseWakeLockInternal(lock, flags);
5977             } finally {
5978                 Binder.restoreCallingIdentity(ident);
5979             }
5980         }
5981 
5982         @Override // Binder call
5983         public void releaseWakeLockAsync(IBinder lock, int flags) {
5984             releaseWakeLock(lock, flags);
5985         }
5986 
5987         @Override // Binder call
5988         public void updateWakeLockUids(IBinder lock, int[] uids) {
5989             WorkSource ws = null;
5990 
5991             if (uids != null) {
5992                 ws = new WorkSource();
5993                 if (mFeatureFlags.isWakelockAttributionViaWorkchainEnabled()) {
5994                     int callingUid = Binder.getCallingUid();
5995                     for (int uid : uids) {
5996                         WorkChain workChain = ws.createWorkChain();
5997                         workChain.addNode(uid, null);
5998                         workChain.addNode(callingUid, null);
5999                     }
6000                 } else {
6001                     // XXX should WorkSource have a way to set uids as an int[] instead of
6002                     // adding them one at a time?
6003                     for (int uid : uids) {
6004                         ws.add(uid);
6005                     }
6006                 }
6007             }
6008             updateWakeLockWorkSource(lock, ws, null);
6009         }
6010 
6011         @Override // Binder call
6012         public void updateWakeLockUidsAsync(IBinder lock, int[] uids) {
6013             updateWakeLockUids(lock, uids);
6014         }
6015 
6016         @Override // Binder call
6017         public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
6018             if (lock == null) {
6019                 throw new IllegalArgumentException("lock must not be null");
6020             }
6021 
6022             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
6023             if (ws != null && !ws.isEmpty()) {
6024                 mContext.enforceCallingOrSelfPermission(
6025                         android.Manifest.permission.UPDATE_DEVICE_STATS, null);
6026             } else {
6027                 ws = null;
6028             }
6029 
6030             final int callingUid = Binder.getCallingUid();
6031             final long ident = Binder.clearCallingIdentity();
6032             try {
6033                 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
6034             } finally {
6035                 Binder.restoreCallingIdentity(ident);
6036             }
6037         }
6038 
6039         @Override // Binder call
6040         public void updateWakeLockCallback(IBinder lock, IWakeLockCallback callback) {
6041             if (lock == null) {
6042                 throw new IllegalArgumentException("lock must not be null");
6043             }
6044 
6045             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
6046 
6047             final int callingUid = Binder.getCallingUid();
6048             final long ident = Binder.clearCallingIdentity();
6049             try {
6050                 updateWakeLockCallbackInternal(lock, callback, callingUid);
6051             } finally {
6052                 Binder.restoreCallingIdentity(ident);
6053             }
6054         }
6055 
6056         @Override // Binder call
6057         public boolean isWakeLockLevelSupported(int level) {
6058             final long ident = Binder.clearCallingIdentity();
6059             try {
6060                 return isWakeLockLevelSupportedInternal(level, Display.DEFAULT_DISPLAY);
6061             } finally {
6062                 Binder.restoreCallingIdentity(ident);
6063             }
6064         }
6065 
6066         @Override // Binder call
6067         public boolean isWakeLockLevelSupportedWithDisplayId(int level, int displayId) {
6068             final long ident = Binder.clearCallingIdentity();
6069             try {
6070                 return isWakeLockLevelSupportedInternal(level, displayId);
6071             } finally {
6072                 Binder.restoreCallingIdentity(ident);
6073             }
6074         }
6075 
6076         @Override // Binder call
6077         public void addScreenTimeoutPolicyListener(int displayId,
6078                 IScreenTimeoutPolicyListener listener) {
6079             if (!mFeatureFlags.isScreenTimeoutPolicyListenerApiEnabled()) {
6080                 throw new IllegalStateException("Screen timeout policy listener API flag "
6081                         + "is not enabled");
6082             }
6083 
6084             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
6085                     null);
6086 
6087             if (displayId == Display.INVALID_DISPLAY) {
6088                 throw new IllegalArgumentException("Valid display id is expected");
6089             }
6090 
6091             final long ident = Binder.clearCallingIdentity();
6092             try {
6093                 int initialTimeoutPolicy;
6094                 final int displayGroupId = mDisplayManagerInternal.getGroupIdForDisplay(displayId);
6095                 synchronized (mLock) {
6096                     final PowerGroup powerGroup = mPowerGroups.get(displayGroupId);
6097                     if (powerGroup != null) {
6098                         initialTimeoutPolicy = powerGroup.getScreenTimeoutPolicy();
6099                     } else {
6100                         throw new IllegalArgumentException("No display found for the specified "
6101                                 + "display id " + displayId);
6102                     }
6103                 }
6104 
6105                 mNotifier.addScreenTimeoutPolicyListener(displayId, initialTimeoutPolicy,
6106                         listener);
6107             } finally {
6108                 Binder.restoreCallingIdentity(ident);
6109             }
6110         }
6111 
6112         @Override // Binder call
6113         public void removeScreenTimeoutPolicyListener(int displayId,
6114                 IScreenTimeoutPolicyListener listener) {
6115             if (!mFeatureFlags.isScreenTimeoutPolicyListenerApiEnabled()) {
6116                 throw new IllegalStateException("Screen timeout policy listener API flag "
6117                         + "is not enabled");
6118             }
6119 
6120             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
6121                     null);
6122 
6123             if (displayId == Display.INVALID_DISPLAY) {
6124                 throw new IllegalArgumentException("Valid display id is expected");
6125             }
6126 
6127             final long ident = Binder.clearCallingIdentity();
6128             try {
6129                 mNotifier.removeScreenTimeoutPolicyListener(displayId, listener);
6130             } finally {
6131                 Binder.restoreCallingIdentity(ident);
6132             }
6133         }
6134 
6135         @Override // Binder call
6136         public void userActivity(int displayId, long eventTime,
6137                 @PowerManager.UserActivityEvent int event, int flags) {
6138             final long now = mClock.uptimeMillis();
6139             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
6140                     != PackageManager.PERMISSION_GRANTED
6141                     && mContext.checkCallingOrSelfPermission(
6142                             android.Manifest.permission.USER_ACTIVITY)
6143                             != PackageManager.PERMISSION_GRANTED) {
6144                 // Once upon a time applications could call userActivity().
6145                 // Now we require the DEVICE_POWER permission.  Log a warning and ignore the
6146                 // request instead of throwing a SecurityException so we don't break old apps.
6147                 synchronized (mLock) {
6148                     if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
6149                         mLastWarningAboutUserActivityPermission = now;
6150                         Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
6151                                 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
6152                                 + "permission.  Please fix your app!  "
6153                                 + " pid=" + Binder.getCallingPid()
6154                                 + " uid=" + Binder.getCallingUid());
6155                     }
6156                 }
6157                 return;
6158             }
6159 
6160             if (eventTime > now) {
6161                 Slog.wtf(TAG, "Event cannot be newer than the current time ("
6162                         + "now=" + now
6163                         + ", eventTime=" + eventTime
6164                         + ", displayId=" + displayId
6165                         + ", event=" + PowerManager.userActivityEventToString(event)
6166                         + ", flags=" + flags
6167                         + ")");
6168                 return;
6169             }
6170 
6171             final int uid = Binder.getCallingUid();
6172             final long ident = Binder.clearCallingIdentity();
6173             try {
6174                 userActivityInternal(displayId, eventTime, event, flags, uid);
6175             } finally {
6176                 Binder.restoreCallingIdentity(ident);
6177             }
6178         }
6179 
6180         @Override // Binder call
6181         public void wakeUp(long eventTime, @WakeReason int reason, String details,
6182                 String opPackageName) {
6183             wakeUpWithDisplayId(eventTime, reason, details, opPackageName, Display.DEFAULT_DISPLAY);
6184         }
6185 
6186         @Override // Binder call
6187         public void wakeUpWithDisplayId(long eventTime, @WakeReason int reason, String details,
6188                 String opPackageName, int displayId) {
6189             final long now = mClock.uptimeMillis();
6190             if (eventTime > now) {
6191                 Slog.e(TAG, "Event time " + eventTime + " cannot be newer than " + now);
6192                 throw new IllegalArgumentException("event time must not be in the future");
6193             }
6194 
6195             mContext.enforceCallingOrSelfPermission(
6196                     android.Manifest.permission.DEVICE_POWER, null);
6197 
6198             final int uid = Binder.getCallingUid();
6199             final long ident = Binder.clearCallingIdentity();
6200             try {
6201                 int displayGroupId = getDisplayGroupId(displayId);
6202                 synchronized (mLock) {
6203                     if (!mBootCompleted && sQuiescent) {
6204                         mDirty |= DIRTY_QUIESCENT;
6205                         updatePowerStateLocked();
6206                         return;
6207                     }
6208                     wakePowerGroupLocked(mPowerGroups.get(displayGroupId), eventTime,
6209                             reason, details, uid, opPackageName, uid);
6210                 }
6211             } finally {
6212                 Binder.restoreCallingIdentity(ident);
6213             }
6214         }
6215 
6216         @Override // Binder call
6217         @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
6218         public void goToSleep(long eventTime, int reason, int flags) {
6219             goToSleepInternal(DEFAULT_DISPLAY_GROUP_IDS, eventTime, reason, flags);
6220         }
6221 
6222         @Override // Binder call
6223         @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
6224         public void goToSleepWithDisplayId(int displayId, long eventTime, int reason, int flags) {
6225             IntArray groupIds;
6226 
6227             if (displayId == Display.INVALID_DISPLAY) {
6228                 groupIds = mDisplayManagerInternal.getDisplayGroupIds();
6229             } else {
6230                 DisplayInfo displayInfo = mDisplayManagerInternal.getDisplayInfo(displayId);
6231                 Preconditions.checkArgument(displayInfo != null, "display ID(%d) doesn't exist",
6232                         displayId);
6233                 int groupId = displayInfo.displayGroupId;
6234                 if (groupId == Display.INVALID_DISPLAY_GROUP) {
6235                     throw new IllegalArgumentException("invalid display group ID");
6236                 }
6237                 groupIds = IntArray.wrap(new int[]{groupId});
6238             }
6239             goToSleepInternal(groupIds, eventTime, reason, flags);
6240         }
6241 
6242         @Override // Binder call
6243         public void nap(long eventTime) {
6244             final long now = mClock.uptimeMillis();
6245             if (eventTime > now) {
6246                 Slog.e(TAG, "Event time " + eventTime + " cannot be newer than " + now);
6247                 throw new IllegalArgumentException("event time must not be in the future");
6248             }
6249 
6250             mContext.enforceCallingOrSelfPermission(
6251                     android.Manifest.permission.DEVICE_POWER, null);
6252 
6253             final int uid = Binder.getCallingUid();
6254             final long ident = Binder.clearCallingIdentity();
6255             try {
6256                 napInternal(eventTime, uid, /* allowWake= */ false);
6257             } finally {
6258                 Binder.restoreCallingIdentity(ident);
6259             }
6260         }
6261 
6262         @Override
6263         public float getBrightnessConstraint(
6264                 int displayId, @PowerManager.BrightnessConstraint int constraint) {
6265             DisplayInfo info = null;
6266             if (android.companion.virtualdevice.flags.Flags.displayPowerManagerApis()
6267                     && mDisplayManagerInternal != null) {
6268                 info = mDisplayManagerInternal.getDisplayInfo(displayId);
6269             }
6270             switch (constraint) {
6271                 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM:
6272                     return info != null && isValidBrightnessValue(info.brightnessMinimum)
6273                             ? info.brightnessMinimum : mScreenBrightnessMinimum;
6274                 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM:
6275                     return info != null && isValidBrightnessValue(info.brightnessMaximum)
6276                             ? info.brightnessMaximum : mScreenBrightnessMaximum;
6277                 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT:
6278                     return info != null && isValidBrightnessValue(info.brightnessDefault)
6279                             ? info.brightnessDefault : mScreenBrightnessDefault;
6280                 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DIM:
6281                     return android.companion.virtualdevice.flags.Flags.deviceAwareDisplayPower()
6282                             && info != null && isValidBrightnessValue(info.brightnessDim)
6283                             ? info.brightnessDim : mScreenBrightnessDim;
6284                 default:
6285                     return PowerManager.BRIGHTNESS_INVALID_FLOAT;
6286             }
6287         }
6288 
6289         @Override // Binder call
6290         public boolean isInteractive() {
6291             final long ident = Binder.clearCallingIdentity();
6292             try {
6293                 return isGloballyInteractiveInternal();
6294             } finally {
6295                 Binder.restoreCallingIdentity(ident);
6296             }
6297         }
6298 
6299         @Override // Binder call
6300         public boolean isDisplayInteractive(int displayId) {
6301             int uid = Binder.getCallingUid();
6302             final long ident = Binder.clearCallingIdentity();
6303             try {
6304                 return isInteractiveInternal(displayId, uid);
6305             } finally {
6306                 Binder.restoreCallingIdentity(ident);
6307             }
6308         }
6309 
6310         @Override // Binder call
6311         public boolean areAutoPowerSaveModesEnabled() {
6312             final long ident = Binder.clearCallingIdentity();
6313             try {
6314                 return mContext.getResources().getBoolean(
6315                         com.android.internal.R.bool.config_enableAutoPowerModes);
6316             } finally {
6317                 Binder.restoreCallingIdentity(ident);
6318             }
6319         }
6320 
6321         @Override // Binder call
6322         public boolean isPowerSaveMode() {
6323             final long ident = Binder.clearCallingIdentity();
6324             try {
6325                 return mBatterySaverSupported
6326                         && mBatterySaverStateMachine.getBatterySaverController().isEnabled();
6327             } finally {
6328                 Binder.restoreCallingIdentity(ident);
6329             }
6330         }
6331 
6332         // Binder call
6333         public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
6334             final long ident = Binder.clearCallingIdentity();
6335             try {
6336                 // Return default PowerSaveState if battery saver is not supported.
6337                 return mBatterySaverSupported
6338                         ?
6339                         mBatterySaverStateMachine.getBatterySaverPolicy().getBatterySaverPolicy(
6340                                 serviceType)
6341                         : new PowerSaveState.Builder().build();
6342             } finally {
6343                 Binder.restoreCallingIdentity(ident);
6344             }
6345         }
6346 
6347         @Override // Binder call
6348         public boolean setPowerSaveModeEnabled(boolean enabled) {
6349             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
6350                     != PackageManager.PERMISSION_GRANTED) {
6351                 mContext.enforceCallingOrSelfPermission(
6352                         android.Manifest.permission.DEVICE_POWER, null);
6353             }
6354             final long ident = Binder.clearCallingIdentity();
6355             try {
6356                 return setLowPowerModeInternal(enabled);
6357             } finally {
6358                 Binder.restoreCallingIdentity(ident);
6359             }
6360         }
6361 
6362         @Override
6363         public boolean isBatterySaverSupported() {
6364             final long ident = Binder.clearCallingIdentity();
6365             try {
6366                 return mBatterySaverSupported;
6367             } finally {
6368                 Binder.restoreCallingIdentity(ident);
6369             }
6370         }
6371 
6372         @Override // Binder call
6373         public BatterySaverPolicyConfig getFullPowerSavePolicy() {
6374             // Return default BatterySaverPolicyConfig if battery saver is not supported.
6375             final long ident = Binder.clearCallingIdentity();
6376             try {
6377                 return mBatterySaverSupported
6378                         ? mBatterySaverStateMachine.getFullBatterySaverPolicy()
6379                         : new BatterySaverPolicyConfig.Builder().build();
6380             } finally {
6381                 Binder.restoreCallingIdentity(ident);
6382             }
6383         }
6384 
6385         @Override // Binder call
6386         public boolean setFullPowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
6387             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
6388                     != PackageManager.PERMISSION_GRANTED) {
6389                 mContext.enforceCallingOrSelfPermission(
6390                         android.Manifest.permission.DEVICE_POWER, "setFullPowerSavePolicy");
6391             }
6392             final long ident = Binder.clearCallingIdentity();
6393             try {
6394                 return mBatterySaverSupported
6395                         && mBatterySaverStateMachine.setFullBatterySaverPolicy(config);
6396             } finally {
6397                 Binder.restoreCallingIdentity(ident);
6398             }
6399         }
6400 
6401         @Override // Binder call
6402         public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
6403             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER,
6404                     "updateDynamicPowerSavings");
6405             final long ident = Binder.clearCallingIdentity();
6406             try {
6407                 final ContentResolver resolver = mContext.getContentResolver();
6408                 boolean success = Settings.Global.putInt(resolver,
6409                         Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
6410                         disableThreshold);
6411                 if (success) {
6412                     // abort updating if we weren't able to succeed on the threshold
6413                     success &= Settings.Global.putInt(resolver,
6414                             Settings.Global.DYNAMIC_POWER_SAVINGS_ENABLED,
6415                             powerSaveHint ? 1 : 0);
6416                 }
6417                 return success;
6418             } finally {
6419                 Binder.restoreCallingIdentity(ident);
6420             }
6421         }
6422 
6423         @Override // Binder call
6424         public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
6425             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
6426                     != PackageManager.PERMISSION_GRANTED) {
6427                 mContext.enforceCallingOrSelfPermission(
6428                         android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSavePolicy");
6429             }
6430             final long ident = Binder.clearCallingIdentity();
6431             try {
6432                 return mBatterySaverSupported
6433                         && mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
6434             } finally {
6435                 Binder.restoreCallingIdentity(ident);
6436             }
6437         }
6438 
6439         @Override // Binder call
6440         public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
6441             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
6442                     != PackageManager.PERMISSION_GRANTED) {
6443                 mContext.enforceCallingOrSelfPermission(
6444                         android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSaveEnabled");
6445             }
6446             final long ident = Binder.clearCallingIdentity();
6447             try {
6448                 return mBatterySaverSupported
6449                         && mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
6450             } finally {
6451                 Binder.restoreCallingIdentity(ident);
6452             }
6453         }
6454 
6455         @Override // Binder call
6456         public int getPowerSaveModeTrigger() {
6457             final long ident = Binder.clearCallingIdentity();
6458             try {
6459                 return Settings.Global.getInt(mContext.getContentResolver(),
6460                         Settings.Global.AUTOMATIC_POWER_SAVE_MODE,
6461                         PowerManager.POWER_SAVE_MODE_TRIGGER_PERCENTAGE);
6462             } finally {
6463                 Binder.restoreCallingIdentity(ident);
6464             }
6465         }
6466 
6467         @Override // Binder call
6468         public void setBatteryDischargePrediction(@NonNull ParcelDuration timeRemaining,
6469                 boolean isPersonalized) {
6470             // Get current time before acquiring the lock so that the calculated end time is as
6471             // accurate as possible.
6472             final long nowElapsed = mClock.elapsedRealtime();
6473             if (mContext.checkCallingOrSelfPermission(
6474                     android.Manifest.permission.BATTERY_PREDICTION)
6475                     != PackageManager.PERMISSION_GRANTED) {
6476                 mContext.enforceCallingOrSelfPermission(
6477                         android.Manifest.permission.DEVICE_POWER, "setBatteryDischargePrediction");
6478             }
6479 
6480             final long timeRemainingMs = timeRemaining.getDuration().toMillis();
6481             // A non-positive number means the battery should be dead right now...
6482             Preconditions.checkArgumentPositive(timeRemainingMs,
6483                     "Given time remaining is not positive: " + timeRemainingMs);
6484 
6485             final long ident = Binder.clearCallingIdentity();
6486             try {
6487                 synchronized (mLock) {
6488                     if (mIsPowered) {
6489                         throw new IllegalStateException(
6490                                 "Discharge prediction can't be set while the device is charging");
6491                     }
6492                 }
6493 
6494                 final long broadcastDelayMs;
6495                 synchronized (mEnhancedDischargeTimeLock) {
6496                     if (mLastEnhancedDischargeTimeUpdatedElapsed > nowElapsed) {
6497                         // Another later call made it into the block first. Keep the latest info.
6498                         return;
6499                     }
6500                     broadcastDelayMs = Math.max(0,
6501                             ENHANCED_DISCHARGE_PREDICTION_BROADCAST_MIN_DELAY_MS
6502                                     - (nowElapsed - mLastEnhancedDischargeTimeUpdatedElapsed));
6503 
6504                     // No need to persist the discharge prediction values since they'll most likely
6505                     // be wrong immediately after a reboot anyway.
6506                     mEnhancedDischargeTimeElapsed = nowElapsed + timeRemainingMs;
6507                     mEnhancedDischargePredictionIsPersonalized = isPersonalized;
6508                     mLastEnhancedDischargeTimeUpdatedElapsed = nowElapsed;
6509                 }
6510                 mNotifier.postEnhancedDischargePredictionBroadcast(broadcastDelayMs);
6511             } finally {
6512                 Binder.restoreCallingIdentity(ident);
6513             }
6514         }
6515 
6516         @GuardedBy("PowerManagerService.this.mEnhancedDischargeTimeLock")
6517         private boolean isEnhancedDischargePredictionValidLocked(long nowElapsed) {
6518             return mLastEnhancedDischargeTimeUpdatedElapsed > 0
6519                     && nowElapsed < mEnhancedDischargeTimeElapsed
6520                     && nowElapsed - mLastEnhancedDischargeTimeUpdatedElapsed
6521                     < ENHANCED_DISCHARGE_PREDICTION_TIMEOUT_MS;
6522         }
6523 
6524         @Override // Binder call
6525         public ParcelDuration getBatteryDischargePrediction() {
6526             final long ident = Binder.clearCallingIdentity();
6527             try {
6528                 synchronized (mLock) {
6529                     if (mIsPowered) {
6530                         return null;
6531                     }
6532                 }
6533                 synchronized (mEnhancedDischargeTimeLock) {
6534                     // Get current time after acquiring the lock so that the calculated duration
6535                     // is as accurate as possible.
6536                     final long nowElapsed = mClock.elapsedRealtime();
6537                     if (isEnhancedDischargePredictionValidLocked(nowElapsed)) {
6538                         return new ParcelDuration(mEnhancedDischargeTimeElapsed - nowElapsed);
6539                     }
6540                 }
6541                 return new ParcelDuration(mBatteryStats.computeBatteryTimeRemaining());
6542             } catch (RemoteException e) {
6543                 // Shouldn't happen in-process.
6544             } finally {
6545                 Binder.restoreCallingIdentity(ident);
6546             }
6547             return null;
6548         }
6549 
6550         @Override // Binder call
6551         public boolean isBatteryDischargePredictionPersonalized() {
6552             final long ident = Binder.clearCallingIdentity();
6553             try {
6554                 synchronized (mEnhancedDischargeTimeLock) {
6555                     return isEnhancedDischargePredictionValidLocked(mClock.elapsedRealtime())
6556                             && mEnhancedDischargePredictionIsPersonalized;
6557                 }
6558             } finally {
6559                 Binder.restoreCallingIdentity(ident);
6560             }
6561         }
6562 
6563         @Override // Binder call
6564         public boolean isDeviceIdleMode() {
6565             final long ident = Binder.clearCallingIdentity();
6566             try {
6567                 return isDeviceIdleModeInternal();
6568             } finally {
6569                 Binder.restoreCallingIdentity(ident);
6570             }
6571         }
6572 
6573         @Override // Binder call
6574         public boolean isLightDeviceIdleMode() {
6575             final long ident = Binder.clearCallingIdentity();
6576             try {
6577                 return isLightDeviceIdleModeInternal();
6578             } finally {
6579                 Binder.restoreCallingIdentity(ident);
6580             }
6581         }
6582 
6583         @Override // Binder call
6584         @RequiresPermission(anyOf = {
6585                 android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6586                 android.Manifest.permission.DEVICE_POWER
6587         })
6588         public boolean isLowPowerStandbySupported() {
6589             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
6590                     != PackageManager.PERMISSION_GRANTED) {
6591                 mContext.enforceCallingOrSelfPermission(
6592                         android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6593                         "isLowPowerStandbySupported");
6594             }
6595 
6596             final long ident = Binder.clearCallingIdentity();
6597             try {
6598                 return mLowPowerStandbyController.isSupported();
6599             } finally {
6600                 Binder.restoreCallingIdentity(ident);
6601             }
6602         }
6603 
6604         @Override // Binder call
6605         public boolean isLowPowerStandbyEnabled() {
6606             final long ident = Binder.clearCallingIdentity();
6607             try {
6608                 return mLowPowerStandbyController.isEnabled();
6609             } finally {
6610                 Binder.restoreCallingIdentity(ident);
6611             }
6612         }
6613 
6614         @Override // Binder call
6615         @RequiresPermission(anyOf = {
6616                 android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6617                 android.Manifest.permission.DEVICE_POWER
6618         })
6619         public void setLowPowerStandbyEnabled(boolean enabled) {
6620             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
6621                     != PackageManager.PERMISSION_GRANTED) {
6622                 mContext.enforceCallingOrSelfPermission(
6623                         android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6624                         "setLowPowerStandbyEnabled");
6625             }
6626 
6627             final long ident = Binder.clearCallingIdentity();
6628             try {
6629                 mLowPowerStandbyController.setEnabled(enabled);
6630             } finally {
6631                 Binder.restoreCallingIdentity(ident);
6632             }
6633         }
6634 
6635         @Override // Binder call
6636         @RequiresPermission(anyOf = {
6637                 android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6638                 android.Manifest.permission.DEVICE_POWER
6639         })
6640         public void setLowPowerStandbyActiveDuringMaintenance(boolean activeDuringMaintenance) {
6641             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
6642                     != PackageManager.PERMISSION_GRANTED) {
6643                 mContext.enforceCallingOrSelfPermission(
6644                         android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6645                         "setLowPowerStandbyActiveDuringMaintenance");
6646             }
6647 
6648             final long ident = Binder.clearCallingIdentity();
6649             try {
6650                 mLowPowerStandbyController.setActiveDuringMaintenance(activeDuringMaintenance);
6651             } finally {
6652                 Binder.restoreCallingIdentity(ident);
6653             }
6654         }
6655 
6656         @Override // Binder call
6657         @RequiresPermission(anyOf = {
6658                 android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6659                 android.Manifest.permission.DEVICE_POWER
6660         })
6661         public void forceLowPowerStandbyActive(boolean active) {
6662             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
6663                     != PackageManager.PERMISSION_GRANTED) {
6664                 mContext.enforceCallingOrSelfPermission(
6665                         android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6666                         "forceLowPowerStandbyActive");
6667             }
6668 
6669             final long ident = Binder.clearCallingIdentity();
6670             try {
6671                 mLowPowerStandbyController.forceActive(active);
6672             } finally {
6673                 Binder.restoreCallingIdentity(ident);
6674             }
6675         }
6676 
6677         @Override // Binder call
6678         @RequiresPermission(anyOf = {
6679                 android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6680                 android.Manifest.permission.DEVICE_POWER
6681         })
6682         public void setLowPowerStandbyPolicy(@Nullable IPowerManager.LowPowerStandbyPolicy policy) {
6683             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
6684                     != PackageManager.PERMISSION_GRANTED) {
6685                 mContext.enforceCallingOrSelfPermission(
6686                         android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6687                         "setLowPowerStandbyPolicy");
6688             }
6689 
6690             final long ident = Binder.clearCallingIdentity();
6691             try {
6692                 mLowPowerStandbyController.setPolicy(
6693                         PowerManager.LowPowerStandbyPolicy.fromParcelable(policy));
6694             } finally {
6695                 Binder.restoreCallingIdentity(ident);
6696             }
6697         }
6698 
6699         @Override // Binder call
6700         @RequiresPermission(anyOf = {
6701                 android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6702                 android.Manifest.permission.DEVICE_POWER
6703         })
6704         public IPowerManager.LowPowerStandbyPolicy getLowPowerStandbyPolicy() {
6705             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
6706                     != PackageManager.PERMISSION_GRANTED) {
6707                 mContext.enforceCallingOrSelfPermission(
6708                         android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6709                         "getLowPowerStandbyPolicy");
6710             }
6711 
6712             final long ident = Binder.clearCallingIdentity();
6713             try {
6714                 return PowerManager.LowPowerStandbyPolicy.toParcelable(
6715                         mLowPowerStandbyController.getPolicy());
6716             } finally {
6717                 Binder.restoreCallingIdentity(ident);
6718             }
6719         }
6720 
6721         @Override // Binder call
6722         public boolean isExemptFromLowPowerStandby() {
6723             final int callingUid = Binder.getCallingUid();
6724             final long ident = Binder.clearCallingIdentity();
6725             try {
6726                 return mLowPowerStandbyController.isPackageExempt(callingUid);
6727             } finally {
6728                 Binder.restoreCallingIdentity(ident);
6729             }
6730         }
6731 
6732         @Override // Binder call
6733         public boolean isReasonAllowedInLowPowerStandby(
6734                 @PowerManager.LowPowerStandbyAllowedReason int reason) {
6735             final long ident = Binder.clearCallingIdentity();
6736             try {
6737                 return mLowPowerStandbyController.isAllowed(reason);
6738             } finally {
6739                 Binder.restoreCallingIdentity(ident);
6740             }
6741         }
6742 
6743         @Override // Binder call
6744         public boolean isFeatureAllowedInLowPowerStandby(String feature) {
6745             final long ident = Binder.clearCallingIdentity();
6746             try {
6747                 return mLowPowerStandbyController.isAllowed(feature);
6748             } finally {
6749                 Binder.restoreCallingIdentity(ident);
6750             }
6751         }
6752 
6753         @Override // Binder call
6754         @RequiresPermission(android.Manifest.permission.SET_LOW_POWER_STANDBY_PORTS)
6755         public void acquireLowPowerStandbyPorts(IBinder token,
6756                 List<LowPowerStandbyPortDescription> ports) {
6757             mContext.enforceCallingOrSelfPermission(
6758                     android.Manifest.permission.SET_LOW_POWER_STANDBY_PORTS,
6759                     "acquireLowPowerStandbyPorts");
6760 
6761             final int callingUid = Binder.getCallingUid();
6762             final long ident = Binder.clearCallingIdentity();
6763             try {
6764                 mLowPowerStandbyController.acquireStandbyPorts(token, callingUid,
6765                         PowerManager.LowPowerStandbyPortDescription.fromParcelable(ports));
6766             } finally {
6767                 Binder.restoreCallingIdentity(ident);
6768             }
6769         }
6770 
6771         @Override // Binder call
6772         @RequiresPermission(android.Manifest.permission.SET_LOW_POWER_STANDBY_PORTS)
6773         public void releaseLowPowerStandbyPorts(IBinder token) {
6774             mContext.enforceCallingOrSelfPermission(
6775                     android.Manifest.permission.SET_LOW_POWER_STANDBY_PORTS,
6776                     "releaseLowPowerStandbyPorts");
6777 
6778             final long ident = Binder.clearCallingIdentity();
6779             try {
6780                 mLowPowerStandbyController.releaseStandbyPorts(token);
6781             } finally {
6782                 Binder.restoreCallingIdentity(ident);
6783             }
6784         }
6785 
6786         @Override // Binder call
6787         @RequiresPermission(anyOf = {
6788                 android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6789                 android.Manifest.permission.DEVICE_POWER
6790         })
6791         public List<LowPowerStandbyPortDescription> getActiveLowPowerStandbyPorts() {
6792             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
6793                     != PackageManager.PERMISSION_GRANTED) {
6794                 mContext.enforceCallingOrSelfPermission(
6795                         android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
6796                         "getActiveLowPowerStandbyPorts");
6797             }
6798 
6799             final long ident = Binder.clearCallingIdentity();
6800             try {
6801                 return PowerManager.LowPowerStandbyPortDescription.toParcelable(
6802                         mLowPowerStandbyController.getActiveStandbyPorts());
6803             } finally {
6804                 Binder.restoreCallingIdentity(ident);
6805             }
6806         }
6807 
6808         /**
6809          * Gets the reason for the last time the phone had to reboot.
6810          *
6811          * @return The reason the phone last shut down as an int or
6812          * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
6813          */
6814         @Override // Binder call
6815         public int getLastShutdownReason() {
6816             mContext.enforceCallingOrSelfPermission(
6817                     android.Manifest.permission.DEVICE_POWER, null);
6818 
6819             final long ident = Binder.clearCallingIdentity();
6820             try {
6821                 return getLastShutdownReasonInternal();
6822             } finally {
6823                 Binder.restoreCallingIdentity(ident);
6824             }
6825         }
6826 
6827         @Override // Binder call
6828         public int getLastSleepReason() {
6829             mContext.enforceCallingOrSelfPermission(
6830                     android.Manifest.permission.DEVICE_POWER, null);
6831 
6832             final long ident = Binder.clearCallingIdentity();
6833             try {
6834                 return getLastSleepReasonInternal();
6835             } finally {
6836                 Binder.restoreCallingIdentity(ident);
6837             }
6838         }
6839 
6840         /**
6841          * Reboots the device.
6842          *
6843          * @param confirm If true, shows a reboot confirmation dialog.
6844          * @param reason The reason for the reboot, or null if none.
6845          * @param wait If true, this call waits for the reboot to complete and does not return.
6846          */
6847         @Override // Binder call
6848         public void reboot(boolean confirm, @Nullable String reason, boolean wait) {
6849             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
6850             if (PowerManager.REBOOT_RECOVERY.equals(reason)
6851                     || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
6852                 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
6853             }
6854 
6855             ShutdownCheckPoints.recordCheckPoint(Binder.getCallingPid(), reason);
6856             final long ident = Binder.clearCallingIdentity();
6857             try {
6858                 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
6859             } finally {
6860                 Binder.restoreCallingIdentity(ident);
6861             }
6862         }
6863 
6864         /**
6865          * Reboots the device into safe mode
6866          *
6867          * @param confirm If true, shows a reboot confirmation dialog.
6868          * @param wait If true, this call waits for the reboot to complete and does not return.
6869          */
6870         @Override // Binder call
6871         public void rebootSafeMode(boolean confirm, boolean wait) {
6872             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
6873 
6874             String reason = PowerManager.REBOOT_SAFE_MODE;
6875             ShutdownCheckPoints.recordCheckPoint(Binder.getCallingPid(), reason);
6876             final long ident = Binder.clearCallingIdentity();
6877             try {
6878                 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm, reason, wait);
6879             } finally {
6880                 Binder.restoreCallingIdentity(ident);
6881             }
6882         }
6883 
6884         /**
6885          * Shuts down the device.
6886          *
6887          * @param confirm If true, shows a shutdown confirmation dialog.
6888          * @param wait If true, this call waits for the shutdown to complete and does not return.
6889          */
6890         @Override // Binder call
6891         public void shutdown(boolean confirm, String reason, boolean wait) {
6892             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
6893 
6894             ShutdownCheckPoints.recordCheckPoint(Binder.getCallingPid(), reason);
6895             final long ident = Binder.clearCallingIdentity();
6896             try {
6897                 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
6898             } finally {
6899                 Binder.restoreCallingIdentity(ident);
6900             }
6901         }
6902 
6903         /**
6904          * Crash the runtime (causing a complete restart of the Android framework).
6905          * Requires REBOOT permission.  Mostly for testing.  Should not return.
6906          */
6907         @Override // Binder call
6908         public void crash(String message) {
6909             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
6910 
6911             final long ident = Binder.clearCallingIdentity();
6912             try {
6913                 crashInternal(message);
6914             } finally {
6915                 Binder.restoreCallingIdentity(ident);
6916             }
6917         }
6918 
6919         /**
6920          * Set the setting that determines whether the device stays on when plugged in.
6921          * The argument is a bit string, with each bit specifying a power source that,
6922          * when the device is connected to that source, causes the device to stay on.
6923          * See {@link android.os.BatteryManager} for the list of power sources that
6924          * can be specified. Current values include
6925          * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
6926          * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
6927          *
6928          * Used by "adb shell svc power stayon ..."
6929          *
6930          * @param val an {@code int} containing the bits that specify which power sources
6931          * should cause the device to stay on.
6932          */
6933         @Override // Binder call
6934         public void setStayOnSetting(int val) {
6935             int uid = Binder.getCallingUid();
6936             // if uid is of root's, we permit this operation straight away
6937             if (uid != Process.ROOT_UID) {
6938                 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
6939                         Settings.getPackageNameForUid(mContext, uid), /* attributionTag= */ null,
6940                         /* throwException= */ true)) {
6941                     return;
6942                 }
6943             }
6944 
6945             final long ident = Binder.clearCallingIdentity();
6946             try {
6947                 setStayOnSettingInternal(val);
6948             } finally {
6949                 Binder.restoreCallingIdentity(ident);
6950             }
6951         }
6952 
6953         /**
6954          * Used by the phone application to make the attention LED flash when ringing.
6955          */
6956         @Override // Binder call
6957         public void setAttentionLight(boolean on, int color) {
6958             mContext.enforceCallingOrSelfPermission(
6959                     android.Manifest.permission.DEVICE_POWER, null);
6960 
6961             final long ident = Binder.clearCallingIdentity();
6962             try {
6963                 setAttentionLightInternal(on, color);
6964             } finally {
6965                 Binder.restoreCallingIdentity(ident);
6966             }
6967         }
6968 
6969         @Override // Binder call
6970         public void setDozeAfterScreenOff(boolean on) {
6971             mContext.enforceCallingOrSelfPermission(
6972                     android.Manifest.permission.DEVICE_POWER, null);
6973 
6974             final long ident = Binder.clearCallingIdentity();
6975             try {
6976                 setDozeAfterScreenOffInternal(on);
6977             } finally {
6978                 Binder.restoreCallingIdentity(ident);
6979             }
6980         }
6981 
6982         @Override // Binder call
6983         public boolean isAmbientDisplayAvailable() {
6984             mContext.enforceCallingOrSelfPermission(
6985                     android.Manifest.permission.READ_DREAM_STATE, null);
6986 
6987             final long ident = Binder.clearCallingIdentity();
6988             try {
6989                 return mAmbientDisplayConfiguration.ambientDisplayAvailable();
6990             } finally {
6991                 Binder.restoreCallingIdentity(ident);
6992             }
6993         }
6994 
6995         @Override // Binder call
6996         public void suppressAmbientDisplay(@NonNull String token, boolean suppress) {
6997             mContext.enforceCallingOrSelfPermission(
6998                     android.Manifest.permission.WRITE_DREAM_STATE, null);
6999 
7000             final int uid = Binder.getCallingUid();
7001             final long ident = Binder.clearCallingIdentity();
7002             try {
7003                 mAmbientDisplaySuppressionController.suppress(token, uid, suppress);
7004             } finally {
7005                 Binder.restoreCallingIdentity(ident);
7006             }
7007         }
7008 
7009         @Override // Binder call
7010         public boolean isAmbientDisplaySuppressedForToken(@NonNull String token) {
7011             mContext.enforceCallingOrSelfPermission(
7012                     android.Manifest.permission.READ_DREAM_STATE, null);
7013 
7014             final int uid = Binder.getCallingUid();
7015             final long ident = Binder.clearCallingIdentity();
7016             try {
7017                 return mAmbientDisplaySuppressionController.isSuppressed(token, uid);
7018             } finally {
7019                 Binder.restoreCallingIdentity(ident);
7020             }
7021         }
7022 
7023         @Override // Binder call
7024         public boolean isAmbientDisplaySuppressedForTokenByApp(@NonNull String token, int appUid) {
7025             mContext.enforceCallingOrSelfPermission(
7026                     android.Manifest.permission.READ_DREAM_STATE, null);
7027             mContext.enforceCallingOrSelfPermission(
7028                     android.Manifest.permission.READ_DREAM_SUPPRESSION, null);
7029 
7030             final long ident = Binder.clearCallingIdentity();
7031             try {
7032                 return isAmbientDisplayAvailable()
7033                         && mAmbientDisplaySuppressionController.isSuppressed(token, appUid);
7034             } finally {
7035                 Binder.restoreCallingIdentity(ident);
7036             }
7037         }
7038 
7039         @Override // Binder call
7040         public boolean isAmbientDisplaySuppressed() {
7041             mContext.enforceCallingOrSelfPermission(
7042                     android.Manifest.permission.READ_DREAM_STATE, null);
7043 
7044             final long ident = Binder.clearCallingIdentity();
7045             try {
7046                 return mAmbientDisplaySuppressionController.isSuppressed();
7047             } finally {
7048                 Binder.restoreCallingIdentity(ident);
7049             }
7050         }
7051 
7052         @Override // Binder call
7053         public void boostScreenBrightness(long eventTime) {
7054             final long now = mClock.uptimeMillis();
7055             if (eventTime > mClock.uptimeMillis()) {
7056                 Slog.e(TAG, "Event time " + eventTime + " cannot be newer than " + now);
7057                 throw new IllegalArgumentException("event time must not be in the future");
7058             }
7059 
7060             mContext.enforceCallingOrSelfPermission(
7061                     android.Manifest.permission.DEVICE_POWER, null);
7062 
7063             final int uid = Binder.getCallingUid();
7064             final long ident = Binder.clearCallingIdentity();
7065             try {
7066                 boostScreenBrightnessInternal(eventTime, uid);
7067             } finally {
7068                 Binder.restoreCallingIdentity(ident);
7069             }
7070         }
7071 
7072         @Override // Binder call
7073         public boolean isScreenBrightnessBoosted() {
7074             final long ident = Binder.clearCallingIdentity();
7075             try {
7076                 return isScreenBrightnessBoostedInternal();
7077             } finally {
7078                 Binder.restoreCallingIdentity(ident);
7079             }
7080         }
7081 
7082         @Override // binder call
7083         public boolean forceSuspend() {
7084             mContext.enforceCallingOrSelfPermission(
7085                     android.Manifest.permission.DEVICE_POWER, null);
7086 
7087             final int uid = Binder.getCallingUid();
7088             final long ident = Binder.clearCallingIdentity();
7089             try {
7090                 return forceSuspendInternal(uid);
7091             } finally {
7092                 Binder.restoreCallingIdentity(ident);
7093             }
7094         }
7095 
7096         @Override // Binder call
7097         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7098             if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
7099 
7100             final long ident = Binder.clearCallingIdentity();
7101 
7102             boolean isDumpProto = false;
7103             for (String arg : args) {
7104                 if (arg.equals("--proto")) {
7105                     isDumpProto = true;
7106                     break;
7107                 }
7108             }
7109             try {
7110                 if (isDumpProto) {
7111                     dumpProto(fd);
7112                 } else {
7113                     dumpInternal(pw);
7114                 }
7115             } finally {
7116                 Binder.restoreCallingIdentity(ident);
7117             }
7118         }
7119 
7120         /**
7121          * Returns the tokens used to suppress ambient display by the calling app.
7122          *
7123          * <p>The calling app suppressed ambient display by calling
7124          * {@link #suppressAmbientDisplay(String, boolean)}.
7125          */
7126         public List<String> getAmbientDisplaySuppressionTokens() {
7127             final int uid = Binder.getCallingUid();
7128             final long ident = Binder.clearCallingIdentity();
7129             try {
7130                 return mAmbientDisplaySuppressionController.getSuppressionTokens(uid);
7131             } finally {
7132                 Binder.restoreCallingIdentity(ident);
7133             }
7134         }
7135 
7136         public void setUseFaceDownDetector(boolean enable) {
7137             final long ident = Binder.clearCallingIdentity();
7138             try {
7139                 mFaceDownDetector.setEnabledOverride(enable);
7140             } finally {
7141                 Binder.restoreCallingIdentity(ident);
7142             }
7143         }
7144 
7145     }
7146 
7147     @VisibleForTesting
7148     BinderService getBinderServiceInstance() {
7149         return mBinderService;
7150     }
7151 
7152     @VisibleForTesting
7153     LocalService getLocalServiceInstance() {
7154         return mLocalService;
7155     }
7156 
7157     @VisibleForTesting
7158     int getLastShutdownReasonInternal() {
7159         String line = mSystemProperties.get(SYSTEM_PROPERTY_REBOOT_REASON, null);
7160         switch (line) {
7161             case REASON_SHUTDOWN:
7162                 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
7163             case REASON_REBOOT:
7164                 return PowerManager.SHUTDOWN_REASON_REBOOT;
7165             case REASON_USERREQUESTED:
7166                 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
7167             case REASON_THERMAL_SHUTDOWN:
7168                 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
7169             case REASON_LOW_BATTERY:
7170                 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
7171             case REASON_BATTERY_THERMAL_STATE:
7172                 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
7173             default:
7174                 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
7175         }
7176     }
7177 
7178     @VisibleForTesting
7179     int getPowerGroupSize() {
7180         synchronized (mLock) {
7181             return mPowerGroups.size();
7182         }
7183     }
7184 
7185     @GoToSleepReason
7186     private int getLastSleepReasonInternal() {
7187         synchronized (mLock) {
7188             return mLastGlobalSleepReason;
7189         }
7190     }
7191 
7192     private PowerManager.WakeData getLastWakeupInternal() {
7193         synchronized (mLock) {
7194             return new PowerManager.WakeData(mLastGlobalWakeTime, mLastGlobalWakeReason,
7195                     mLastGlobalWakeTimeRealtime - mLastGlobalSleepTimeRealtime);
7196         }
7197     }
7198 
7199     private PowerManager.SleepData getLastGoToSleepInternal() {
7200         synchronized (mLock) {
7201             return new PowerManager.SleepData(mLastGlobalSleepTime, mLastGlobalSleepReason);
7202         }
7203     }
7204 
7205     /**
7206      * If the user presses power while the proximity sensor is enabled and keeping
7207      * the screen off, then turn the screen back on by telling display manager to
7208      * ignore the proximity sensor.  We don't turn off the proximity sensor because
7209      * we still want it to be reenabled if it's state changes.
7210      *
7211      * @return true if the proximity sensor was successfully ignored and we should
7212      * consume the key event.
7213      */
7214     private boolean interceptPowerKeyDownInternal(KeyEvent event) {
7215         synchronized (mLock) {
7216             // DisplayPowerController only reports proximity positive (near) if it's
7217             // positive and the proximity wasn't already being ignored. So it reliably
7218             // also tells us that we're not already ignoring the proximity sensor.
7219 
7220             if (mProximityPositive && !mInterceptedPowerKeyForProximity) {
7221                 mDisplayManagerInternal.ignoreProximitySensorUntilChanged();
7222                 mInterceptedPowerKeyForProximity = true;
7223                 return true;
7224             }
7225         }
7226 
7227         return false;
7228     }
7229 
7230     @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
7231     private void goToSleepInternal(IntArray groupIds, long eventTime, int reason, int flags) {
7232         final long now = mClock.uptimeMillis();
7233         if (eventTime > now) {
7234             Slog.e(TAG, "Event time " + eventTime + " cannot be newer than " + now);
7235             throw new IllegalArgumentException("event time must not be in the future");
7236         }
7237 
7238         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
7239                 /* message= */ null);
7240 
7241         boolean isNoDoze = (flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0;
7242         int uid = Binder.getCallingUid();
7243         final long ident = Binder.clearCallingIdentity();
7244         try {
7245             synchronized (mLock) {
7246                 for (int i = 0; i < groupIds.size(); i++) {
7247                     int groupId = groupIds.get(i);
7248                     PowerGroup powerGroup = mPowerGroups.get(groupId);
7249                     if (powerGroup == null) {
7250                         throw new IllegalArgumentException("power group(" + groupId
7251                                 + ") doesn't exist");
7252                     }
7253                     if ((flags & PowerManager.GO_TO_SLEEP_FLAG_SOFT_SLEEP) != 0) {
7254                         if (mFoldGracePeriodProvider.isEnabled()) {
7255                             if (!powerGroup.hasWakeLockKeepingScreenOnLocked()) {
7256                                 Slog.d(TAG, "Showing dismissible keyguard");
7257                                 mNotifier.showDismissibleKeyguard();
7258                             } else {
7259                                 Slog.i(TAG, "There is a screen wake lock present: "
7260                                         + "sleep request will be ignored");
7261                             }
7262                             continue; // never actually goes to sleep for SOFT_SLEEP
7263                         } else {
7264                             if (powerGroup.hasWakeLockKeepingScreenOnLocked()) {
7265                                 continue;
7266                             }
7267                         }
7268                     }
7269                     if (isNoDoze) {
7270                         sleepPowerGroupLocked(powerGroup, eventTime, reason, uid);
7271                     } else {
7272                         dozePowerGroupLocked(powerGroup, eventTime, reason, uid);
7273                     }
7274                 }
7275             }
7276         } finally {
7277             Binder.restoreCallingIdentity(ident);
7278         }
7279     }
7280 
7281     @VisibleForTesting
7282     final class LocalService extends PowerManagerInternal {
7283         @Override
7284         public void setDozeOverrideFromDreamManager(
7285                 int screenState, int reason, float screenBrightnessFloat, int screenBrightnessInt,
7286                 boolean useNormalBrightnessForDoze) {
7287             switch (screenState) {
7288                 case Display.STATE_UNKNOWN:
7289                 case Display.STATE_OFF:
7290                 case Display.STATE_DOZE:
7291                 case Display.STATE_DOZE_SUSPEND:
7292                 case Display.STATE_ON_SUSPEND:
7293                 case Display.STATE_ON:
7294                     break;
7295                 default:
7296                     screenState = Display.STATE_UNKNOWN;
7297                     break;
7298             }
7299             if (screenBrightnessInt < PowerManager.BRIGHTNESS_DEFAULT
7300                     || screenBrightnessInt > PowerManager.BRIGHTNESS_ON) {
7301                 screenBrightnessInt = PowerManager.BRIGHTNESS_DEFAULT;
7302             }
7303             if (screenBrightnessFloat != PowerManager.BRIGHTNESS_OFF_FLOAT
7304                     && (screenBrightnessFloat < PowerManager.BRIGHTNESS_MIN
7305                     || screenBrightnessFloat > PowerManager.BRIGHTNESS_MAX)) {
7306                 screenBrightnessFloat = PowerManager.BRIGHTNESS_INVALID_FLOAT;
7307             }
7308             setDozeOverrideFromDreamManagerInternal(screenState, reason, screenBrightnessFloat,
7309                     screenBrightnessInt, useNormalBrightnessForDoze);
7310         }
7311 
7312         @Override
7313         public void setUserInactiveOverrideFromWindowManager() {
7314             setUserInactiveOverrideFromWindowManagerInternal();
7315         }
7316 
7317         @Override
7318         public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
7319             setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
7320         }
7321 
7322         @Override
7323         public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
7324             setDrawWakeLockOverrideFromSidekickInternal(keepState);
7325         }
7326 
7327         @Override
7328         public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
7329             setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
7330         }
7331 
7332         @Override
7333         public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
7334             // Return default PowerSaveState if battery saver is not supported.
7335             return mBatterySaverSupported
7336                     ?
7337                     mBatterySaverStateMachine.getBatterySaverPolicy().getBatterySaverPolicy(
7338                             serviceType) : new PowerSaveState.Builder().build();
7339         }
7340 
7341         @Override
7342         public void registerLowPowerModeObserver(LowPowerModeListener listener) {
7343             if (mBatterySaverSupported) {
7344                 mBatterySaverStateMachine.getBatterySaverController().addListener(listener);
7345             } else {
7346                 Slog.w(TAG,
7347                         "Battery saver is not supported, no low power mode observer registered");
7348             }
7349         }
7350 
7351         @Override
7352         public boolean setDeviceIdleMode(boolean enabled) {
7353             return setDeviceIdleModeInternal(enabled);
7354         }
7355 
7356         @Override
7357         public boolean setLightDeviceIdleMode(boolean enabled) {
7358             return setLightDeviceIdleModeInternal(enabled);
7359         }
7360 
7361         @Override
7362         public void setDeviceIdleWhitelist(int[] appids) {
7363             setDeviceIdleWhitelistInternal(appids);
7364         }
7365 
7366         @Override
7367         public void setDeviceIdleTempWhitelist(int[] appids) {
7368             setDeviceIdleTempWhitelistInternal(appids);
7369         }
7370 
7371         @Override
7372         public void setLowPowerStandbyAllowlist(int[] appids) {
7373             setLowPowerStandbyAllowlistInternal(appids);
7374         }
7375 
7376         @Override
7377         public void setLowPowerStandbyActive(boolean enabled) {
7378             setLowPowerStandbyActiveInternal(enabled);
7379         }
7380 
7381         @Override
7382         public void startUidChanges() {
7383             startUidChangesInternal();
7384         }
7385 
7386         @Override
7387         public void finishUidChanges() {
7388             finishUidChangesInternal();
7389         }
7390 
7391         @Override
7392         public void updateUidProcState(int uid, int procState) {
7393             updateUidProcStateInternal(uid, procState);
7394         }
7395 
7396         @Override
7397         public void uidGone(int uid) {
7398             uidGoneInternal(uid);
7399         }
7400 
7401         @Override
7402         public void uidActive(int uid) {
7403             uidActiveInternal(uid);
7404         }
7405 
7406         @Override
7407         public void uidIdle(int uid) {
7408             uidIdleInternal(uid);
7409         }
7410 
7411         @Override
7412         public void setPowerBoost(int boost, int durationMs) {
7413             setPowerBoostInternal(boost, durationMs);
7414         }
7415 
7416         @Override
7417         public void setPowerMode(int mode, boolean enabled) {
7418             setPowerModeInternal(mode, enabled);
7419         }
7420 
7421         @Override
7422         public boolean wasDeviceIdleFor(long ms) {
7423             return wasDeviceIdleForInternal(ms);
7424         }
7425 
7426         @Override
7427         public PowerManager.WakeData getLastWakeup() {
7428             return getLastWakeupInternal();
7429         }
7430 
7431         @Override
7432         public PowerManager.SleepData getLastGoToSleep() {
7433             return getLastGoToSleepInternal();
7434         }
7435 
7436         @Override
7437         public boolean interceptPowerKeyDown(KeyEvent event) {
7438             return interceptPowerKeyDownInternal(event);
7439         }
7440 
7441         @Override
7442         public void nap(long eventTime, boolean allowWake) {
7443             napInternal(eventTime, Process.SYSTEM_UID, allowWake);
7444         }
7445 
7446         @Override
7447         public boolean isAmbientDisplaySuppressed() {
7448             return mAmbientDisplaySuppressionController.isSuppressed();
7449         }
7450 
7451         @Override
7452         public void setDevicePostured(boolean isPostured) {
7453             setDevicePosturedInternal(isPostured);
7454         }
7455 
7456         @Override
7457         public void updateSettings() {
7458             synchronized (mLock) {
7459                 updateSettingsLocked();
7460             }
7461         }
7462     }
7463 
7464     /**
7465      * Listens to changes in device state and updates the interactivity time.
7466      * Any changes to the device state are treated as user interactions.
7467      */
7468     class DeviceStateListener implements DeviceStateManager.DeviceStateCallback {
7469         private int mDeviceState = DeviceStateManager.INVALID_DEVICE_STATE_IDENTIFIER;
7470 
7471         @Override
7472         public void onDeviceStateChanged(@NonNull DeviceState deviceState) {
7473             int stateIdentifier = deviceState.getIdentifier();
7474             if (mDeviceState != stateIdentifier) {
7475                 mDeviceState = stateIdentifier;
7476                 // Device-state interactions are applied to the default display so that they
7477                 // are reflected only with the default power group.
7478                 userActivityInternal(Display.DEFAULT_DISPLAY, mClock.uptimeMillis(),
7479                         PowerManager.USER_ACTIVITY_EVENT_DEVICE_STATE, /* flags= */0,
7480                         Process.SYSTEM_UID);
7481             }
7482         }
7483     };
7484 
7485     static boolean isSameCallback(IWakeLockCallback callback1,
7486             IWakeLockCallback callback2) {
7487         if (callback1 == callback2) {
7488             return true;
7489         }
7490         if (callback1 != null && callback2 != null
7491                 && callback1.asBinder() == callback2.asBinder()) {
7492             return true;
7493         }
7494         return false;
7495     }
7496 
7497     private void releaseAllOverrideWakeLocks(int releaseReason) {
7498         synchronized (mLock) {
7499             final int size = mWakeLocks.size();
7500             boolean change = false;
7501             for (int i = size - 1; i >= 0; i--) {
7502                 final WakeLock wakeLock = mWakeLocks.get(i);
7503                 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
7504                         == PowerManager.SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK) {
7505                     removeWakeLockNoUpdateLocked(wakeLock, i, releaseReason);
7506                     change = true;
7507                 }
7508             }
7509 
7510             if (change) {
7511                 updatePowerStateLocked();
7512             }
7513         }
7514     }
7515 
7516     private int getDisplayGroupId(int displayId) {
7517         DisplayInfo displayInfo = mDisplayManagerInternal.getDisplayInfo(displayId);
7518         if (displayInfo == null) {
7519             return Display.INVALID_DISPLAY_GROUP;
7520         }
7521         return displayInfo.displayGroupId;
7522     }
7523 }
7524