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