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