• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.power;
18 
19 import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
20 import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
21 import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
22 import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
23 
24 import android.annotation.IntDef;
25 import android.annotation.NonNull;
26 import android.annotation.UserIdInt;
27 import android.app.ActivityManager;
28 import android.app.SynchronousUserSwitchObserver;
29 import android.content.BroadcastReceiver;
30 import android.content.ContentResolver;
31 import android.content.Context;
32 import android.content.Intent;
33 import android.content.IntentFilter;
34 import android.content.pm.PackageManager;
35 import android.content.res.Resources;
36 import android.database.ContentObserver;
37 import android.hardware.SensorManager;
38 import android.hardware.SystemSensorManager;
39 import android.hardware.display.AmbientDisplayConfiguration;
40 import android.hardware.display.DisplayManagerInternal;
41 import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
42 import android.hardware.power.V1_0.PowerHint;
43 import android.net.Uri;
44 import android.os.BatteryManager;
45 import android.os.BatteryManagerInternal;
46 import android.os.BatterySaverPolicyConfig;
47 import android.os.Binder;
48 import android.os.Handler;
49 import android.os.IBinder;
50 import android.os.IPowerManager;
51 import android.os.Looper;
52 import android.os.Message;
53 import android.os.PowerManager;
54 import android.os.PowerManager.ServiceType;
55 import android.os.PowerManager.WakeData;
56 import android.os.PowerManager.WakeReason;
57 import android.os.PowerManagerInternal;
58 import android.os.PowerSaveState;
59 import android.os.Process;
60 import android.os.RemoteException;
61 import android.os.ResultReceiver;
62 import android.os.ShellCallback;
63 import android.os.SystemClock;
64 import android.os.SystemProperties;
65 import android.os.Trace;
66 import android.os.UserHandle;
67 import android.os.UserManager;
68 import android.os.WorkSource;
69 import android.os.WorkSource.WorkChain;
70 import android.provider.Settings;
71 import android.provider.Settings.SettingNotFoundException;
72 import android.service.dreams.DreamManagerInternal;
73 import android.service.vr.IVrManager;
74 import android.service.vr.IVrStateCallbacks;
75 import android.util.KeyValueListParser;
76 import android.util.PrintWriterPrinter;
77 import android.util.Slog;
78 import android.util.SparseArray;
79 import android.util.TimeUtils;
80 import android.util.proto.ProtoOutputStream;
81 import android.view.Display;
82 
83 import com.android.internal.annotations.VisibleForTesting;
84 import com.android.internal.app.IAppOpsService;
85 import com.android.internal.app.IBatteryStats;
86 import com.android.internal.os.BackgroundThread;
87 import com.android.internal.util.DumpUtils;
88 import com.android.server.EventLogTags;
89 import com.android.server.LockGuard;
90 import com.android.server.RescueParty;
91 import com.android.server.ServiceThread;
92 import com.android.server.SystemService;
93 import com.android.server.UiThread;
94 import com.android.server.Watchdog;
95 import com.android.server.am.BatteryStatsService;
96 import com.android.server.lights.Light;
97 import com.android.server.lights.LightsManager;
98 import com.android.server.policy.WindowManagerPolicy;
99 import com.android.server.power.batterysaver.BatterySaverController;
100 import com.android.server.power.batterysaver.BatterySaverPolicy;
101 import com.android.server.power.batterysaver.BatterySaverStateMachine;
102 import com.android.server.power.batterysaver.BatterySavingStats;
103 
104 import java.io.FileDescriptor;
105 import java.io.PrintWriter;
106 import java.lang.annotation.Retention;
107 import java.lang.annotation.RetentionPolicy;
108 import java.util.ArrayList;
109 import java.util.Arrays;
110 import java.util.Objects;
111 
112 /**
113  * The power manager service is responsible for coordinating power management
114  * functions on the device.
115  */
116 public final class PowerManagerService extends SystemService
117         implements Watchdog.Monitor {
118     private static final String TAG = "PowerManagerService";
119 
120     private static final boolean DEBUG = false;
121     private static final boolean DEBUG_SPEW = DEBUG && true;
122 
123     // Message: Sent when a user activity timeout occurs to update the power state.
124     private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
125     // Message: Sent when the device enters or exits a dreaming or dozing state.
126     private static final int MSG_SANDMAN = 2;
127     // Message: Sent when the screen brightness boost expires.
128     private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
129     // Message: Polling to look for long held wake locks.
130     private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
131 
132     // Dirty bit: mWakeLocks changed
133     private static final int DIRTY_WAKE_LOCKS = 1 << 0;
134     // Dirty bit: mWakefulness changed
135     private static final int DIRTY_WAKEFULNESS = 1 << 1;
136     // Dirty bit: user activity was poked or may have timed out
137     private static final int DIRTY_USER_ACTIVITY = 1 << 2;
138     // Dirty bit: actual display power state was updated asynchronously
139     private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
140     // Dirty bit: mBootCompleted changed
141     private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
142     // Dirty bit: settings changed
143     private static final int DIRTY_SETTINGS = 1 << 5;
144     // Dirty bit: mIsPowered changed
145     private static final int DIRTY_IS_POWERED = 1 << 6;
146     // Dirty bit: mStayOn changed
147     private static final int DIRTY_STAY_ON = 1 << 7;
148     // Dirty bit: battery state changed
149     private static final int DIRTY_BATTERY_STATE = 1 << 8;
150     // Dirty bit: proximity state changed
151     private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
152     // Dirty bit: dock state changed
153     private static final int DIRTY_DOCK_STATE = 1 << 10;
154     // Dirty bit: brightness boost changed
155     private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
156     // Dirty bit: sQuiescent changed
157     private static final int DIRTY_QUIESCENT = 1 << 12;
158     // Dirty bit: VR Mode enabled changed
159     private static final int DIRTY_VR_MODE_CHANGED = 1 << 13;
160 
161     // Summarizes the state of all active wakelocks.
162     private static final int WAKE_LOCK_CPU = 1 << 0;
163     private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
164     private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
165     private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
166     private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
167     private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
168     private static final int WAKE_LOCK_DOZE = 1 << 6;
169     private static final int WAKE_LOCK_DRAW = 1 << 7;
170 
171     // Summarizes the user activity state.
172     private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
173     private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
174     private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
175 
176     // Default timeout in milliseconds.  This is only used until the settings
177     // provider populates the actual default value (R.integer.def_screen_off_timeout).
178     private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
179     private static final int DEFAULT_SLEEP_TIMEOUT = -1;
180 
181     // Screen brightness boost timeout.
182     // Hardcoded for now until we decide what the right policy should be.
183     // This should perhaps be a setting.
184     private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
185 
186     // How long a partial wake lock must be held until we consider it a long wake lock.
187     static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
188 
189     // Power features defined in hardware/libhardware/include/hardware/power.h.
190     private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1;
191 
192     // Default setting for double tap to wake.
193     private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
194 
195     // System property indicating that the screen should remain off until an explicit user action
196     private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
197 
198     // System Property indicating that retail demo mode is currently enabled.
199     private static final String SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED = "sys.retaildemo.enabled";
200 
201     // Possible reasons for shutting down or reboot for use in REBOOT_PROPERTY(sys.boot.reason)
202     // which is set by bootstat
203     private static final String REASON_SHUTDOWN = "shutdown";
204     private static final String REASON_REBOOT = "reboot";
205     private static final String REASON_USERREQUESTED = "shutdown,userrequested";
206     private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
207     private static final String REASON_LOW_BATTERY = "shutdown,battery";
208     private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
209 
210     private static final String TRACE_SCREEN_ON = "Screen turning on";
211 
212     /** If turning screen on takes more than this long, we show a warning on logcat. */
213     private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
214 
215     /** Constants for {@link #shutdownOrRebootInternal} */
216     @Retention(RetentionPolicy.SOURCE)
217     @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
218     public @interface HaltMode {}
219     private static final int HALT_MODE_SHUTDOWN = 0;
220     private static final int HALT_MODE_REBOOT = 1;
221     private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
222 
223     // property for last reboot reason
224     private static final String REBOOT_PROPERTY = "sys.boot.reason";
225 
226     private final Context mContext;
227     private final ServiceThread mHandlerThread;
228     private final PowerManagerHandler mHandler;
229     private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
230     private final BatterySaverPolicy mBatterySaverPolicy;
231     private final BatterySaverController mBatterySaverController;
232     private final BatterySaverStateMachine mBatterySaverStateMachine;
233     private final BatterySavingStats mBatterySavingStats;
234     private final AttentionDetector mAttentionDetector;
235     private final BinderService mBinderService;
236     private final LocalService mLocalService;
237     private final NativeWrapper mNativeWrapper;
238     private final Injector mInjector;
239 
240     private LightsManager mLightsManager;
241     private BatteryManagerInternal mBatteryManagerInternal;
242     private DisplayManagerInternal mDisplayManagerInternal;
243     private IBatteryStats mBatteryStats;
244     private IAppOpsService mAppOps;
245     private WindowManagerPolicy mPolicy;
246     private Notifier mNotifier;
247     private WirelessChargerDetector mWirelessChargerDetector;
248     private SettingsObserver mSettingsObserver;
249     private DreamManagerInternal mDreamManager;
250     private Light mAttentionLight;
251 
252     private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
253 
254     // A bitfield that indicates what parts of the power state have
255     // changed and need to be recalculated.
256     private int mDirty;
257 
258     // Indicates whether the device is awake or asleep or somewhere in between.
259     // This is distinct from the screen power state, which is managed separately.
260     private int mWakefulness;
261     private boolean mWakefulnessChanging;
262 
263     // True if the sandman has just been summoned for the first time since entering the
264     // dreaming or dozing state.  Indicates whether a new dream should begin.
265     private boolean mSandmanSummoned;
266 
267     // True if MSG_SANDMAN has been scheduled.
268     private boolean mSandmanScheduled;
269 
270     // Table of all suspend blockers.
271     // There should only be a few of these.
272     private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
273 
274     // Table of all wake locks acquired by applications.
275     private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
276 
277     // A bitfield that summarizes the state of all active wakelocks.
278     private int mWakeLockSummary;
279 
280     // Have we scheduled a message to check for long wake locks?  This is when we will check.
281     private long mNotifyLongScheduled;
282 
283     // Last time we checked for long wake locks.
284     private long mNotifyLongDispatched;
285 
286     // The time we decided to do next long check.
287     private long mNotifyLongNextCheck;
288 
289     // If true, instructs the display controller to wait for the proximity sensor to
290     // go negative before turning the screen on.
291     private boolean mRequestWaitForNegativeProximity;
292 
293     // Timestamp of the last time the device was awoken or put to sleep.
294     private long mLastWakeTime;
295     private long mLastSleepTime;
296 
297     // Last reason the device went to sleep.
298     private @WakeReason int mLastWakeReason;
299     private int mLastSleepReason;
300 
301     // Timestamp of the last call to user activity.
302     private long mLastUserActivityTime;
303     private long mLastUserActivityTimeNoChangeLights;
304 
305     // Timestamp of last interactive power hint.
306     private long mLastInteractivePowerHintTime;
307 
308     // Timestamp of the last screen brightness boost.
309     private long mLastScreenBrightnessBoostTime;
310     private boolean mScreenBrightnessBoostInProgress;
311 
312     // A bitfield that summarizes the effect of the user activity timer.
313     private int mUserActivitySummary;
314 
315     // The desired display power state.  The actual state may lag behind the
316     // requested because it is updated asynchronously by the display power controller.
317     private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
318 
319     // True if the display power state has been fully applied, which means the display
320     // is actually on or actually off or whatever was requested.
321     private boolean mDisplayReady;
322 
323     // The suspend blocker used to keep the CPU alive when an application has acquired
324     // a wake lock.
325     private final SuspendBlocker mWakeLockSuspendBlocker;
326 
327     // True if the wake lock suspend blocker has been acquired.
328     private boolean mHoldingWakeLockSuspendBlocker;
329 
330     // The suspend blocker used to keep the CPU alive when the display is on, the
331     // display is getting ready or there is user activity (in which case the display
332     // must be on).
333     private final SuspendBlocker mDisplaySuspendBlocker;
334 
335     // True if the display suspend blocker has been acquired.
336     private boolean mHoldingDisplaySuspendBlocker;
337 
338     // True if systemReady() has been called.
339     private boolean mSystemReady;
340 
341     // True if boot completed occurred.  We keep the screen on until this happens.
342     private boolean mBootCompleted;
343 
344     // True if auto-suspend mode is enabled.
345     // Refer to autosuspend.h.
346     private boolean mHalAutoSuspendModeEnabled;
347 
348     // True if interactive mode is enabled.
349     // Refer to power.h.
350     private boolean mHalInteractiveModeEnabled;
351 
352     // True if the device is plugged into a power source.
353     private boolean mIsPowered;
354 
355     // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
356     private int mPlugType;
357 
358     // The current battery level percentage.
359     private int mBatteryLevel;
360 
361     // The battery level percentage at the time the dream started.
362     // This is used to terminate a dream and go to sleep if the battery is
363     // draining faster than it is charging and the user activity timeout has expired.
364     private int mBatteryLevelWhenDreamStarted;
365 
366     // The current dock state.
367     private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
368 
369     // True to decouple auto-suspend mode from the display state.
370     private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
371 
372     // True to decouple interactive mode from the display state.
373     private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
374 
375     // True if the device should wake up when plugged or unplugged.
376     private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
377 
378     // True if the device should wake up when plugged or unplugged in theater mode.
379     private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
380 
381     // True if the device should suspend when the screen is off due to proximity.
382     private boolean mSuspendWhenScreenOffDueToProximityConfig;
383 
384     // True if dreams are supported on this device.
385     private boolean mDreamsSupportedConfig;
386 
387     // Default value for dreams enabled
388     private boolean mDreamsEnabledByDefaultConfig;
389 
390     // Default value for dreams activate-on-sleep
391     private boolean mDreamsActivatedOnSleepByDefaultConfig;
392 
393     // Default value for dreams activate-on-dock
394     private boolean mDreamsActivatedOnDockByDefaultConfig;
395 
396     // True if dreams can run while not plugged in.
397     private boolean mDreamsEnabledOnBatteryConfig;
398 
399     // Minimum battery level to allow dreaming when powered.
400     // Use -1 to disable this safety feature.
401     private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
402 
403     // Minimum battery level to allow dreaming when not powered.
404     // Use -1 to disable this safety feature.
405     private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
406 
407     // If the battery level drops by this percentage and the user activity timeout
408     // has expired, then assume the device is receiving insufficient current to charge
409     // effectively and terminate the dream.  Use -1 to disable this safety feature.
410     private int mDreamsBatteryLevelDrainCutoffConfig;
411 
412     // True if dreams are enabled by the user.
413     private boolean mDreamsEnabledSetting;
414 
415     // True if dreams should be activated on sleep.
416     private boolean mDreamsActivateOnSleepSetting;
417 
418     // True if dreams should be activated on dock.
419     private boolean mDreamsActivateOnDockSetting;
420 
421     // True if doze should not be started until after the screen off transition.
422     private boolean mDozeAfterScreenOff;
423 
424     // The minimum screen off timeout, in milliseconds.
425     private long mMinimumScreenOffTimeoutConfig;
426 
427     // The screen dim duration, in milliseconds.
428     // This is subtracted from the end of the screen off timeout so the
429     // minimum screen off timeout should be longer than this.
430     private long mMaximumScreenDimDurationConfig;
431 
432     // The maximum screen dim time expressed as a ratio relative to the screen
433     // off timeout.  If the screen off timeout is very short then we want the
434     // dim timeout to also be quite short so that most of the time is spent on.
435     // Otherwise the user won't get much screen on time before dimming occurs.
436     private float mMaximumScreenDimRatioConfig;
437 
438     // Whether device supports double tap to wake.
439     private boolean mSupportsDoubleTapWakeConfig;
440 
441     // The screen off timeout setting value in milliseconds.
442     private long mScreenOffTimeoutSetting;
443 
444     // The sleep timeout setting value in milliseconds.
445     private long mSleepTimeoutSetting;
446 
447     // The maximum allowable screen off timeout according to the device
448     // administration policy.  Overrides other settings.
449     private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
450 
451     // The stay on while plugged in setting.
452     // A bitfield of battery conditions under which to make the screen stay on.
453     private int mStayOnWhilePluggedInSetting;
454 
455     // True if the device should stay on.
456     private boolean mStayOn;
457 
458     // True if the lights should stay off until an explicit user action.
459     private static boolean sQuiescent;
460 
461     // True if the proximity sensor reads a positive result.
462     private boolean mProximityPositive;
463 
464     // Screen brightness setting limits.
465     private int mScreenBrightnessSettingMinimum;
466     private int mScreenBrightnessSettingMaximum;
467     private int mScreenBrightnessSettingDefault;
468 
469     // The screen brightness setting, from 0 to 255.
470     // Use -1 if no value has been set.
471     private int mScreenBrightnessSetting;
472 
473     // The screen brightness mode.
474     // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
475     private int mScreenBrightnessModeSetting;
476 
477     // The screen brightness setting override from the window manager
478     // to allow the current foreground activity to override the brightness.
479     // Use -1 to disable.
480     private int mScreenBrightnessOverrideFromWindowManager = -1;
481 
482     // The window manager has determined the user to be inactive via other means.
483     // Set this to false to disable.
484     private boolean mUserInactiveOverrideFromWindowManager;
485 
486     // The next possible user activity timeout after being explicitly told the user is inactive.
487     // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
488     private long mOverriddenTimeout = -1;
489 
490     // The user activity timeout override from the window manager
491     // to allow the current foreground activity to override the user activity timeout.
492     // Use -1 to disable.
493     private long mUserActivityTimeoutOverrideFromWindowManager = -1;
494 
495     // The screen state to use while dozing.
496     private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
497 
498     // The screen brightness to use while dozing.
499     private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
500 
501     // Keep display state when dozing.
502     private boolean mDrawWakeLockOverrideFromSidekick;
503 
504     // Time when we last logged a warning about calling userActivity() without permission.
505     private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
506 
507     // True if the battery level is currently considered low.
508     private boolean mBatteryLevelLow;
509 
510     // True if we are currently in device idle mode.
511     private boolean mDeviceIdleMode;
512 
513     // True if we are currently in light device idle mode.
514     private boolean mLightDeviceIdleMode;
515 
516     // Set of app ids that we will always respect the wake locks for.
517     int[] mDeviceIdleWhitelist = new int[0];
518 
519     // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
520     int[] mDeviceIdleTempWhitelist = new int[0];
521 
522     private final SparseArray<UidState> mUidState = new SparseArray<>();
523 
524     // We are currently in the middle of a batch change of uids.
525     private boolean mUidsChanging;
526 
527     // Some uids have actually changed while mUidsChanging was true.
528     private boolean mUidsChanged;
529 
530     // True if theater mode is enabled
531     private boolean mTheaterModeEnabled;
532 
533     // True if always on display is enabled
534     private boolean mAlwaysOnEnabled;
535 
536     // True if double tap to wake is enabled
537     private boolean mDoubleTapWakeEnabled;
538 
539     // True if we are currently in VR Mode.
540     private boolean mIsVrModeEnabled;
541 
542     // True if we in the process of performing a forceSuspend
543     private boolean mForceSuspendActive;
544 
545     private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
546         @Override
onUserSwitching(int newUserId)547         public void onUserSwitching(int newUserId) throws RemoteException {}
548 
549         @Override
onForegroundProfileSwitch(@serIdInt int newProfileId)550         public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
551             final long now = SystemClock.uptimeMillis();
552             synchronized(mLock) {
553                 mForegroundProfile = newProfileId;
554                 maybeUpdateForegroundProfileLastActivityLocked(now);
555             }
556         }
557     }
558 
559     // User id corresponding to activity the user is currently interacting with.
560     private @UserIdInt int mForegroundProfile;
561 
562     // Per-profile state to track when a profile should be locked.
563     private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
564 
565     private static final class ProfilePowerState {
566         // Profile user id.
567         final @UserIdInt int mUserId;
568         // Maximum time to lock set by admin.
569         long mScreenOffTimeout;
570         // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
571         int mWakeLockSummary;
572         // Last user activity that happened in an app running in the profile.
573         long mLastUserActivityTime;
574         // Whether profile has been locked last time it timed out.
575         boolean mLockingNotified;
576 
ProfilePowerState(@serIdInt int userId, long screenOffTimeout)577         public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout) {
578             mUserId = userId;
579             mScreenOffTimeout = screenOffTimeout;
580             // Not accurate but at least won't cause immediate locking of the profile.
581             mLastUserActivityTime = SystemClock.uptimeMillis();
582         }
583     }
584 
585     /**
586      * All times are in milliseconds. These constants are kept synchronized with the system
587      * global Settings. Any access to this class or its fields should be done while
588      * holding the PowerManagerService.mLock lock.
589      */
590     private final class Constants extends ContentObserver {
591         // Key names stored in the settings value.
592         private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
593 
594         private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
595 
596         // Prevent processes that are cached from holding wake locks?
597         public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
598 
599         private ContentResolver mResolver;
600         private final KeyValueListParser mParser = new KeyValueListParser(',');
601 
Constants(Handler handler)602         public Constants(Handler handler) {
603             super(handler);
604         }
605 
start(ContentResolver resolver)606         public void start(ContentResolver resolver) {
607             mResolver = resolver;
608             mResolver.registerContentObserver(Settings.Global.getUriFor(
609                     Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
610             updateConstants();
611         }
612 
613         @Override
onChange(boolean selfChange, Uri uri)614         public void onChange(boolean selfChange, Uri uri) {
615             updateConstants();
616         }
617 
updateConstants()618         private void updateConstants() {
619             synchronized (mLock) {
620                 try {
621                     mParser.setString(Settings.Global.getString(mResolver,
622                             Settings.Global.POWER_MANAGER_CONSTANTS));
623                 } catch (IllegalArgumentException e) {
624                     // Failed to parse the settings string, log this and move on
625                     // with defaults.
626                     Slog.e(TAG, "Bad alarm manager settings", e);
627                 }
628 
629                 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
630                         DEFAULT_NO_CACHED_WAKE_LOCKS);
631             }
632         }
633 
dump(PrintWriter pw)634         void dump(PrintWriter pw) {
635             pw.println("  Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
636 
637             pw.print("    "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
638             pw.println(NO_CACHED_WAKE_LOCKS);
639         }
640 
dumpProto(ProtoOutputStream proto)641         void dumpProto(ProtoOutputStream proto) {
642             final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
643             proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
644                     NO_CACHED_WAKE_LOCKS);
645             proto.end(constantsToken);
646         }
647     }
648 
649     /**
650      * Wrapper around the static-native methods of PowerManagerService.
651      *
652      * This class exists to allow us to mock static native methods in our tests. If mocking static
653      * methods becomes easier than this in the future, we can delete this class.
654      */
655     @VisibleForTesting
656     public static class NativeWrapper {
657         /** Wrapper for PowerManager.nativeInit */
nativeInit(PowerManagerService service)658         public void nativeInit(PowerManagerService service) {
659             service.nativeInit();
660         }
661 
662         /** Wrapper for PowerManager.nativeAcquireSuspectBlocker */
nativeAcquireSuspendBlocker(String name)663         public void nativeAcquireSuspendBlocker(String name) {
664             PowerManagerService.nativeAcquireSuspendBlocker(name);
665         }
666 
667         /** Wrapper for PowerManager.nativeReleaseSuspendBlocker */
nativeReleaseSuspendBlocker(String name)668         public void nativeReleaseSuspendBlocker(String name) {
669             PowerManagerService.nativeReleaseSuspendBlocker(name);
670         }
671 
672         /** Wrapper for PowerManager.nativeSetInteractive */
nativeSetInteractive(boolean enable)673         public void nativeSetInteractive(boolean enable) {
674             PowerManagerService.nativeSetInteractive(enable);
675         }
676 
677         /** Wrapper for PowerManager.nativeSetAutoSuspend */
nativeSetAutoSuspend(boolean enable)678         public void nativeSetAutoSuspend(boolean enable) {
679             PowerManagerService.nativeSetAutoSuspend(enable);
680         }
681 
682         /** Wrapper for PowerManager.nativeSendPowerHint */
nativeSendPowerHint(int hintId, int data)683         public void nativeSendPowerHint(int hintId, int data) {
684             PowerManagerService.nativeSendPowerHint(hintId, data);
685         }
686 
687         /** Wrapper for PowerManager.nativeSetFeature */
nativeSetFeature(int featureId, int data)688         public void nativeSetFeature(int featureId, int data) {
689             PowerManagerService.nativeSetFeature(featureId, data);
690         }
691 
692         /** Wrapper for PowerManager.nativeForceSuspend */
nativeForceSuspend()693         public boolean nativeForceSuspend() {
694             return PowerManagerService.nativeForceSuspend();
695         }
696     }
697 
698     @VisibleForTesting
699     static class Injector {
createNotifier(Looper looper, Context context, IBatteryStats batteryStats, SuspendBlocker suspendBlocker, WindowManagerPolicy policy)700         Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
701                 SuspendBlocker suspendBlocker, WindowManagerPolicy policy) {
702             return new Notifier(looper, context, batteryStats, suspendBlocker, policy);
703         }
704 
createSuspendBlocker(PowerManagerService service, String name)705         SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
706             SuspendBlocker suspendBlocker = service.new SuspendBlockerImpl(name);
707             service.mSuspendBlockers.add(suspendBlocker);
708             return suspendBlocker;
709         }
710 
createBatterySaverPolicy( Object lock, Context context, BatterySavingStats batterySavingStats)711         BatterySaverPolicy createBatterySaverPolicy(
712                 Object lock, Context context, BatterySavingStats batterySavingStats) {
713             return new BatterySaverPolicy(lock, context, batterySavingStats);
714         }
715 
createNativeWrapper()716         NativeWrapper createNativeWrapper() {
717             return new NativeWrapper();
718         }
719 
createWirelessChargerDetector( SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler)720         WirelessChargerDetector createWirelessChargerDetector(
721                 SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
722             return new WirelessChargerDetector(sensorManager, suspendBlocker, handler);
723         }
724 
createAmbientDisplayConfiguration(Context context)725         AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
726             return new AmbientDisplayConfiguration(context);
727         }
728     }
729 
730     final Constants mConstants;
731 
nativeInit()732     private native void nativeInit();
nativeAcquireSuspendBlocker(String name)733     private static native void nativeAcquireSuspendBlocker(String name);
nativeReleaseSuspendBlocker(String name)734     private static native void nativeReleaseSuspendBlocker(String name);
nativeSetInteractive(boolean enable)735     private static native void nativeSetInteractive(boolean enable);
nativeSetAutoSuspend(boolean enable)736     private static native void nativeSetAutoSuspend(boolean enable);
nativeSendPowerHint(int hintId, int data)737     private static native void nativeSendPowerHint(int hintId, int data);
nativeSetFeature(int featureId, int data)738     private static native void nativeSetFeature(int featureId, int data);
nativeForceSuspend()739     private static native boolean nativeForceSuspend();
740 
PowerManagerService(Context context)741     public PowerManagerService(Context context) {
742         this(context, new Injector());
743     }
744 
745     @VisibleForTesting
PowerManagerService(Context context, Injector injector)746     PowerManagerService(Context context, Injector injector) {
747         super(context);
748 
749         mContext = context;
750         mBinderService = new BinderService();
751         mLocalService = new LocalService();
752         mNativeWrapper = injector.createNativeWrapper();
753         mInjector = injector;
754 
755         mHandlerThread = new ServiceThread(TAG,
756                 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
757         mHandlerThread.start();
758         mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
759         mConstants = new Constants(mHandler);
760         mAmbientDisplayConfiguration = mInjector.createAmbientDisplayConfiguration(context);
761         mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
762 
763         mBatterySavingStats = new BatterySavingStats(mLock);
764         mBatterySaverPolicy =
765                 mInjector.createBatterySaverPolicy(mLock, mContext, mBatterySavingStats);
766         mBatterySaverController = new BatterySaverController(mLock, mContext,
767                 BackgroundThread.get().getLooper(), mBatterySaverPolicy,
768                 mBatterySavingStats);
769         mBatterySaverStateMachine = new BatterySaverStateMachine(
770                 mLock, mContext, mBatterySaverController);
771 
772         synchronized (mLock) {
773             mWakeLockSuspendBlocker =
774                     mInjector.createSuspendBlocker(this, "PowerManagerService.WakeLocks");
775             mDisplaySuspendBlocker =
776                     mInjector.createSuspendBlocker(this, "PowerManagerService.Display");
777             if (mDisplaySuspendBlocker != null) {
778                 mDisplaySuspendBlocker.acquire();
779                 mHoldingDisplaySuspendBlocker = true;
780             }
781             mHalAutoSuspendModeEnabled = false;
782             mHalInteractiveModeEnabled = true;
783 
784             mWakefulness = WAKEFULNESS_AWAKE;
785             sQuiescent = SystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
786 
787             mNativeWrapper.nativeInit(this);
788             mNativeWrapper.nativeSetAutoSuspend(false);
789             mNativeWrapper.nativeSetInteractive(true);
790             mNativeWrapper.nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
791         }
792     }
793 
794     @Override
onStart()795     public void onStart() {
796         publishBinderService(Context.POWER_SERVICE, mBinderService);
797         publishLocalService(PowerManagerInternal.class, mLocalService);
798 
799         Watchdog.getInstance().addMonitor(this);
800         Watchdog.getInstance().addThread(mHandler);
801     }
802 
803     @Override
onBootPhase(int phase)804     public void onBootPhase(int phase) {
805         synchronized (mLock) {
806             if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
807                 incrementBootCount();
808 
809             } else if (phase == PHASE_BOOT_COMPLETED) {
810                 final long now = SystemClock.uptimeMillis();
811                 mBootCompleted = true;
812                 mDirty |= DIRTY_BOOT_COMPLETED;
813 
814                 mBatterySaverStateMachine.onBootCompleted();
815                 userActivityNoUpdateLocked(
816                         now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
817                 updatePowerStateLocked();
818             }
819         }
820     }
821 
systemReady(IAppOpsService appOps)822     public void systemReady(IAppOpsService appOps) {
823         synchronized (mLock) {
824             mSystemReady = true;
825             mAppOps = appOps;
826             mDreamManager = getLocalService(DreamManagerInternal.class);
827             mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
828             mPolicy = getLocalService(WindowManagerPolicy.class);
829             mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
830             mAttentionDetector.systemReady(mContext);
831 
832             PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
833             mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
834             mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
835             mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
836 
837             SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
838 
839             // The notifier runs on the system server's main looper so as not to interfere
840             // with the animations and other critical functions of the power manager.
841             mBatteryStats = BatteryStatsService.getService();
842             mNotifier = mInjector.createNotifier(Looper.getMainLooper(), mContext, mBatteryStats,
843                     mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
844                     mPolicy);
845 
846             mWirelessChargerDetector = mInjector.createWirelessChargerDetector(sensorManager,
847                     mInjector.createSuspendBlocker(
848                             this, "PowerManagerService.WirelessChargerDetector"),
849                     mHandler);
850             mSettingsObserver = new SettingsObserver(mHandler);
851 
852             mLightsManager = getLocalService(LightsManager.class);
853             mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
854 
855             // Initialize display power management.
856             mDisplayManagerInternal.initPowerManagement(
857                     mDisplayPowerCallbacks, mHandler, sensorManager);
858 
859             try {
860                 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
861                 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
862             } catch (RemoteException e) {
863                 // Shouldn't happen since in-process.
864             }
865 
866             // Go.
867             readConfigurationLocked();
868             updateSettingsLocked();
869             mDirty |= DIRTY_BATTERY_STATE;
870             updatePowerStateLocked();
871         }
872 
873         final ContentResolver resolver = mContext.getContentResolver();
874         mConstants.start(resolver);
875 
876         mBatterySaverController.systemReady();
877         mBatterySaverPolicy.systemReady();
878 
879         // Register for settings changes.
880         resolver.registerContentObserver(Settings.Secure.getUriFor(
881                 Settings.Secure.SCREENSAVER_ENABLED),
882                 false, mSettingsObserver, UserHandle.USER_ALL);
883         resolver.registerContentObserver(Settings.Secure.getUriFor(
884                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
885                 false, mSettingsObserver, UserHandle.USER_ALL);
886         resolver.registerContentObserver(Settings.Secure.getUriFor(
887                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
888                 false, mSettingsObserver, UserHandle.USER_ALL);
889         resolver.registerContentObserver(Settings.System.getUriFor(
890                 Settings.System.SCREEN_OFF_TIMEOUT),
891                 false, mSettingsObserver, UserHandle.USER_ALL);
892         resolver.registerContentObserver(Settings.Secure.getUriFor(
893                 Settings.Secure.SLEEP_TIMEOUT),
894                 false, mSettingsObserver, UserHandle.USER_ALL);
895         resolver.registerContentObserver(Settings.Global.getUriFor(
896                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
897                 false, mSettingsObserver, UserHandle.USER_ALL);
898         resolver.registerContentObserver(Settings.System.getUriFor(
899                 Settings.System.SCREEN_BRIGHTNESS_MODE),
900                 false, mSettingsObserver, UserHandle.USER_ALL);
901         resolver.registerContentObserver(Settings.System.getUriFor(
902                 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
903                 false, mSettingsObserver, UserHandle.USER_ALL);
904         resolver.registerContentObserver(Settings.Global.getUriFor(
905                 Settings.Global.THEATER_MODE_ON),
906                 false, mSettingsObserver, UserHandle.USER_ALL);
907         resolver.registerContentObserver(Settings.Secure.getUriFor(
908                 Settings.Secure.DOZE_ALWAYS_ON),
909                 false, mSettingsObserver, UserHandle.USER_ALL);
910         resolver.registerContentObserver(Settings.Secure.getUriFor(
911                 Settings.Secure.DOUBLE_TAP_TO_WAKE),
912                 false, mSettingsObserver, UserHandle.USER_ALL);
913         resolver.registerContentObserver(Settings.Global.getUriFor(
914                 Settings.Global.DEVICE_DEMO_MODE),
915                 false, mSettingsObserver, UserHandle.USER_SYSTEM);
916         IVrManager vrManager = IVrManager.Stub.asInterface(getBinderService(Context.VR_SERVICE));
917         if (vrManager != null) {
918             try {
919                 vrManager.registerListener(mVrStateCallbacks);
920             } catch (RemoteException e) {
921                 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
922             }
923         }
924 
925         // Register for broadcasts from other components of the system.
926         IntentFilter filter = new IntentFilter();
927         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
928         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
929         mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
930 
931         filter = new IntentFilter();
932         filter.addAction(Intent.ACTION_DREAMING_STARTED);
933         filter.addAction(Intent.ACTION_DREAMING_STOPPED);
934         mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
935 
936         filter = new IntentFilter();
937         filter.addAction(Intent.ACTION_USER_SWITCHED);
938         mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
939 
940         filter = new IntentFilter();
941         filter.addAction(Intent.ACTION_DOCK_EVENT);
942         mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
943     }
944 
945     @VisibleForTesting
readConfigurationLocked()946     void readConfigurationLocked() {
947         final Resources resources = mContext.getResources();
948 
949         mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
950                 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
951         mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
952                 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
953         mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
954                 com.android.internal.R.bool.config_unplugTurnsOnScreen);
955         mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
956                 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
957         mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
958                 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
959         mDreamsSupportedConfig = resources.getBoolean(
960                 com.android.internal.R.bool.config_dreamsSupported);
961         mDreamsEnabledByDefaultConfig = resources.getBoolean(
962                 com.android.internal.R.bool.config_dreamsEnabledByDefault);
963         mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
964                 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
965         mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
966                 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
967         mDreamsEnabledOnBatteryConfig = resources.getBoolean(
968                 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
969         mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
970                 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
971         mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
972                 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
973         mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
974                 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
975         mDozeAfterScreenOff = resources.getBoolean(
976                 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
977         mMinimumScreenOffTimeoutConfig = resources.getInteger(
978                 com.android.internal.R.integer.config_minimumScreenOffTimeout);
979         mMaximumScreenDimDurationConfig = resources.getInteger(
980                 com.android.internal.R.integer.config_maximumScreenDimDuration);
981         mMaximumScreenDimRatioConfig = resources.getFraction(
982                 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
983         mSupportsDoubleTapWakeConfig = resources.getBoolean(
984                 com.android.internal.R.bool.config_supportDoubleTapWake);
985     }
986 
updateSettingsLocked()987     private void updateSettingsLocked() {
988         final ContentResolver resolver = mContext.getContentResolver();
989 
990         mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
991                 Settings.Secure.SCREENSAVER_ENABLED,
992                 mDreamsEnabledByDefaultConfig ? 1 : 0,
993                 UserHandle.USER_CURRENT) != 0);
994         mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
995                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
996                 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
997                 UserHandle.USER_CURRENT) != 0);
998         mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
999                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
1000                 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
1001                 UserHandle.USER_CURRENT) != 0);
1002         mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
1003                 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
1004                 UserHandle.USER_CURRENT);
1005         mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1006                 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
1007                 UserHandle.USER_CURRENT);
1008         mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
1009                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
1010         mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1011                 Settings.Global.THEATER_MODE_ON, 0) == 1;
1012         mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
1013 
1014         if (mSupportsDoubleTapWakeConfig) {
1015             boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
1016                     Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
1017                             UserHandle.USER_CURRENT) != 0;
1018             if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
1019                 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
1020                 mNativeWrapper.nativeSetFeature(
1021                         POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
1022             }
1023         }
1024 
1025         final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
1026         if (!retailDemoValue.equals(SystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED))) {
1027             SystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
1028         }
1029 
1030         mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
1031                 Settings.System.SCREEN_BRIGHTNESS_MODE,
1032                 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
1033 
1034         mDirty |= DIRTY_SETTINGS;
1035     }
1036 
handleSettingsChangedLocked()1037     private void handleSettingsChangedLocked() {
1038         updateSettingsLocked();
1039         updatePowerStateLocked();
1040     }
1041 
acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName, WorkSource ws, String historyTag, int uid, int pid)1042     private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
1043             WorkSource ws, String historyTag, int uid, int pid) {
1044         synchronized (mLock) {
1045             if (DEBUG_SPEW) {
1046                 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1047                         + ", flags=0x" + Integer.toHexString(flags)
1048                         + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
1049             }
1050 
1051             WakeLock wakeLock;
1052             int index = findWakeLockIndexLocked(lock);
1053             boolean notifyAcquire;
1054             if (index >= 0) {
1055                 wakeLock = mWakeLocks.get(index);
1056                 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
1057                     // Update existing wake lock.  This shouldn't happen but is harmless.
1058                     notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1059                             uid, pid, ws, historyTag);
1060                     wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
1061                 }
1062                 notifyAcquire = false;
1063             } else {
1064                 UidState state = mUidState.get(uid);
1065                 if (state == null) {
1066                     state = new UidState(uid);
1067                     state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1068                     mUidState.put(uid, state);
1069                 }
1070                 state.mNumWakeLocks++;
1071                 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
1072                         state);
1073                 try {
1074                     lock.linkToDeath(wakeLock, 0);
1075                 } catch (RemoteException ex) {
1076                     throw new IllegalArgumentException("Wake lock is already dead.");
1077                 }
1078                 mWakeLocks.add(wakeLock);
1079                 setWakeLockDisabledStateLocked(wakeLock);
1080                 notifyAcquire = true;
1081             }
1082 
1083             applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
1084             mDirty |= DIRTY_WAKE_LOCKS;
1085             updatePowerStateLocked();
1086             if (notifyAcquire) {
1087                 // This needs to be done last so we are sure we have acquired the
1088                 // kernel wake lock.  Otherwise we have a race where the system may
1089                 // go to sleep between the time we start the accounting in battery
1090                 // stats and when we actually get around to telling the kernel to
1091                 // stay awake.
1092                 notifyWakeLockAcquiredLocked(wakeLock);
1093             }
1094         }
1095     }
1096 
1097     @SuppressWarnings("deprecation")
isScreenLock(final WakeLock wakeLock)1098     private static boolean isScreenLock(final WakeLock wakeLock) {
1099         switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1100             case PowerManager.FULL_WAKE_LOCK:
1101             case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1102             case PowerManager.SCREEN_DIM_WAKE_LOCK:
1103                 return true;
1104         }
1105         return false;
1106     }
1107 
getFirstNonEmptyWorkChain(WorkSource workSource)1108     private static WorkChain getFirstNonEmptyWorkChain(WorkSource workSource) {
1109         if (workSource.getWorkChains() == null) {
1110             return null;
1111         }
1112 
1113         for (WorkChain workChain: workSource.getWorkChains()) {
1114             if (workChain.getSize() > 0) {
1115                 return workChain;
1116             }
1117         }
1118 
1119         return null;
1120     }
1121 
applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid)1122     private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
1123         if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1124                 && isScreenLock(wakeLock)) {
1125             String opPackageName;
1126             int opUid;
1127             if (wakeLock.mWorkSource != null && !wakeLock.mWorkSource.isEmpty()) {
1128                 WorkSource workSource = wakeLock.mWorkSource;
1129                 WorkChain workChain = getFirstNonEmptyWorkChain(workSource);
1130                 if (workChain != null) {
1131                     opPackageName = workChain.getAttributionTag();
1132                     opUid = workChain.getAttributionUid();
1133                 } else {
1134                     opPackageName = workSource.getName(0) != null
1135                             ? workSource.getName(0) : wakeLock.mPackageName;
1136                     opUid = workSource.get(0);
1137                 }
1138             } else {
1139                 opPackageName = wakeLock.mPackageName;
1140                 opUid = wakeLock.mOwnerUid;
1141             }
1142             wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
1143                     PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag,
1144                     opUid, opPackageName, opUid);
1145         }
1146     }
1147 
releaseWakeLockInternal(IBinder lock, int flags)1148     private void releaseWakeLockInternal(IBinder lock, int flags) {
1149         synchronized (mLock) {
1150             int index = findWakeLockIndexLocked(lock);
1151             if (index < 0) {
1152                 if (DEBUG_SPEW) {
1153                     Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1154                             + " [not found], flags=0x" + Integer.toHexString(flags));
1155                 }
1156                 return;
1157             }
1158 
1159             WakeLock wakeLock = mWakeLocks.get(index);
1160             if (DEBUG_SPEW) {
1161                 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1162                         + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1163             }
1164 
1165             if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
1166                 mRequestWaitForNegativeProximity = true;
1167             }
1168 
1169             wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1170             removeWakeLockLocked(wakeLock, index);
1171         }
1172     }
1173 
handleWakeLockDeath(WakeLock wakeLock)1174     private void handleWakeLockDeath(WakeLock wakeLock) {
1175         synchronized (mLock) {
1176             if (DEBUG_SPEW) {
1177                 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1178                         + " [" + wakeLock.mTag + "]");
1179             }
1180 
1181             int index = mWakeLocks.indexOf(wakeLock);
1182             if (index < 0) {
1183                 return;
1184             }
1185 
1186             removeWakeLockLocked(wakeLock, index);
1187         }
1188     }
1189 
removeWakeLockLocked(WakeLock wakeLock, int index)1190     private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1191         mWakeLocks.remove(index);
1192         UidState state = wakeLock.mUidState;
1193         state.mNumWakeLocks--;
1194         if (state.mNumWakeLocks <= 0 &&
1195                 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1196             mUidState.remove(state.mUid);
1197         }
1198         notifyWakeLockReleasedLocked(wakeLock);
1199 
1200         applyWakeLockFlagsOnReleaseLocked(wakeLock);
1201         mDirty |= DIRTY_WAKE_LOCKS;
1202         updatePowerStateLocked();
1203     }
1204 
applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock)1205     private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
1206         if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1207                 && isScreenLock(wakeLock)) {
1208             userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1209                     PowerManager.USER_ACTIVITY_EVENT_OTHER,
1210                     PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1211                     wakeLock.mOwnerUid);
1212         }
1213     }
1214 
updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag, int callingUid)1215     private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1216             int callingUid) {
1217         synchronized (mLock) {
1218             int index = findWakeLockIndexLocked(lock);
1219             if (index < 0) {
1220                 if (DEBUG_SPEW) {
1221                     Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1222                             + " [not found], ws=" + ws);
1223                 }
1224                 throw new IllegalArgumentException("Wake lock not active: " + lock
1225                         + " from uid " + callingUid);
1226             }
1227 
1228             WakeLock wakeLock = mWakeLocks.get(index);
1229             if (DEBUG_SPEW) {
1230                 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1231                         + " [" + wakeLock.mTag + "], ws=" + ws);
1232             }
1233 
1234             if (!wakeLock.hasSameWorkSource(ws)) {
1235                 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1236                         wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1237                         ws, historyTag);
1238                 wakeLock.mHistoryTag = historyTag;
1239                 wakeLock.updateWorkSource(ws);
1240             }
1241         }
1242     }
1243 
findWakeLockIndexLocked(IBinder lock)1244     private int findWakeLockIndexLocked(IBinder lock) {
1245         final int count = mWakeLocks.size();
1246         for (int i = 0; i < count; i++) {
1247             if (mWakeLocks.get(i).mLock == lock) {
1248                 return i;
1249             }
1250         }
1251         return -1;
1252     }
1253 
notifyWakeLockAcquiredLocked(WakeLock wakeLock)1254     private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
1255         if (mSystemReady && !wakeLock.mDisabled) {
1256             wakeLock.mNotifiedAcquired = true;
1257             mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1258                     wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1259                     wakeLock.mHistoryTag);
1260             restartNofifyLongTimerLocked(wakeLock);
1261         }
1262     }
1263 
enqueueNotifyLongMsgLocked(long time)1264     private void enqueueNotifyLongMsgLocked(long time) {
1265         mNotifyLongScheduled = time;
1266         Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1267         msg.setAsynchronous(true);
1268         mHandler.sendMessageAtTime(msg, time);
1269     }
1270 
restartNofifyLongTimerLocked(WakeLock wakeLock)1271     private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1272         wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1273         if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1274                 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1275             enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1276         }
1277     }
1278 
notifyWakeLockLongStartedLocked(WakeLock wakeLock)1279     private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1280         if (mSystemReady && !wakeLock.mDisabled) {
1281             wakeLock.mNotifiedLong = true;
1282             mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1283                     wakeLock.mWorkSource, wakeLock.mHistoryTag);
1284         }
1285     }
1286 
notifyWakeLockLongFinishedLocked(WakeLock wakeLock)1287     private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1288         if (wakeLock.mNotifiedLong) {
1289             wakeLock.mNotifiedLong = false;
1290             mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1291                     wakeLock.mWorkSource, wakeLock.mHistoryTag);
1292         }
1293     }
1294 
notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag, String packageName, int uid, int pid, WorkSource ws, String historyTag)1295     private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1296             String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1297         if (mSystemReady && wakeLock.mNotifiedAcquired) {
1298             mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1299                     wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1300                     wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
1301             notifyWakeLockLongFinishedLocked(wakeLock);
1302             // Changing the wake lock will count as releasing the old wake lock(s) and
1303             // acquiring the new ones...  we do this because otherwise once a wakelock
1304             // becomes long, if we just continued to treat it as long we can get in to
1305             // situations where we spam battery stats with every following change to it.
1306             restartNofifyLongTimerLocked(wakeLock);
1307         }
1308     }
1309 
notifyWakeLockReleasedLocked(WakeLock wakeLock)1310     private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
1311         if (mSystemReady && wakeLock.mNotifiedAcquired) {
1312             wakeLock.mNotifiedAcquired = false;
1313             wakeLock.mAcquireTime = 0;
1314             mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1315                     wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1316                     wakeLock.mWorkSource, wakeLock.mHistoryTag);
1317             notifyWakeLockLongFinishedLocked(wakeLock);
1318         }
1319     }
1320 
1321     @SuppressWarnings("deprecation")
isWakeLockLevelSupportedInternal(int level)1322     private boolean isWakeLockLevelSupportedInternal(int level) {
1323         synchronized (mLock) {
1324             switch (level) {
1325                 case PowerManager.PARTIAL_WAKE_LOCK:
1326                 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1327                 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1328                 case PowerManager.FULL_WAKE_LOCK:
1329                 case PowerManager.DOZE_WAKE_LOCK:
1330                 case PowerManager.DRAW_WAKE_LOCK:
1331                     return true;
1332 
1333                 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1334                     return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
1335 
1336                 default:
1337                     return false;
1338             }
1339         }
1340     }
1341 
1342     // Called from native code.
userActivityFromNative(long eventTime, int event, int flags)1343     private void userActivityFromNative(long eventTime, int event, int flags) {
1344         userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1345     }
1346 
userActivityInternal(long eventTime, int event, int flags, int uid)1347     private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1348         synchronized (mLock) {
1349             if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1350                 updatePowerStateLocked();
1351             }
1352         }
1353     }
1354 
onUserAttention()1355     private void onUserAttention() {
1356         synchronized (mLock) {
1357             if (userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1358                     PowerManager.USER_ACTIVITY_EVENT_ATTENTION, 0 /* flags */,
1359                     Process.SYSTEM_UID)) {
1360                 updatePowerStateLocked();
1361             }
1362         }
1363     }
1364 
userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid)1365     private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1366         if (DEBUG_SPEW) {
1367             Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1368                     + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1369                     + ", uid=" + uid);
1370         }
1371 
1372         if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
1373                 || !mBootCompleted || !mSystemReady) {
1374             return false;
1375         }
1376 
1377         Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1378         try {
1379             if (eventTime > mLastInteractivePowerHintTime) {
1380                 powerHintInternal(PowerHint.INTERACTION, 0);
1381                 mLastInteractivePowerHintTime = eventTime;
1382             }
1383 
1384             mNotifier.onUserActivity(event, uid);
1385             mAttentionDetector.onUserActivity(eventTime, event);
1386 
1387             if (mUserInactiveOverrideFromWindowManager) {
1388                 mUserInactiveOverrideFromWindowManager = false;
1389                 mOverriddenTimeout = -1;
1390             }
1391 
1392             if (mWakefulness == WAKEFULNESS_ASLEEP
1393                     || mWakefulness == WAKEFULNESS_DOZING
1394                     || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1395                 return false;
1396             }
1397 
1398             maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1399 
1400             if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1401                 if (eventTime > mLastUserActivityTimeNoChangeLights
1402                         && eventTime > mLastUserActivityTime) {
1403                     mLastUserActivityTimeNoChangeLights = eventTime;
1404                     mDirty |= DIRTY_USER_ACTIVITY;
1405                     if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1406                         mDirty |= DIRTY_QUIESCENT;
1407                     }
1408 
1409                     return true;
1410                 }
1411             } else {
1412                 if (eventTime > mLastUserActivityTime) {
1413                     mLastUserActivityTime = eventTime;
1414                     mDirty |= DIRTY_USER_ACTIVITY;
1415                     if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1416                         mDirty |= DIRTY_QUIESCENT;
1417                     }
1418                     return true;
1419                 }
1420             }
1421         } finally {
1422             Trace.traceEnd(Trace.TRACE_TAG_POWER);
1423         }
1424         return false;
1425     }
1426 
maybeUpdateForegroundProfileLastActivityLocked(long eventTime)1427     private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1428         final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1429         if (profile != null && eventTime > profile.mLastUserActivityTime) {
1430             profile.mLastUserActivityTime = eventTime;
1431         }
1432     }
1433 
wakeUpInternal(long eventTime, @WakeReason int reason, String details, int uid, String opPackageName, int opUid)1434     private void wakeUpInternal(long eventTime, @WakeReason int reason, String details, int uid,
1435             String opPackageName, int opUid) {
1436         synchronized (mLock) {
1437             if (wakeUpNoUpdateLocked(eventTime, reason, details, uid, opPackageName, opUid)) {
1438                 updatePowerStateLocked();
1439             }
1440         }
1441     }
1442 
wakeUpNoUpdateLocked(long eventTime, @WakeReason int reason, String details, int reasonUid, String opPackageName, int opUid)1443     private boolean wakeUpNoUpdateLocked(long eventTime, @WakeReason int reason, String details,
1444             int reasonUid, String opPackageName, int opUid) {
1445         if (DEBUG_SPEW) {
1446             Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
1447         }
1448 
1449         if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
1450                 || !mBootCompleted || !mSystemReady || mForceSuspendActive) {
1451             return false;
1452         }
1453 
1454         Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1455 
1456         Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1457         try {
1458             Slog.i(TAG, "Waking up from "
1459                     + PowerManagerInternal.wakefulnessToString(mWakefulness)
1460                     + " (uid=" + reasonUid
1461                     + ", reason=" + PowerManager.wakeReasonToString(reason)
1462                     + ", details=" + details
1463                     + ")...");
1464 
1465             mLastWakeTime = eventTime;
1466             mLastWakeReason = reason;
1467             setWakefulnessLocked(WAKEFULNESS_AWAKE, reason, eventTime);
1468 
1469             mNotifier.onWakeUp(reason, details, reasonUid, opPackageName, opUid);
1470             userActivityNoUpdateLocked(
1471                     eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
1472         } finally {
1473             Trace.traceEnd(Trace.TRACE_TAG_POWER);
1474         }
1475         return true;
1476     }
1477 
goToSleepInternal(long eventTime, int reason, int flags, int uid)1478     private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
1479         synchronized (mLock) {
1480             if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
1481                 updatePowerStateLocked();
1482             }
1483         }
1484     }
1485 
1486     /**
1487      * Puts the system in doze.
1488      *
1489      * This method is called goToSleep for historical reasons but actually attempts to DOZE,
1490      * and only tucks itself in to SLEEP if requested with the flag
1491      * {@link PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE}.
1492      */
1493     @SuppressWarnings("deprecation")
goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid)1494     private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
1495         if (DEBUG_SPEW) {
1496             Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
1497                     + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
1498         }
1499 
1500         if (eventTime < mLastWakeTime
1501                 || mWakefulness == WAKEFULNESS_ASLEEP
1502                 || mWakefulness == WAKEFULNESS_DOZING
1503                 || !mBootCompleted || !mSystemReady) {
1504             return false;
1505         }
1506 
1507         Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1508         try {
1509             reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX,
1510                     Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN));
1511             Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
1512                     + " (uid " + uid + ")...");
1513 
1514             mLastSleepTime = eventTime;
1515             mLastSleepReason = reason;
1516             mSandmanSummoned = true;
1517             setWakefulnessLocked(WAKEFULNESS_DOZING, reason, eventTime);
1518 
1519             // Report the number of wake locks that will be cleared by going to sleep.
1520             int numWakeLocksCleared = 0;
1521             final int numWakeLocks = mWakeLocks.size();
1522             for (int i = 0; i < numWakeLocks; i++) {
1523                 final WakeLock wakeLock = mWakeLocks.get(i);
1524                 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1525                     case PowerManager.FULL_WAKE_LOCK:
1526                     case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1527                     case PowerManager.SCREEN_DIM_WAKE_LOCK:
1528                         numWakeLocksCleared += 1;
1529                         break;
1530                 }
1531             }
1532             EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
1533 
1534             // Skip dozing if requested.
1535             if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1536                 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1537             }
1538         } finally {
1539             Trace.traceEnd(Trace.TRACE_TAG_POWER);
1540         }
1541         return true;
1542     }
1543 
napInternal(long eventTime, int uid)1544     private void napInternal(long eventTime, int uid) {
1545         synchronized (mLock) {
1546             if (napNoUpdateLocked(eventTime, uid)) {
1547                 updatePowerStateLocked();
1548             }
1549         }
1550     }
1551 
napNoUpdateLocked(long eventTime, int uid)1552     private boolean napNoUpdateLocked(long eventTime, int uid) {
1553         if (DEBUG_SPEW) {
1554             Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
1555         }
1556 
1557         if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1558                 || !mBootCompleted || !mSystemReady) {
1559             return false;
1560         }
1561 
1562         Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1563         try {
1564             Slog.i(TAG, "Nap time (uid " + uid +")...");
1565 
1566             mSandmanSummoned = true;
1567             setWakefulnessLocked(WAKEFULNESS_DREAMING, 0, eventTime);
1568         } finally {
1569             Trace.traceEnd(Trace.TRACE_TAG_POWER);
1570         }
1571         return true;
1572     }
1573 
1574     // Done dozing, drop everything and go to sleep.
reallyGoToSleepNoUpdateLocked(long eventTime, int uid)1575     private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
1576         if (DEBUG_SPEW) {
1577             Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1578                     + ", uid=" + uid);
1579         }
1580 
1581         if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1582                 || !mBootCompleted || !mSystemReady) {
1583             return false;
1584         }
1585 
1586         Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1587         try {
1588             Slog.i(TAG, "Sleeping (uid " + uid +")...");
1589 
1590             setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
1591                     eventTime);
1592         } finally {
1593             Trace.traceEnd(Trace.TRACE_TAG_POWER);
1594         }
1595         return true;
1596     }
1597 
1598     @VisibleForTesting
setWakefulnessLocked(int wakefulness, int reason, long eventTime)1599     void setWakefulnessLocked(int wakefulness, int reason, long eventTime) {
1600         if (mWakefulness != wakefulness) {
1601             mWakefulness = wakefulness;
1602             mWakefulnessChanging = true;
1603             mDirty |= DIRTY_WAKEFULNESS;
1604             if (mNotifier != null) {
1605                 mNotifier.onWakefulnessChangeStarted(wakefulness, reason, eventTime);
1606             }
1607             mAttentionDetector.onWakefulnessChangeStarted(wakefulness);
1608         }
1609     }
1610 
1611     @VisibleForTesting
getWakefulness()1612     int getWakefulness() {
1613         return mWakefulness;
1614     }
1615 
1616     /**
1617      * Logs the time the device would have spent awake before user activity timeout,
1618      * had the system not been told the user was inactive.
1619      */
logSleepTimeoutRecapturedLocked()1620     private void logSleepTimeoutRecapturedLocked() {
1621         final long now = SystemClock.uptimeMillis();
1622         final long savedWakeTimeMs = mOverriddenTimeout - now;
1623         if (savedWakeTimeMs >= 0) {
1624             EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
1625             mOverriddenTimeout = -1;
1626         }
1627     }
1628 
finishWakefulnessChangeIfNeededLocked()1629     private void finishWakefulnessChangeIfNeededLocked() {
1630         if (mWakefulnessChanging && mDisplayReady) {
1631             if (mWakefulness == WAKEFULNESS_DOZING
1632                     && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1633                 return; // wait until dream has enabled dozing
1634             }
1635             if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1636                 logSleepTimeoutRecapturedLocked();
1637             }
1638             if (mWakefulness == WAKEFULNESS_AWAKE) {
1639                 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1640                 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1641                 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1642                     Slog.w(TAG, "Screen on took " + latencyMs + " ms");
1643                 }
1644             }
1645             mWakefulnessChanging = false;
1646             mNotifier.onWakefulnessChangeFinished();
1647         }
1648     }
1649 
1650     /**
1651      * Updates the global power state based on dirty bits recorded in mDirty.
1652      *
1653      * This is the main function that performs power state transitions.
1654      * We centralize them here so that we can recompute the power state completely
1655      * each time something important changes, and ensure that we do it the same
1656      * way each time.  The point is to gather all of the transition logic here.
1657      */
updatePowerStateLocked()1658     private void updatePowerStateLocked() {
1659         if (!mSystemReady || mDirty == 0) {
1660             return;
1661         }
1662         if (!Thread.holdsLock(mLock)) {
1663             Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1664         }
1665 
1666         Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1667         try {
1668             // Phase 0: Basic state updates.
1669             updateIsPoweredLocked(mDirty);
1670             updateStayOnLocked(mDirty);
1671             updateScreenBrightnessBoostLocked(mDirty);
1672 
1673             // Phase 1: Update wakefulness.
1674             // Loop because the wake lock and user activity computations are influenced
1675             // by changes in wakefulness.
1676             final long now = SystemClock.uptimeMillis();
1677             int dirtyPhase2 = 0;
1678             for (;;) {
1679                 int dirtyPhase1 = mDirty;
1680                 dirtyPhase2 |= dirtyPhase1;
1681                 mDirty = 0;
1682 
1683                 updateWakeLockSummaryLocked(dirtyPhase1);
1684                 updateUserActivitySummaryLocked(now, dirtyPhase1);
1685                 if (!updateWakefulnessLocked(dirtyPhase1)) {
1686                     break;
1687                 }
1688             }
1689 
1690             // Phase 2: Lock profiles that became inactive/not kept awake.
1691             updateProfilesLocked(now);
1692 
1693             // Phase 3: Update display power state.
1694             final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1695 
1696             // Phase 4: Update dream state (depends on display ready signal).
1697             updateDreamLocked(dirtyPhase2, displayBecameReady);
1698 
1699             // Phase 5: Send notifications, if needed.
1700             finishWakefulnessChangeIfNeededLocked();
1701 
1702             // Phase 6: Update suspend blocker.
1703             // Because we might release the last suspend blocker here, we need to make sure
1704             // we finished everything else first!
1705             updateSuspendBlockerLocked();
1706         } finally {
1707             Trace.traceEnd(Trace.TRACE_TAG_POWER);
1708         }
1709     }
1710 
1711     /**
1712      * Check profile timeouts and notify profiles that should be locked.
1713      */
updateProfilesLocked(long now)1714     private void updateProfilesLocked(long now) {
1715         final int numProfiles = mProfilePowerState.size();
1716         for (int i = 0; i < numProfiles; i++) {
1717             final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1718             if (isProfileBeingKeptAwakeLocked(profile, now)) {
1719                 profile.mLockingNotified = false;
1720             } else if (!profile.mLockingNotified) {
1721                 profile.mLockingNotified = true;
1722                 mNotifier.onProfileTimeout(profile.mUserId);
1723             }
1724         }
1725     }
1726 
isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now)1727     private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1728         return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1729                 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1730                 || (mProximityPositive &&
1731                     (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1732     }
1733 
1734     /**
1735      * Updates the value of mIsPowered.
1736      * Sets DIRTY_IS_POWERED if a change occurred.
1737      */
updateIsPoweredLocked(int dirty)1738     private void updateIsPoweredLocked(int dirty) {
1739         if ((dirty & DIRTY_BATTERY_STATE) != 0) {
1740             final boolean wasPowered = mIsPowered;
1741             final int oldPlugType = mPlugType;
1742             final boolean oldLevelLow = mBatteryLevelLow;
1743             mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1744             mPlugType = mBatteryManagerInternal.getPlugType();
1745             mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1746             mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
1747 
1748             if (DEBUG_SPEW) {
1749                 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
1750                         + ", mIsPowered=" + mIsPowered
1751                         + ", oldPlugType=" + oldPlugType
1752                         + ", mPlugType=" + mPlugType
1753                         + ", mBatteryLevel=" + mBatteryLevel);
1754             }
1755 
1756             if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
1757                 mDirty |= DIRTY_IS_POWERED;
1758 
1759                 // Update wireless dock detection state.
1760                 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1761                         mIsPowered, mPlugType);
1762 
1763                 // Treat plugging and unplugging the devices as a user activity.
1764                 // Users find it disconcerting when they plug or unplug the device
1765                 // and it shuts off right away.
1766                 // Some devices also wake the device when plugged or unplugged because
1767                 // they don't have a charging LED.
1768                 final long now = SystemClock.uptimeMillis();
1769                 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1770                         dockedOnWirelessCharger)) {
1771                     wakeUpNoUpdateLocked(now, PowerManager.WAKE_REASON_PLUGGED_IN,
1772                             "android.server.power:PLUGGED:" + mIsPowered, Process.SYSTEM_UID,
1773                             mContext.getOpPackageName(), Process.SYSTEM_UID);
1774                 }
1775                 userActivityNoUpdateLocked(
1776                         now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1777 
1778                 // only play charging sounds if boot is completed so charging sounds don't play
1779                 // with potential notification sounds
1780                 if (mBootCompleted) {
1781                     if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
1782                             && BatteryManager.isPlugWired(mPlugType)) {
1783                         mNotifier.onWiredChargingStarted(mForegroundProfile);
1784                     } else if (dockedOnWirelessCharger) {
1785                         mNotifier.onWirelessChargingStarted(mBatteryLevel, mForegroundProfile);
1786                     }
1787                 }
1788             }
1789 
1790             mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
1791         }
1792     }
1793 
shouldWakeUpWhenPluggedOrUnpluggedLocked( boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger)1794     private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1795             boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
1796         // Don't wake when powered unless configured to do so.
1797         if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1798             return false;
1799         }
1800 
1801         // Don't wake when undocked from wireless charger.
1802         // See WirelessChargerDetector for justification.
1803         if (wasPowered && !mIsPowered
1804                 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1805             return false;
1806         }
1807 
1808         // Don't wake when docked on wireless charger unless we are certain of it.
1809         // See WirelessChargerDetector for justification.
1810         if (!wasPowered && mIsPowered
1811                 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
1812                 && !dockedOnWirelessCharger) {
1813             return false;
1814         }
1815 
1816         // If already dreaming and becoming powered, then don't wake.
1817         if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
1818             return false;
1819         }
1820 
1821         // Don't wake while theater mode is enabled.
1822         if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1823             return false;
1824         }
1825 
1826         // On Always On Display, SystemUI shows the charging indicator
1827         if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
1828             return false;
1829         }
1830 
1831         // Otherwise wake up!
1832         return true;
1833     }
1834 
1835     /**
1836      * Updates the value of mStayOn.
1837      * Sets DIRTY_STAY_ON if a change occurred.
1838      */
updateStayOnLocked(int dirty)1839     private void updateStayOnLocked(int dirty) {
1840         if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
1841             final boolean wasStayOn = mStayOn;
1842             if (mStayOnWhilePluggedInSetting != 0
1843                     && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1844                 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
1845             } else {
1846                 mStayOn = false;
1847             }
1848 
1849             if (mStayOn != wasStayOn) {
1850                 mDirty |= DIRTY_STAY_ON;
1851             }
1852         }
1853     }
1854 
1855     /**
1856      * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1857      * Note that most wake-locks are ignored when the system is asleep.
1858      *
1859      * This function must have no other side-effects.
1860      */
1861     @SuppressWarnings("deprecation")
updateWakeLockSummaryLocked(int dirty)1862     private void updateWakeLockSummaryLocked(int dirty) {
1863         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1864             mWakeLockSummary = 0;
1865 
1866             final int numProfiles = mProfilePowerState.size();
1867             for (int i = 0; i < numProfiles; i++) {
1868                 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
1869             }
1870 
1871             final int numWakeLocks = mWakeLocks.size();
1872             for (int i = 0; i < numWakeLocks; i++) {
1873                 final WakeLock wakeLock = mWakeLocks.get(i);
1874                 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
1875                 mWakeLockSummary |= wakeLockFlags;
1876                 for (int j = 0; j < numProfiles; j++) {
1877                     final ProfilePowerState profile = mProfilePowerState.valueAt(j);
1878                     if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
1879                         profile.mWakeLockSummary |= wakeLockFlags;
1880                     }
1881                 }
1882             }
1883 
1884             mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
1885             for (int i = 0; i < numProfiles; i++) {
1886                 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1887                 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
1888             }
1889 
1890             if (DEBUG_SPEW) {
1891                 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
1892                         + PowerManagerInternal.wakefulnessToString(mWakefulness)
1893                         + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1894             }
1895         }
1896     }
1897 
adjustWakeLockSummaryLocked(int wakeLockSummary)1898     private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
1899         // Cancel wake locks that make no sense based on the current state.
1900         if (mWakefulness != WAKEFULNESS_DOZING) {
1901             wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
1902         }
1903         if (mWakefulness == WAKEFULNESS_ASLEEP
1904                 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1905             wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1906                     | WAKE_LOCK_BUTTON_BRIGHT);
1907             if (mWakefulness == WAKEFULNESS_ASLEEP) {
1908                 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1909             }
1910         }
1911 
1912         // Infer implied wake locks where necessary based on the current state.
1913         if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1914             if (mWakefulness == WAKEFULNESS_AWAKE) {
1915                 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1916             } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1917                 wakeLockSummary |= WAKE_LOCK_CPU;
1918             }
1919         }
1920         if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1921             wakeLockSummary |= WAKE_LOCK_CPU;
1922         }
1923 
1924         return wakeLockSummary;
1925     }
1926 
1927     /** Get wake lock summary flags that correspond to the given wake lock. */
getWakeLockSummaryFlags(WakeLock wakeLock)1928     private int getWakeLockSummaryFlags(WakeLock wakeLock) {
1929         switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1930             case PowerManager.PARTIAL_WAKE_LOCK:
1931                 if (!wakeLock.mDisabled) {
1932                     // We only respect this if the wake lock is not disabled.
1933                     return WAKE_LOCK_CPU;
1934                 }
1935                 break;
1936             case PowerManager.FULL_WAKE_LOCK:
1937                 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1938             case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1939                 return WAKE_LOCK_SCREEN_BRIGHT;
1940             case PowerManager.SCREEN_DIM_WAKE_LOCK:
1941                 return WAKE_LOCK_SCREEN_DIM;
1942             case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1943                 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1944             case PowerManager.DOZE_WAKE_LOCK:
1945                 return WAKE_LOCK_DOZE;
1946             case PowerManager.DRAW_WAKE_LOCK:
1947                 return WAKE_LOCK_DRAW;
1948         }
1949         return 0;
1950     }
1951 
wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId)1952     private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
1953         if (wakeLock.mWorkSource != null) {
1954             for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
1955                 final int uid = wakeLock.mWorkSource.get(k);
1956                 if (userId == UserHandle.getUserId(uid)) {
1957                     return true;
1958                 }
1959             }
1960 
1961             final ArrayList<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
1962             if (workChains != null) {
1963                 for (int k = 0; k < workChains.size(); k++) {
1964                     final int uid = workChains.get(k).getAttributionUid();
1965                     if (userId == UserHandle.getUserId(uid)) {
1966                         return true;
1967                     }
1968                 }
1969             }
1970         }
1971         return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
1972     }
1973 
checkForLongWakeLocks()1974     void checkForLongWakeLocks() {
1975         synchronized (mLock) {
1976             final long now = SystemClock.uptimeMillis();
1977             mNotifyLongDispatched = now;
1978             final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
1979             long nextCheckTime = Long.MAX_VALUE;
1980             final int numWakeLocks = mWakeLocks.size();
1981             for (int i = 0; i < numWakeLocks; i++) {
1982                 final WakeLock wakeLock = mWakeLocks.get(i);
1983                 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1984                         == PowerManager.PARTIAL_WAKE_LOCK) {
1985                     if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
1986                         if (wakeLock.mAcquireTime < when) {
1987                             // This wake lock has exceeded the long acquire time, report!
1988                             notifyWakeLockLongStartedLocked(wakeLock);
1989                         } else {
1990                             // This wake lock could still become a long one, at this time.
1991                             long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
1992                             if (checkTime < nextCheckTime) {
1993                                 nextCheckTime = checkTime;
1994                             }
1995                         }
1996                     }
1997                 }
1998             }
1999             mNotifyLongScheduled = 0;
2000             mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
2001             if (nextCheckTime != Long.MAX_VALUE) {
2002                 mNotifyLongNextCheck = nextCheckTime;
2003                 enqueueNotifyLongMsgLocked(nextCheckTime);
2004             } else {
2005                 mNotifyLongNextCheck = 0;
2006             }
2007         }
2008     }
2009 
2010     /**
2011      * Updates the value of mUserActivitySummary to summarize the user requested
2012      * state of the system such as whether the screen should be bright or dim.
2013      * Note that user activity is ignored when the system is asleep.
2014      *
2015      * This function must have no other side-effects.
2016      */
updateUserActivitySummaryLocked(long now, int dirty)2017     private void updateUserActivitySummaryLocked(long now, int dirty) {
2018         // Update the status of the user activity timeout timer.
2019         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
2020                 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
2021             mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
2022 
2023             long nextTimeout = 0;
2024             if (mWakefulness == WAKEFULNESS_AWAKE
2025                     || mWakefulness == WAKEFULNESS_DREAMING
2026                     || mWakefulness == WAKEFULNESS_DOZING) {
2027                 final long sleepTimeout = getSleepTimeoutLocked();
2028                 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
2029                 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
2030                 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
2031                 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
2032 
2033                 mUserActivitySummary = 0;
2034                 if (mLastUserActivityTime >= mLastWakeTime) {
2035                     nextTimeout = mLastUserActivityTime
2036                             + screenOffTimeout - screenDimDuration;
2037                     if (now < nextTimeout) {
2038                         mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2039                     } else {
2040                         nextTimeout = mLastUserActivityTime + screenOffTimeout;
2041                         if (now < nextTimeout) {
2042                             mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2043                         }
2044                     }
2045                 }
2046                 if (mUserActivitySummary == 0
2047                         && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
2048                     nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
2049                     if (now < nextTimeout) {
2050                         if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
2051                                 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
2052                             mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2053                         } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
2054                             mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2055                         }
2056                     }
2057                 }
2058 
2059                 if (mUserActivitySummary == 0) {
2060                     if (sleepTimeout >= 0) {
2061                         final long anyUserActivity = Math.max(mLastUserActivityTime,
2062                                 mLastUserActivityTimeNoChangeLights);
2063                         if (anyUserActivity >= mLastWakeTime) {
2064                             nextTimeout = anyUserActivity + sleepTimeout;
2065                             if (now < nextTimeout) {
2066                                 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2067                             }
2068                         }
2069                     } else {
2070                         mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2071                         nextTimeout = -1;
2072                     }
2073                 }
2074 
2075                 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
2076                     if ((mUserActivitySummary &
2077                             (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
2078                         // Device is being kept awake by recent user activity
2079                         if (nextTimeout >= now && mOverriddenTimeout == -1) {
2080                             // Save when the next timeout would have occurred
2081                             mOverriddenTimeout = nextTimeout;
2082                         }
2083                     }
2084                     mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2085                     nextTimeout = -1;
2086                 }
2087 
2088                 if ((mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
2089                         && (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) == 0) {
2090                     nextTimeout = mAttentionDetector.updateUserActivity(nextTimeout);
2091                 }
2092 
2093                 if (nextProfileTimeout > 0) {
2094                     nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2095                 }
2096 
2097                 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
2098                     scheduleUserInactivityTimeout(nextTimeout);
2099                 }
2100             } else {
2101                 mUserActivitySummary = 0;
2102             }
2103 
2104             if (DEBUG_SPEW) {
2105                 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
2106                         + PowerManagerInternal.wakefulnessToString(mWakefulness)
2107                         + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2108                         + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2109             }
2110         }
2111     }
2112 
scheduleUserInactivityTimeout(long timeMs)2113     private void scheduleUserInactivityTimeout(long timeMs) {
2114         final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2115         msg.setAsynchronous(true);
2116         mHandler.sendMessageAtTime(msg, timeMs);
2117     }
2118 
2119     /**
2120      * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2121      */
getNextProfileTimeoutLocked(long now)2122     private long getNextProfileTimeoutLocked(long now) {
2123         long nextTimeout = -1;
2124         final int numProfiles = mProfilePowerState.size();
2125         for (int i = 0; i < numProfiles; i++) {
2126             final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2127             final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2128             if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2129                 nextTimeout = timeout;
2130             }
2131         }
2132         return nextTimeout;
2133     }
2134 
2135     /**
2136      * Called when a user activity timeout has occurred.
2137      * Simply indicates that something about user activity has changed so that the new
2138      * state can be recomputed when the power state is updated.
2139      *
2140      * This function must have no other side-effects besides setting the dirty
2141      * bit and calling update power state.  Wakefulness transitions are handled elsewhere.
2142      */
handleUserActivityTimeout()2143     private void handleUserActivityTimeout() { // runs on handler thread
2144         synchronized (mLock) {
2145             if (DEBUG_SPEW) {
2146                 Slog.d(TAG, "handleUserActivityTimeout");
2147             }
2148 
2149             mDirty |= DIRTY_USER_ACTIVITY;
2150             updatePowerStateLocked();
2151         }
2152     }
2153 
getSleepTimeoutLocked()2154     private long getSleepTimeoutLocked() {
2155         final long timeout = mSleepTimeoutSetting;
2156         if (timeout <= 0) {
2157             return -1;
2158         }
2159         return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2160     }
2161 
getScreenOffTimeoutLocked(long sleepTimeout)2162     private long getScreenOffTimeoutLocked(long sleepTimeout) {
2163         long timeout = mScreenOffTimeoutSetting;
2164         if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2165             timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2166         }
2167         if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
2168             timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
2169         }
2170         if (sleepTimeout >= 0) {
2171             timeout = Math.min(timeout, sleepTimeout);
2172         }
2173         return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2174     }
2175 
getScreenDimDurationLocked(long screenOffTimeout)2176     private long getScreenDimDurationLocked(long screenOffTimeout) {
2177         return Math.min(mMaximumScreenDimDurationConfig,
2178                 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
2179     }
2180 
2181     /**
2182      * Updates the wakefulness of the device.
2183      *
2184      * This is the function that decides whether the device should start dreaming
2185      * based on the current wake locks and user activity state.  It may modify mDirty
2186      * if the wakefulness changes.
2187      *
2188      * Returns true if the wakefulness changed and we need to restart power state calculation.
2189      */
updateWakefulnessLocked(int dirty)2190     private boolean updateWakefulnessLocked(int dirty) {
2191         boolean changed = false;
2192         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
2193                 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
2194                 | DIRTY_DOCK_STATE)) != 0) {
2195             if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2196                 if (DEBUG_SPEW) {
2197                     Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
2198                 }
2199                 final long time = SystemClock.uptimeMillis();
2200                 if (shouldNapAtBedTimeLocked()) {
2201                     changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
2202                 } else {
2203                     changed = goToSleepNoUpdateLocked(time,
2204                             PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
2205                 }
2206             }
2207         }
2208         return changed;
2209     }
2210 
2211     /**
2212      * Returns true if the device should automatically nap and start dreaming when the user
2213      * activity timeout has expired and it's bedtime.
2214      */
shouldNapAtBedTimeLocked()2215     private boolean shouldNapAtBedTimeLocked() {
2216         return mDreamsActivateOnSleepSetting
2217                 || (mDreamsActivateOnDockSetting
2218                         && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2219     }
2220 
2221     /**
2222      * Returns true if the device should go to sleep now.
2223      * Also used when exiting a dream to determine whether we should go back
2224      * to being fully awake or else go to sleep for good.
2225      */
isItBedTimeYetLocked()2226     private boolean isItBedTimeYetLocked() {
2227         return mBootCompleted && !isBeingKeptAwakeLocked();
2228     }
2229 
2230     /**
2231      * Returns true if the device is being kept awake by a wake lock, user activity
2232      * or the stay on while powered setting.  We also keep the phone awake when
2233      * the proximity sensor returns a positive result so that the device does not
2234      * lock while in a phone call.  This function only controls whether the device
2235      * will go to sleep or dream which is independent of whether it will be allowed
2236      * to suspend.
2237      */
isBeingKeptAwakeLocked()2238     private boolean isBeingKeptAwakeLocked() {
2239         return mStayOn
2240                 || mProximityPositive
2241                 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
2242                 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2243                         | USER_ACTIVITY_SCREEN_DIM)) != 0
2244                 || mScreenBrightnessBoostInProgress;
2245     }
2246 
2247     /**
2248      * Determines whether to post a message to the sandman to update the dream state.
2249      */
updateDreamLocked(int dirty, boolean displayBecameReady)2250     private void updateDreamLocked(int dirty, boolean displayBecameReady) {
2251         if ((dirty & (DIRTY_WAKEFULNESS
2252                 | DIRTY_USER_ACTIVITY
2253                 | DIRTY_WAKE_LOCKS
2254                 | DIRTY_BOOT_COMPLETED
2255                 | DIRTY_SETTINGS
2256                 | DIRTY_IS_POWERED
2257                 | DIRTY_STAY_ON
2258                 | DIRTY_PROXIMITY_POSITIVE
2259                 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2260             if (mDisplayReady) {
2261                 scheduleSandmanLocked();
2262             }
2263         }
2264     }
2265 
scheduleSandmanLocked()2266     private void scheduleSandmanLocked() {
2267         if (!mSandmanScheduled) {
2268             mSandmanScheduled = true;
2269             Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2270             msg.setAsynchronous(true);
2271             mHandler.sendMessage(msg);
2272         }
2273     }
2274 
2275     /**
2276      * Called when the device enters or exits a dreaming or dozing state.
2277      *
2278      * We do this asynchronously because we must call out of the power manager to start
2279      * the dream and we don't want to hold our lock while doing so.  There is a risk that
2280      * the device will wake or go to sleep in the meantime so we have to handle that case.
2281      */
handleSandman()2282     private void handleSandman() { // runs on handler thread
2283         // Handle preconditions.
2284         final boolean startDreaming;
2285         final int wakefulness;
2286         synchronized (mLock) {
2287             mSandmanScheduled = false;
2288             wakefulness = mWakefulness;
2289             if (mSandmanSummoned && mDisplayReady) {
2290                 startDreaming = canDreamLocked() || canDozeLocked();
2291                 mSandmanSummoned = false;
2292             } else {
2293                 startDreaming = false;
2294             }
2295         }
2296 
2297         // Start dreaming if needed.
2298         // We only control the dream on the handler thread, so we don't need to worry about
2299         // concurrent attempts to start or stop the dream.
2300         final boolean isDreaming;
2301         if (mDreamManager != null) {
2302             // Restart the dream whenever the sandman is summoned.
2303             if (startDreaming) {
2304                 mDreamManager.stopDream(false /*immediate*/);
2305                 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
2306             }
2307             isDreaming = mDreamManager.isDreaming();
2308         } else {
2309             isDreaming = false;
2310         }
2311 
2312         // Update dream state.
2313         synchronized (mLock) {
2314             // Remember the initial battery level when the dream started.
2315             if (startDreaming && isDreaming) {
2316                 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2317                 if (wakefulness == WAKEFULNESS_DOZING) {
2318                     Slog.i(TAG, "Dozing...");
2319                 } else {
2320                     Slog.i(TAG, "Dreaming...");
2321                 }
2322             }
2323 
2324             // If preconditions changed, wait for the next iteration to determine
2325             // whether the dream should continue (or be restarted).
2326             if (mSandmanSummoned || mWakefulness != wakefulness) {
2327                 return; // wait for next cycle
2328             }
2329 
2330             // Determine whether the dream should continue.
2331             if (wakefulness == WAKEFULNESS_DREAMING) {
2332                 if (isDreaming && canDreamLocked()) {
2333                     if (mDreamsBatteryLevelDrainCutoffConfig >= 0
2334                             && mBatteryLevel < mBatteryLevelWhenDreamStarted
2335                                     - mDreamsBatteryLevelDrainCutoffConfig
2336                             && !isBeingKeptAwakeLocked()) {
2337                         // If the user activity timeout expired and the battery appears
2338                         // to be draining faster than it is charging then stop dreaming
2339                         // and go to sleep.
2340                         Slog.i(TAG, "Stopping dream because the battery appears to "
2341                                 + "be draining faster than it is charging.  "
2342                                 + "Battery level when dream started: "
2343                                 + mBatteryLevelWhenDreamStarted + "%.  "
2344                                 + "Battery level now: " + mBatteryLevel + "%.");
2345                     } else {
2346                         return; // continue dreaming
2347                     }
2348                 }
2349 
2350                 // Dream has ended or will be stopped.  Update the power state.
2351                 if (isItBedTimeYetLocked()) {
2352                     goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
2353                             PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
2354                     updatePowerStateLocked();
2355                 } else {
2356                     wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
2357                             PowerManager.WAKE_REASON_UNKNOWN,
2358                             "android.server.power:DREAM_FINISHED", Process.SYSTEM_UID,
2359                             mContext.getOpPackageName(), Process.SYSTEM_UID);
2360                     updatePowerStateLocked();
2361                 }
2362             } else if (wakefulness == WAKEFULNESS_DOZING) {
2363                 if (isDreaming) {
2364                     return; // continue dozing
2365                 }
2366 
2367                 // Doze has ended or will be stopped.  Update the power state.
2368                 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
2369                 updatePowerStateLocked();
2370             }
2371         }
2372 
2373         // Stop dream.
2374         if (isDreaming) {
2375             mDreamManager.stopDream(false /*immediate*/);
2376         }
2377     }
2378 
2379     /**
2380      * Returns true if the device is allowed to dream in its current state.
2381      */
canDreamLocked()2382     private boolean canDreamLocked() {
2383         if (mWakefulness != WAKEFULNESS_DREAMING
2384                 || !mDreamsSupportedConfig
2385                 || !mDreamsEnabledSetting
2386                 || !mDisplayPowerRequest.isBrightOrDim()
2387                 || mDisplayPowerRequest.isVr()
2388                 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2389                         | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
2390                 || !mBootCompleted) {
2391             return false;
2392         }
2393         if (!isBeingKeptAwakeLocked()) {
2394             if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
2395                 return false;
2396             }
2397             if (!mIsPowered
2398                     && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2399                     && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2400                 return false;
2401             }
2402             if (mIsPowered
2403                     && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2404                     && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2405                 return false;
2406             }
2407         }
2408         return true;
2409     }
2410 
2411     /**
2412      * Returns true if the device is allowed to doze in its current state.
2413      */
canDozeLocked()2414     private boolean canDozeLocked() {
2415         return mWakefulness == WAKEFULNESS_DOZING;
2416     }
2417 
2418     /**
2419      * Updates the display power state asynchronously.
2420      * When the update is finished, mDisplayReady will be set to true.  The display
2421      * controller posts a message to tell us when the actual display power state
2422      * has been updated so we come back here to double-check and finish up.
2423      *
2424      * This function recalculates the display power state each time.
2425      *
2426      * @return True if the display became ready.
2427      */
updateDisplayPowerStateLocked(int dirty)2428     private boolean updateDisplayPowerStateLocked(int dirty) {
2429         final boolean oldDisplayReady = mDisplayReady;
2430         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2431                 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
2432                 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2433                 DIRTY_QUIESCENT)) != 0) {
2434             mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
2435 
2436             // Determine appropriate screen brightness and auto-brightness adjustments.
2437             final boolean autoBrightness;
2438             final int screenBrightnessOverride;
2439             if (!mBootCompleted) {
2440                 // Keep the brightness steady during boot. This requires the
2441                 // bootloader brightness and the default brightness to be identical.
2442                 autoBrightness = false;
2443                 screenBrightnessOverride = mScreenBrightnessSettingDefault;
2444             } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
2445                 autoBrightness = false;
2446                 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManager;
2447             } else {
2448                 autoBrightness = (mScreenBrightnessModeSetting ==
2449                         Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2450                 screenBrightnessOverride = -1;
2451             }
2452 
2453             // Update display power request.
2454             mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
2455             mDisplayPowerRequest.useAutoBrightness = autoBrightness;
2456             mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
2457             mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
2458 
2459             updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2460 
2461             if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2462                 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
2463                 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0
2464                         && !mDrawWakeLockOverrideFromSidekick) {
2465                     if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2466                         mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2467                     }
2468                     if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2469                         mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2470                     }
2471                 }
2472                 mDisplayPowerRequest.dozeScreenBrightness =
2473                         mDozeScreenBrightnessOverrideFromDreamManager;
2474             } else {
2475                 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2476                 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2477             }
2478 
2479             mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
2480                     mRequestWaitForNegativeProximity);
2481             mRequestWaitForNegativeProximity = false;
2482 
2483             if ((dirty & DIRTY_QUIESCENT) != 0) {
2484                 sQuiescent = false;
2485             }
2486             if (DEBUG_SPEW) {
2487                 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
2488                         + ", policy=" + mDisplayPowerRequest.policy
2489                         + ", mWakefulness=" + mWakefulness
2490                         + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2491                         + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2492                         + ", mBootCompleted=" + mBootCompleted
2493                         + ", screenBrightnessOverride=" + screenBrightnessOverride
2494                         + ", useAutoBrightness=" + autoBrightness
2495                         + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
2496                         + ", mIsVrModeEnabled= " + mIsVrModeEnabled
2497                         + ", sQuiescent=" + sQuiescent);
2498             }
2499         }
2500         return mDisplayReady && !oldDisplayReady;
2501     }
2502 
updateScreenBrightnessBoostLocked(int dirty)2503     private void updateScreenBrightnessBoostLocked(int dirty) {
2504         if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2505             if (mScreenBrightnessBoostInProgress) {
2506                 final long now = SystemClock.uptimeMillis();
2507                 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2508                 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2509                     final long boostTimeout = mLastScreenBrightnessBoostTime +
2510                             SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2511                     if (boostTimeout > now) {
2512                         Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2513                         msg.setAsynchronous(true);
2514                         mHandler.sendMessageAtTime(msg, boostTimeout);
2515                         return;
2516                     }
2517                 }
2518                 mScreenBrightnessBoostInProgress = false;
2519                 mNotifier.onScreenBrightnessBoostChanged();
2520                 userActivityNoUpdateLocked(now,
2521                         PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2522             }
2523         }
2524     }
2525 
shouldBoostScreenBrightness()2526     private boolean shouldBoostScreenBrightness() {
2527         return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2528     }
2529 
isValidBrightness(int value)2530     private static boolean isValidBrightness(int value) {
2531         return value >= 0 && value <= 255;
2532     }
2533 
2534     @VisibleForTesting
getDesiredScreenPolicyLocked()2535     int getDesiredScreenPolicyLocked() {
2536         if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
2537             return DisplayPowerRequest.POLICY_OFF;
2538         }
2539 
2540         if (mWakefulness == WAKEFULNESS_DOZING) {
2541             if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2542                 return DisplayPowerRequest.POLICY_DOZE;
2543             }
2544             if (mDozeAfterScreenOff) {
2545                 return DisplayPowerRequest.POLICY_OFF;
2546             }
2547             // Fall through and preserve the current screen policy if not configured to
2548             // doze after screen off.  This causes the screen off transition to be skipped.
2549         }
2550 
2551         // It is important that POLICY_VR check happens after the wakefulness checks above so
2552         // that VR-mode does not prevent displays from transitioning to the correct state when
2553         // dozing or sleeping.
2554         if (mIsVrModeEnabled) {
2555             return DisplayPowerRequest.POLICY_VR;
2556         }
2557 
2558         if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2559                 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
2560                 || !mBootCompleted
2561                 || mScreenBrightnessBoostInProgress) {
2562             return DisplayPowerRequest.POLICY_BRIGHT;
2563         }
2564 
2565         return DisplayPowerRequest.POLICY_DIM;
2566     }
2567 
2568     private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2569             new DisplayManagerInternal.DisplayPowerCallbacks() {
2570         private int mDisplayState = Display.STATE_UNKNOWN;
2571 
2572         @Override
2573         public void onStateChanged() {
2574             synchronized (mLock) {
2575                 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2576                 updatePowerStateLocked();
2577             }
2578         }
2579 
2580         @Override
2581         public void onProximityPositive() {
2582             synchronized (mLock) {
2583                 mProximityPositive = true;
2584                 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2585                 updatePowerStateLocked();
2586             }
2587         }
2588 
2589         @Override
2590         public void onProximityNegative() {
2591             synchronized (mLock) {
2592                 mProximityPositive = false;
2593                 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2594                 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2595                         PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2596                 updatePowerStateLocked();
2597             }
2598         }
2599 
2600         @Override
2601         public void onDisplayStateChange(int state) {
2602             // This method is only needed to support legacy display blanking behavior
2603             // where the display's power state is coupled to suspend or to the power HAL.
2604             // The order of operations matters here.
2605             synchronized (mLock) {
2606                 if (mDisplayState != state) {
2607                     mDisplayState = state;
2608                     if (state == Display.STATE_OFF) {
2609                         if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2610                             setHalInteractiveModeLocked(false);
2611                         }
2612                         if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2613                             setHalAutoSuspendModeLocked(true);
2614                         }
2615                     } else {
2616                         if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2617                             setHalAutoSuspendModeLocked(false);
2618                         }
2619                         if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2620                             setHalInteractiveModeLocked(true);
2621                         }
2622                     }
2623                 }
2624             }
2625         }
2626 
2627         @Override
2628         public void acquireSuspendBlocker() {
2629             mDisplaySuspendBlocker.acquire();
2630         }
2631 
2632         @Override
2633         public void releaseSuspendBlocker() {
2634             mDisplaySuspendBlocker.release();
2635         }
2636 
2637         @Override
2638         public String toString() {
2639             synchronized (this) {
2640                 return "state=" + Display.stateToString(mDisplayState);
2641             }
2642         }
2643     };
2644 
shouldUseProximitySensorLocked()2645     private boolean shouldUseProximitySensorLocked() {
2646         return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
2647     }
2648 
2649     /**
2650      * Updates the suspend blocker that keeps the CPU alive.
2651      *
2652      * This function must have no other side-effects.
2653      */
updateSuspendBlockerLocked()2654     private void updateSuspendBlockerLocked() {
2655         final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
2656         final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2657         final boolean autoSuspend = !needDisplaySuspendBlocker;
2658         final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
2659 
2660         // Disable auto-suspend if needed.
2661         // FIXME We should consider just leaving auto-suspend enabled forever since
2662         // we already hold the necessary wakelocks.
2663         if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2664             setHalAutoSuspendModeLocked(false);
2665         }
2666 
2667         // First acquire suspend blockers if needed.
2668         if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2669             mWakeLockSuspendBlocker.acquire();
2670             mHoldingWakeLockSuspendBlocker = true;
2671         }
2672         if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2673             mDisplaySuspendBlocker.acquire();
2674             mHoldingDisplaySuspendBlocker = true;
2675         }
2676 
2677         // Inform the power HAL about interactive mode.
2678         // Although we could set interactive strictly based on the wakefulness
2679         // as reported by isInteractive(), it is actually more desirable to track
2680         // the display policy state instead so that the interactive state observed
2681         // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2682         // Refer to getDesiredScreenPolicyLocked() for details.
2683         if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2684             // When becoming non-interactive, we want to defer sending this signal
2685             // until the display is actually ready so that all transitions have
2686             // completed.  This is probably a good sign that things have gotten
2687             // too tangled over here...
2688             if (interactive || mDisplayReady) {
2689                 setHalInteractiveModeLocked(interactive);
2690             }
2691         }
2692 
2693         // Then release suspend blockers if needed.
2694         if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2695             mWakeLockSuspendBlocker.release();
2696             mHoldingWakeLockSuspendBlocker = false;
2697         }
2698         if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2699             mDisplaySuspendBlocker.release();
2700             mHoldingDisplaySuspendBlocker = false;
2701         }
2702 
2703         // Enable auto-suspend if needed.
2704         if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2705             setHalAutoSuspendModeLocked(true);
2706         }
2707     }
2708 
2709     /**
2710      * Return true if we must keep a suspend blocker active on behalf of the display.
2711      * We do so if the screen is on or is in transition between states.
2712      */
needDisplaySuspendBlockerLocked()2713     private boolean needDisplaySuspendBlockerLocked() {
2714         if (!mDisplayReady) {
2715             return true;
2716         }
2717         if (mDisplayPowerRequest.isBrightOrDim()) {
2718             // If we asked for the screen to be on but it is off due to the proximity
2719             // sensor then we may suspend but only if the configuration allows it.
2720             // On some hardware it may not be safe to suspend because the proximity
2721             // sensor may not be correctly configured as a wake-up source.
2722             if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2723                     || !mSuspendWhenScreenOffDueToProximityConfig) {
2724                 return true;
2725             }
2726         }
2727         if (mScreenBrightnessBoostInProgress) {
2728             return true;
2729         }
2730         // Let the system suspend if the screen is off or dozing.
2731         return false;
2732     }
2733 
setHalAutoSuspendModeLocked(boolean enable)2734     private void setHalAutoSuspendModeLocked(boolean enable) {
2735         if (enable != mHalAutoSuspendModeEnabled) {
2736             if (DEBUG) {
2737                 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
2738             }
2739             mHalAutoSuspendModeEnabled = enable;
2740             Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2741             try {
2742                 mNativeWrapper.nativeSetAutoSuspend(enable);
2743             } finally {
2744                 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2745             }
2746         }
2747     }
2748 
setHalInteractiveModeLocked(boolean enable)2749     private void setHalInteractiveModeLocked(boolean enable) {
2750         if (enable != mHalInteractiveModeEnabled) {
2751             if (DEBUG) {
2752                 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
2753             }
2754             mHalInteractiveModeEnabled = enable;
2755             Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2756             try {
2757                 mNativeWrapper.nativeSetInteractive(enable);
2758             } finally {
2759                 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2760             }
2761         }
2762     }
2763 
isInteractiveInternal()2764     private boolean isInteractiveInternal() {
2765         synchronized (mLock) {
2766             return PowerManagerInternal.isInteractive(mWakefulness);
2767         }
2768     }
2769 
setLowPowerModeInternal(boolean enabled)2770     private boolean setLowPowerModeInternal(boolean enabled) {
2771         synchronized (mLock) {
2772             if (DEBUG) {
2773                 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
2774             }
2775             if (mIsPowered) {
2776                 return false;
2777             }
2778 
2779             mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
2780 
2781             return true;
2782         }
2783     }
2784 
isDeviceIdleModeInternal()2785     boolean isDeviceIdleModeInternal() {
2786         synchronized (mLock) {
2787             return mDeviceIdleMode;
2788         }
2789     }
2790 
isLightDeviceIdleModeInternal()2791     boolean isLightDeviceIdleModeInternal() {
2792         synchronized (mLock) {
2793             return mLightDeviceIdleMode;
2794         }
2795     }
2796 
handleBatteryStateChangedLocked()2797     private void handleBatteryStateChangedLocked() {
2798         mDirty |= DIRTY_BATTERY_STATE;
2799         updatePowerStateLocked();
2800     }
2801 
shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm, final String reason, boolean wait)2802     private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
2803             final String reason, boolean wait) {
2804         if (mHandler == null || !mSystemReady) {
2805             if (RescueParty.isAttemptingFactoryReset()) {
2806                 // If we're stuck in a really low-level reboot loop, and a
2807                 // rescue party is trying to prompt the user for a factory data
2808                 // reset, we must GET TO DA CHOPPA!
2809                 PowerManagerService.lowLevelReboot(reason);
2810             } else {
2811                 throw new IllegalStateException("Too early to call shutdown() or reboot()");
2812             }
2813         }
2814 
2815         Runnable runnable = new Runnable() {
2816             @Override
2817             public void run() {
2818                 synchronized (this) {
2819                     if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
2820                         ShutdownThread.rebootSafeMode(getUiContext(), confirm);
2821                     } else if (haltMode == HALT_MODE_REBOOT) {
2822                         ShutdownThread.reboot(getUiContext(), reason, confirm);
2823                     } else {
2824                         ShutdownThread.shutdown(getUiContext(), reason, confirm);
2825                     }
2826                 }
2827             }
2828         };
2829 
2830         // ShutdownThread must run on a looper capable of displaying the UI.
2831         Message msg = Message.obtain(UiThread.getHandler(), runnable);
2832         msg.setAsynchronous(true);
2833         UiThread.getHandler().sendMessage(msg);
2834 
2835         // PowerManager.reboot() is documented not to return so just wait for the inevitable.
2836         if (wait) {
2837             synchronized (runnable) {
2838                 while (true) {
2839                     try {
2840                         runnable.wait();
2841                     } catch (InterruptedException e) {
2842                     }
2843                 }
2844             }
2845         }
2846     }
2847 
crashInternal(final String message)2848     private void crashInternal(final String message) {
2849         Thread t = new Thread("PowerManagerService.crash()") {
2850             @Override
2851             public void run() {
2852                 throw new RuntimeException(message);
2853             }
2854         };
2855         try {
2856             t.start();
2857             t.join();
2858         } catch (InterruptedException e) {
2859             Slog.wtf(TAG, e);
2860         }
2861     }
2862 
2863     @VisibleForTesting
updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest)2864     void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
2865         PowerSaveState state = mBatterySaverPolicy.
2866                 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS);
2867         displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
2868         displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
2869     }
2870 
setStayOnSettingInternal(int val)2871     void setStayOnSettingInternal(int val) {
2872         Settings.Global.putInt(mContext.getContentResolver(),
2873                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
2874     }
2875 
setMaximumScreenOffTimeoutFromDeviceAdminInternal(@serIdInt int userId, long timeMs)2876     void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
2877         if (userId < 0) {
2878             Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
2879             return;
2880         }
2881         synchronized (mLock) {
2882             // System-wide timeout
2883             if (userId == UserHandle.USER_SYSTEM) {
2884                 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2885             } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
2886                 mProfilePowerState.delete(userId);
2887             } else {
2888                 final ProfilePowerState profile = mProfilePowerState.get(userId);
2889                 if (profile != null) {
2890                     profile.mScreenOffTimeout = timeMs;
2891                 } else {
2892                     mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
2893                     // We need to recalculate wake locks for the new profile state.
2894                     mDirty |= DIRTY_WAKE_LOCKS;
2895                 }
2896             }
2897             mDirty |= DIRTY_SETTINGS;
2898             updatePowerStateLocked();
2899         }
2900     }
2901 
setDeviceIdleModeInternal(boolean enabled)2902     boolean setDeviceIdleModeInternal(boolean enabled) {
2903         synchronized (mLock) {
2904             if (mDeviceIdleMode == enabled) {
2905                 return false;
2906             }
2907             mDeviceIdleMode = enabled;
2908             updateWakeLockDisabledStatesLocked();
2909         }
2910         if (enabled) {
2911             EventLogTags.writeDeviceIdleOnPhase("power");
2912         } else {
2913             EventLogTags.writeDeviceIdleOffPhase("power");
2914         }
2915         return true;
2916     }
2917 
setLightDeviceIdleModeInternal(boolean enabled)2918     boolean setLightDeviceIdleModeInternal(boolean enabled) {
2919         synchronized (mLock) {
2920             if (mLightDeviceIdleMode != enabled) {
2921                 mLightDeviceIdleMode = enabled;
2922                 return true;
2923             }
2924             return false;
2925         }
2926     }
2927 
setDeviceIdleWhitelistInternal(int[] appids)2928     void setDeviceIdleWhitelistInternal(int[] appids) {
2929         synchronized (mLock) {
2930             mDeviceIdleWhitelist = appids;
2931             if (mDeviceIdleMode) {
2932                 updateWakeLockDisabledStatesLocked();
2933             }
2934         }
2935     }
2936 
setDeviceIdleTempWhitelistInternal(int[] appids)2937     void setDeviceIdleTempWhitelistInternal(int[] appids) {
2938         synchronized (mLock) {
2939             mDeviceIdleTempWhitelist = appids;
2940             if (mDeviceIdleMode) {
2941                 updateWakeLockDisabledStatesLocked();
2942             }
2943         }
2944     }
2945 
startUidChangesInternal()2946     void startUidChangesInternal() {
2947         synchronized (mLock) {
2948             mUidsChanging = true;
2949         }
2950     }
2951 
finishUidChangesInternal()2952     void finishUidChangesInternal() {
2953         synchronized (mLock) {
2954             mUidsChanging = false;
2955             if (mUidsChanged) {
2956                 updateWakeLockDisabledStatesLocked();
2957                 mUidsChanged = false;
2958             }
2959         }
2960     }
2961 
handleUidStateChangeLocked()2962     private void handleUidStateChangeLocked() {
2963         if (mUidsChanging) {
2964             mUidsChanged = true;
2965         } else {
2966             updateWakeLockDisabledStatesLocked();
2967         }
2968     }
2969 
updateUidProcStateInternal(int uid, int procState)2970     void updateUidProcStateInternal(int uid, int procState) {
2971         synchronized (mLock) {
2972             UidState state = mUidState.get(uid);
2973             if (state == null) {
2974                 state = new UidState(uid);
2975                 mUidState.put(uid, state);
2976             }
2977             final boolean oldShouldAllow = state.mProcState
2978                     <= ActivityManager.PROCESS_STATE_RECEIVER;
2979             state.mProcState = procState;
2980             if (state.mNumWakeLocks > 0) {
2981                 if (mDeviceIdleMode) {
2982                     handleUidStateChangeLocked();
2983                 } else if (!state.mActive && oldShouldAllow !=
2984                         (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
2985                     // If this uid is not active, but the process state has changed such
2986                     // that we may still want to allow it to hold a wake lock, then take care of it.
2987                     handleUidStateChangeLocked();
2988                 }
2989             }
2990         }
2991     }
2992 
uidGoneInternal(int uid)2993     void uidGoneInternal(int uid) {
2994         synchronized (mLock) {
2995             final int index = mUidState.indexOfKey(uid);
2996             if (index >= 0) {
2997                 UidState state = mUidState.valueAt(index);
2998                 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
2999                 state.mActive = false;
3000                 mUidState.removeAt(index);
3001                 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
3002                     handleUidStateChangeLocked();
3003                 }
3004             }
3005         }
3006     }
3007 
uidActiveInternal(int uid)3008     void uidActiveInternal(int uid) {
3009         synchronized (mLock) {
3010             UidState state = mUidState.get(uid);
3011             if (state == null) {
3012                 state = new UidState(uid);
3013                 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
3014                 mUidState.put(uid, state);
3015             }
3016             state.mActive = true;
3017             if (state.mNumWakeLocks > 0) {
3018                 handleUidStateChangeLocked();
3019             }
3020         }
3021     }
3022 
uidIdleInternal(int uid)3023     void uidIdleInternal(int uid) {
3024         synchronized (mLock) {
3025             UidState state = mUidState.get(uid);
3026             if (state != null) {
3027                 state.mActive = false;
3028                 if (state.mNumWakeLocks > 0) {
3029                     handleUidStateChangeLocked();
3030                 }
3031             }
3032         }
3033     }
3034 
updateWakeLockDisabledStatesLocked()3035     private void updateWakeLockDisabledStatesLocked() {
3036         boolean changed = false;
3037         final int numWakeLocks = mWakeLocks.size();
3038         for (int i = 0; i < numWakeLocks; i++) {
3039             final WakeLock wakeLock = mWakeLocks.get(i);
3040             if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3041                     == PowerManager.PARTIAL_WAKE_LOCK) {
3042                 if (setWakeLockDisabledStateLocked(wakeLock)) {
3043                     changed = true;
3044                     if (wakeLock.mDisabled) {
3045                         // This wake lock is no longer being respected.
3046                         notifyWakeLockReleasedLocked(wakeLock);
3047                     } else {
3048                         notifyWakeLockAcquiredLocked(wakeLock);
3049                     }
3050                 }
3051             }
3052         }
3053         if (changed) {
3054             mDirty |= DIRTY_WAKE_LOCKS;
3055             updatePowerStateLocked();
3056         }
3057     }
3058 
setWakeLockDisabledStateLocked(WakeLock wakeLock)3059     private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
3060         if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3061                 == PowerManager.PARTIAL_WAKE_LOCK) {
3062             boolean disabled = false;
3063             final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
3064             if (appid >= Process.FIRST_APPLICATION_UID) {
3065                 // Cached inactive processes are never allowed to hold wake locks.
3066                 if (mConstants.NO_CACHED_WAKE_LOCKS) {
3067                     disabled = mForceSuspendActive
3068                             || (!wakeLock.mUidState.mActive && wakeLock.mUidState.mProcState
3069                                     != ActivityManager.PROCESS_STATE_NONEXISTENT &&
3070                             wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER);
3071                 }
3072                 if (mDeviceIdleMode) {
3073                     // If we are in idle mode, we will also ignore all partial wake locks that are
3074                     // for application uids that are not whitelisted.
3075                     final UidState state = wakeLock.mUidState;
3076                     if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
3077                             Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
3078                             state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
3079                             state.mProcState >
3080                                     ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
3081                         disabled = true;
3082                     }
3083                 }
3084             }
3085             if (wakeLock.mDisabled != disabled) {
3086                 wakeLock.mDisabled = disabled;
3087                 return true;
3088             }
3089         }
3090         return false;
3091     }
3092 
isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()3093     private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3094         return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
3095                 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
3096     }
3097 
setAttentionLightInternal(boolean on, int color)3098     private void setAttentionLightInternal(boolean on, int color) {
3099         Light light;
3100         synchronized (mLock) {
3101             if (!mSystemReady) {
3102                 return;
3103             }
3104             light = mAttentionLight;
3105         }
3106 
3107         // Control light outside of lock.
3108         light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
3109     }
3110 
setDozeAfterScreenOffInternal(boolean on)3111     private void setDozeAfterScreenOffInternal(boolean on) {
3112         synchronized (mLock) {
3113             mDozeAfterScreenOff = on;
3114         }
3115     }
3116 
boostScreenBrightnessInternal(long eventTime, int uid)3117     private void boostScreenBrightnessInternal(long eventTime, int uid) {
3118         synchronized (mLock) {
3119             if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3120                     || eventTime < mLastScreenBrightnessBoostTime) {
3121                 return;
3122             }
3123 
3124             Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3125             mLastScreenBrightnessBoostTime = eventTime;
3126             if (!mScreenBrightnessBoostInProgress) {
3127                 mScreenBrightnessBoostInProgress = true;
3128                 mNotifier.onScreenBrightnessBoostChanged();
3129             }
3130             mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3131 
3132             userActivityNoUpdateLocked(eventTime,
3133                     PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3134             updatePowerStateLocked();
3135         }
3136     }
3137 
isScreenBrightnessBoostedInternal()3138     private boolean isScreenBrightnessBoostedInternal() {
3139         synchronized (mLock) {
3140             return mScreenBrightnessBoostInProgress;
3141         }
3142     }
3143 
3144     /**
3145      * Called when a screen brightness boost timeout has occurred.
3146      *
3147      * This function must have no other side-effects besides setting the dirty
3148      * bit and calling update power state.
3149      */
handleScreenBrightnessBoostTimeout()3150     private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3151         synchronized (mLock) {
3152             if (DEBUG_SPEW) {
3153                 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3154             }
3155 
3156             mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3157             updatePowerStateLocked();
3158         }
3159     }
3160 
setScreenBrightnessOverrideFromWindowManagerInternal(int brightness)3161     private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3162         synchronized (mLock) {
3163             if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3164                 mScreenBrightnessOverrideFromWindowManager = brightness;
3165                 mDirty |= DIRTY_SETTINGS;
3166                 updatePowerStateLocked();
3167             }
3168         }
3169     }
3170 
setUserInactiveOverrideFromWindowManagerInternal()3171     private void setUserInactiveOverrideFromWindowManagerInternal() {
3172         synchronized (mLock) {
3173             mUserInactiveOverrideFromWindowManager = true;
3174             mDirty |= DIRTY_USER_ACTIVITY;
3175             updatePowerStateLocked();
3176         }
3177     }
3178 
setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis)3179     private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3180         synchronized (mLock) {
3181             if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3182                 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
3183                 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
3184                 mDirty |= DIRTY_SETTINGS;
3185                 updatePowerStateLocked();
3186             }
3187         }
3188     }
3189 
setDozeOverrideFromDreamManagerInternal( int screenState, int screenBrightness)3190     private void setDozeOverrideFromDreamManagerInternal(
3191             int screenState, int screenBrightness) {
3192         synchronized (mLock) {
3193             if (mDozeScreenStateOverrideFromDreamManager != screenState
3194                     || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3195                 mDozeScreenStateOverrideFromDreamManager = screenState;
3196                 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
3197                 mDirty |= DIRTY_SETTINGS;
3198                 updatePowerStateLocked();
3199             }
3200         }
3201     }
3202 
setDrawWakeLockOverrideFromSidekickInternal(boolean keepState)3203     private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
3204         synchronized (mLock) {
3205             if (mDrawWakeLockOverrideFromSidekick != keepState) {
3206                 mDrawWakeLockOverrideFromSidekick = keepState;
3207                 mDirty |= DIRTY_SETTINGS;
3208                 updatePowerStateLocked();
3209             }
3210         }
3211     }
3212 
3213     @VisibleForTesting
setVrModeEnabled(boolean enabled)3214     void setVrModeEnabled(boolean enabled) {
3215         mIsVrModeEnabled = enabled;
3216     }
3217 
powerHintInternal(int hintId, int data)3218     private void powerHintInternal(int hintId, int data) {
3219         // Maybe filter the event.
3220         switch (hintId) {
3221             case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3222                 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3223                     return;
3224                 }
3225                 break;
3226         }
3227 
3228         mNativeWrapper.nativeSendPowerHint(hintId, data);
3229     }
3230 
3231     @VisibleForTesting
wasDeviceIdleForInternal(long ms)3232     boolean wasDeviceIdleForInternal(long ms) {
3233         synchronized (mLock) {
3234             return mLastUserActivityTime + ms < SystemClock.uptimeMillis();
3235         }
3236     }
3237 
3238     @VisibleForTesting
onUserActivity()3239     void onUserActivity() {
3240         synchronized (mLock) {
3241             mLastUserActivityTime = SystemClock.uptimeMillis();
3242         }
3243     }
3244 
forceSuspendInternal(int uid)3245     private boolean forceSuspendInternal(int uid) {
3246         try {
3247             synchronized (mLock) {
3248                 mForceSuspendActive = true;
3249                 // Place the system in an non-interactive state
3250                 goToSleepInternal(SystemClock.uptimeMillis(),
3251                         PowerManager.GO_TO_SLEEP_REASON_FORCE_SUSPEND,
3252                         PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, uid);
3253 
3254                 // Disable all the partial wake locks as well
3255                 updateWakeLockDisabledStatesLocked();
3256             }
3257 
3258             Slog.i(TAG, "Force-Suspending (uid " + uid + ")...");
3259             boolean success = mNativeWrapper.nativeForceSuspend();
3260             if (!success) {
3261                 Slog.i(TAG, "Force-Suspending failed in native.");
3262             }
3263             return success;
3264         } finally {
3265             synchronized (mLock) {
3266                 mForceSuspendActive = false;
3267                 // Re-enable wake locks once again.
3268                 updateWakeLockDisabledStatesLocked();
3269             }
3270         }
3271     }
3272 
3273     /**
3274      * Low-level function turn the device off immediately, without trying
3275      * to be clean.  Most people should use {@link ShutdownThread} for a clean shutdown.
3276      *
3277      * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
3278      */
lowLevelShutdown(String reason)3279     public static void lowLevelShutdown(String reason) {
3280         if (reason == null) {
3281             reason = "";
3282         }
3283         SystemProperties.set("sys.powerctl", "shutdown," + reason);
3284     }
3285 
3286     /**
3287      * Low-level function to reboot the device. On success, this
3288      * function doesn't return. If more than 20 seconds passes from
3289      * the time a reboot is requested, this method returns.
3290      *
3291      * @param reason code to pass to the kernel (e.g. "recovery"), or null.
3292      */
lowLevelReboot(String reason)3293     public static void lowLevelReboot(String reason) {
3294         if (reason == null) {
3295             reason = "";
3296         }
3297 
3298         // If the reason is "quiescent", it means that the boot process should proceed
3299         // without turning on the screen/lights.
3300         // The "quiescent" property is sticky, meaning that any number
3301         // of subsequent reboots should honor the property until it is reset.
3302         if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3303             sQuiescent = true;
3304             reason = "";
3305         } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3306             sQuiescent = true;
3307             reason = reason.substring(0,
3308                     reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3309         }
3310 
3311         if (reason.equals(PowerManager.REBOOT_RECOVERY)
3312                 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3313             reason = "recovery";
3314         }
3315 
3316         if (sQuiescent) {
3317             // Pass the optional "quiescent" argument to the bootloader to let it know
3318             // that it should not turn the screen/lights on.
3319             reason = reason + ",quiescent";
3320         }
3321 
3322         SystemProperties.set("sys.powerctl", "reboot," + reason);
3323         try {
3324             Thread.sleep(20 * 1000L);
3325         } catch (InterruptedException e) {
3326             Thread.currentThread().interrupt();
3327         }
3328         Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
3329     }
3330 
3331     @Override // Watchdog.Monitor implementation
monitor()3332     public void monitor() {
3333         // Grab and release lock for watchdog monitor to detect deadlocks.
3334         synchronized (mLock) {
3335         }
3336     }
3337 
dumpInternal(PrintWriter pw)3338     private void dumpInternal(PrintWriter pw) {
3339         pw.println("POWER MANAGER (dumpsys power)\n");
3340 
3341         final WirelessChargerDetector wcd;
3342         synchronized (mLock) {
3343             pw.println("Power Manager State:");
3344             mConstants.dump(pw);
3345             pw.println("  mDirty=0x" + Integer.toHexString(mDirty));
3346             pw.println("  mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3347             pw.println("  mWakefulnessChanging=" + mWakefulnessChanging);
3348             pw.println("  mIsPowered=" + mIsPowered);
3349             pw.println("  mPlugType=" + mPlugType);
3350             pw.println("  mBatteryLevel=" + mBatteryLevel);
3351             pw.println("  mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
3352             pw.println("  mDockState=" + mDockState);
3353             pw.println("  mStayOn=" + mStayOn);
3354             pw.println("  mProximityPositive=" + mProximityPositive);
3355             pw.println("  mBootCompleted=" + mBootCompleted);
3356             pw.println("  mSystemReady=" + mSystemReady);
3357             pw.println("  mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3358             pw.println("  mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
3359             pw.println("  mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
3360             pw.print("  mNotifyLongScheduled=");
3361             if (mNotifyLongScheduled == 0) {
3362                 pw.print("(none)");
3363             } else {
3364                 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3365             }
3366             pw.println();
3367             pw.print("  mNotifyLongDispatched=");
3368             if (mNotifyLongDispatched == 0) {
3369                 pw.print("(none)");
3370             } else {
3371                 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3372             }
3373             pw.println();
3374             pw.print("  mNotifyLongNextCheck=");
3375             if (mNotifyLongNextCheck == 0) {
3376                 pw.print("(none)");
3377             } else {
3378                 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3379             }
3380             pw.println();
3381             pw.println("  mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3382             pw.println("  mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3383             pw.println("  mSandmanScheduled=" + mSandmanScheduled);
3384             pw.println("  mSandmanSummoned=" + mSandmanSummoned);
3385             pw.println("  mBatteryLevelLow=" + mBatteryLevelLow);
3386             pw.println("  mLightDeviceIdleMode=" + mLightDeviceIdleMode);
3387             pw.println("  mDeviceIdleMode=" + mDeviceIdleMode);
3388             pw.println("  mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
3389             pw.println("  mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
3390             pw.println("  mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3391             pw.println("  mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
3392             pw.println("  mLastSleepReason=" + PowerManager.sleepReasonToString(mLastSleepReason));
3393             pw.println("  mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3394             pw.println("  mLastUserActivityTimeNoChangeLights="
3395                     + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
3396             pw.println("  mLastInteractivePowerHintTime="
3397                     + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
3398             pw.println("  mLastScreenBrightnessBoostTime="
3399                     + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3400             pw.println("  mScreenBrightnessBoostInProgress="
3401                     + mScreenBrightnessBoostInProgress);
3402             pw.println("  mDisplayReady=" + mDisplayReady);
3403             pw.println("  mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
3404             pw.println("  mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
3405 
3406             pw.println();
3407             pw.println("Settings and Configuration:");
3408             pw.println("  mDecoupleHalAutoSuspendModeFromDisplayConfig="
3409                     + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3410             pw.println("  mDecoupleHalInteractiveModeFromDisplayConfig="
3411                     + mDecoupleHalInteractiveModeFromDisplayConfig);
3412             pw.println("  mWakeUpWhenPluggedOrUnpluggedConfig="
3413                     + mWakeUpWhenPluggedOrUnpluggedConfig);
3414             pw.println("  mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3415                     + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3416             pw.println("  mTheaterModeEnabled="
3417                     + mTheaterModeEnabled);
3418             pw.println("  mSuspendWhenScreenOffDueToProximityConfig="
3419                     + mSuspendWhenScreenOffDueToProximityConfig);
3420             pw.println("  mDreamsSupportedConfig=" + mDreamsSupportedConfig);
3421             pw.println("  mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3422             pw.println("  mDreamsActivatedOnSleepByDefaultConfig="
3423                     + mDreamsActivatedOnSleepByDefaultConfig);
3424             pw.println("  mDreamsActivatedOnDockByDefaultConfig="
3425                     + mDreamsActivatedOnDockByDefaultConfig);
3426             pw.println("  mDreamsEnabledOnBatteryConfig="
3427                     + mDreamsEnabledOnBatteryConfig);
3428             pw.println("  mDreamsBatteryLevelMinimumWhenPoweredConfig="
3429                     + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3430             pw.println("  mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3431                     + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3432             pw.println("  mDreamsBatteryLevelDrainCutoffConfig="
3433                     + mDreamsBatteryLevelDrainCutoffConfig);
3434             pw.println("  mDreamsEnabledSetting=" + mDreamsEnabledSetting);
3435             pw.println("  mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
3436             pw.println("  mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
3437             pw.println("  mDozeAfterScreenOff=" + mDozeAfterScreenOff);
3438             pw.println("  mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3439             pw.println("  mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3440             pw.println("  mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
3441             pw.println("  mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
3442             pw.println("  mSleepTimeoutSetting=" + mSleepTimeoutSetting);
3443             pw.println("  mMaximumScreenOffTimeoutFromDeviceAdmin="
3444                     + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3445                     + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3446             pw.println("  mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
3447             pw.println("  mScreenBrightnessSetting=" + mScreenBrightnessSetting);
3448             pw.println("  mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
3449             pw.println("  mScreenBrightnessOverrideFromWindowManager="
3450                     + mScreenBrightnessOverrideFromWindowManager);
3451             pw.println("  mUserActivityTimeoutOverrideFromWindowManager="
3452                     + mUserActivityTimeoutOverrideFromWindowManager);
3453             pw.println("  mUserInactiveOverrideFromWindowManager="
3454                     + mUserInactiveOverrideFromWindowManager);
3455             pw.println("  mDozeScreenStateOverrideFromDreamManager="
3456                     + mDozeScreenStateOverrideFromDreamManager);
3457             pw.println("  mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
3458             pw.println("  mDozeScreenBrightnessOverrideFromDreamManager="
3459                     + mDozeScreenBrightnessOverrideFromDreamManager);
3460             pw.println("  mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
3461             pw.println("  mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
3462             pw.println("  mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
3463             pw.println("  mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
3464             pw.println("  mIsVrModeEnabled=" + mIsVrModeEnabled);
3465             pw.println("  mForegroundProfile=" + mForegroundProfile);
3466 
3467             final long sleepTimeout = getSleepTimeoutLocked();
3468             final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3469             final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
3470             pw.println();
3471             pw.println("Sleep timeout: " + sleepTimeout + " ms");
3472             pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3473             pw.println("Screen dim duration: " + screenDimDuration + " ms");
3474 
3475             pw.println();
3476             pw.print("UID states (changing=");
3477             pw.print(mUidsChanging);
3478             pw.print(" changed=");
3479             pw.print(mUidsChanged);
3480             pw.println("):");
3481             for (int i=0; i<mUidState.size(); i++) {
3482                 final UidState state = mUidState.valueAt(i);
3483                 pw.print("  UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
3484                 pw.print(": ");
3485                 if (state.mActive) pw.print("  ACTIVE ");
3486                 else pw.print("INACTIVE ");
3487                 pw.print(" count=");
3488                 pw.print(state.mNumWakeLocks);
3489                 pw.print(" state=");
3490                 pw.println(state.mProcState);
3491             }
3492 
3493             pw.println();
3494             pw.println("Looper state:");
3495             mHandler.getLooper().dump(new PrintWriterPrinter(pw), "  ");
3496 
3497             pw.println();
3498             pw.println("Wake Locks: size=" + mWakeLocks.size());
3499             for (WakeLock wl : mWakeLocks) {
3500                 pw.println("  " + wl);
3501             }
3502 
3503             pw.println();
3504             pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3505             for (SuspendBlocker sb : mSuspendBlockers) {
3506                 pw.println("  " + sb);
3507             }
3508 
3509             pw.println();
3510             pw.println("Display Power: " + mDisplayPowerCallbacks);
3511 
3512             mBatterySaverPolicy.dump(pw);
3513             mBatterySaverStateMachine.dump(pw);
3514             mAttentionDetector.dump(pw);
3515 
3516             pw.println();
3517             final int numProfiles = mProfilePowerState.size();
3518             pw.println("Profile power states: size=" + numProfiles);
3519             for (int i = 0; i < numProfiles; i++) {
3520                 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3521                 pw.print("  mUserId=");
3522                 pw.print(profile.mUserId);
3523                 pw.print(" mScreenOffTimeout=");
3524                 pw.print(profile.mScreenOffTimeout);
3525                 pw.print(" mWakeLockSummary=");
3526                 pw.print(profile.mWakeLockSummary);
3527                 pw.print(" mLastUserActivityTime=");
3528                 pw.print(profile.mLastUserActivityTime);
3529                 pw.print(" mLockingNotified=");
3530                 pw.println(profile.mLockingNotified);
3531             }
3532 
3533             wcd = mWirelessChargerDetector;
3534         }
3535 
3536         if (wcd != null) {
3537             wcd.dump(pw);
3538         }
3539     }
3540 
dumpProto(FileDescriptor fd)3541     private void dumpProto(FileDescriptor fd) {
3542         final WirelessChargerDetector wcd;
3543         final ProtoOutputStream proto = new ProtoOutputStream(fd);
3544 
3545         synchronized (mLock) {
3546             mConstants.dumpProto(proto);
3547             proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3548             proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3549             proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3550             proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3551             proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3552             proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
3553             proto.write(
3554                     PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
3555                     mBatteryLevelWhenDreamStarted);
3556             proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3557             proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3558             proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3559             proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3560             proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
3561             proto.write(
3562                     PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
3563                     mHalAutoSuspendModeEnabled);
3564             proto.write(
3565                     PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
3566                     mHalInteractiveModeEnabled);
3567 
3568             final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
3569             proto.write(
3570                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
3571                     (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3572             proto.write(
3573                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
3574                     (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3575             proto.write(
3576                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
3577                     (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3578             proto.write(
3579                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
3580                     (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3581             proto.write(
3582                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
3583                     (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3584             proto.write(
3585                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
3586                     (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3587             proto.write(
3588                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
3589                     (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3590             proto.write(
3591                     PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
3592                     (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3593             proto.end(activeWakeLocksToken);
3594 
3595             proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3596             proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3597             proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
3598 
3599             final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
3600             proto.write(
3601                     PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
3602                     (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3603             proto.write(
3604                     PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
3605                     (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3606             proto.write(
3607                     PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
3608                     (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
3609             proto.end(userActivityToken);
3610 
3611             proto.write(
3612                     PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
3613                     mRequestWaitForNegativeProximity);
3614             proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
3615             proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
3616             proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
3617             proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
3618             proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
3619 
3620             for (int id : mDeviceIdleWhitelist) {
3621                 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
3622             }
3623             for (int id : mDeviceIdleTempWhitelist) {
3624                 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
3625             }
3626 
3627             proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
3628             proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
3629             proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
3630             proto.write(
3631                     PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
3632                     mLastUserActivityTimeNoChangeLights);
3633             proto.write(
3634                     PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
3635                     mLastInteractivePowerHintTime);
3636             proto.write(
3637                     PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
3638                     mLastScreenBrightnessBoostTime);
3639             proto.write(
3640                     PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
3641                     mScreenBrightnessBoostInProgress);
3642             proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
3643             proto.write(
3644                     PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
3645                     mHoldingWakeLockSuspendBlocker);
3646             proto.write(
3647                     PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
3648                     mHoldingDisplaySuspendBlocker);
3649 
3650             final long settingsAndConfigurationToken =
3651                     proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
3652             proto.write(
3653                     PowerServiceSettingsAndConfigurationDumpProto
3654                             .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
3655                     mDecoupleHalAutoSuspendModeFromDisplayConfig);
3656             proto.write(
3657                     PowerServiceSettingsAndConfigurationDumpProto
3658                             .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
3659                     mDecoupleHalInteractiveModeFromDisplayConfig);
3660             proto.write(
3661                     PowerServiceSettingsAndConfigurationDumpProto
3662                             .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
3663                     mWakeUpWhenPluggedOrUnpluggedConfig);
3664             proto.write(
3665                     PowerServiceSettingsAndConfigurationDumpProto
3666                             .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
3667                     mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3668             proto.write(
3669                     PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
3670                     mTheaterModeEnabled);
3671             proto.write(
3672                     PowerServiceSettingsAndConfigurationDumpProto
3673                             .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
3674                     mSuspendWhenScreenOffDueToProximityConfig);
3675             proto.write(
3676                     PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
3677                     mDreamsSupportedConfig);
3678             proto.write(
3679                     PowerServiceSettingsAndConfigurationDumpProto
3680                             .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
3681                     mDreamsEnabledByDefaultConfig);
3682             proto.write(
3683                     PowerServiceSettingsAndConfigurationDumpProto
3684                             .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
3685                     mDreamsActivatedOnSleepByDefaultConfig);
3686             proto.write(
3687                     PowerServiceSettingsAndConfigurationDumpProto
3688                             .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
3689                     mDreamsActivatedOnDockByDefaultConfig);
3690             proto.write(
3691                     PowerServiceSettingsAndConfigurationDumpProto
3692                             .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
3693                     mDreamsEnabledOnBatteryConfig);
3694             proto.write(
3695                     PowerServiceSettingsAndConfigurationDumpProto
3696                             .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
3697                     mDreamsBatteryLevelMinimumWhenPoweredConfig);
3698             proto.write(
3699                     PowerServiceSettingsAndConfigurationDumpProto
3700                             .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
3701                     mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3702             proto.write(
3703                     PowerServiceSettingsAndConfigurationDumpProto
3704                             .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
3705                     mDreamsBatteryLevelDrainCutoffConfig);
3706             proto.write(
3707                     PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
3708                     mDreamsEnabledSetting);
3709             proto.write(
3710                     PowerServiceSettingsAndConfigurationDumpProto
3711                             .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
3712                     mDreamsActivateOnSleepSetting);
3713             proto.write(
3714                     PowerServiceSettingsAndConfigurationDumpProto
3715                             .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
3716                     mDreamsActivateOnDockSetting);
3717             proto.write(
3718                     PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
3719                     mDozeAfterScreenOff);
3720             proto.write(
3721                     PowerServiceSettingsAndConfigurationDumpProto
3722                             .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
3723                     mMinimumScreenOffTimeoutConfig);
3724             proto.write(
3725                     PowerServiceSettingsAndConfigurationDumpProto
3726                             .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
3727                     mMaximumScreenDimDurationConfig);
3728             proto.write(
3729                     PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
3730                     mMaximumScreenDimRatioConfig);
3731             proto.write(
3732                     PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
3733                     mScreenOffTimeoutSetting);
3734             proto.write(
3735                     PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
3736                     mSleepTimeoutSetting);
3737             proto.write(
3738                     PowerServiceSettingsAndConfigurationDumpProto
3739                             .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
3740                     // Clamp to int32
3741                     Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
3742             proto.write(
3743                     PowerServiceSettingsAndConfigurationDumpProto
3744                             .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
3745                     isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
3746 
3747             final long stayOnWhilePluggedInToken =
3748                     proto.start(
3749                             PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
3750             proto.write(
3751                     PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3752                             .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
3753                     ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
3754             proto.write(
3755                     PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3756                             .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
3757                     ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
3758             proto.write(
3759                     PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3760                             .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
3761                     ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
3762                             != 0));
3763             proto.end(stayOnWhilePluggedInToken);
3764 
3765             proto.write(
3766                     PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
3767                     mScreenBrightnessModeSetting);
3768             proto.write(
3769                     PowerServiceSettingsAndConfigurationDumpProto
3770                             .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
3771                     mScreenBrightnessOverrideFromWindowManager);
3772             proto.write(
3773                     PowerServiceSettingsAndConfigurationDumpProto
3774                             .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
3775                     mUserActivityTimeoutOverrideFromWindowManager);
3776             proto.write(
3777                     PowerServiceSettingsAndConfigurationDumpProto
3778                             .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
3779                     mUserInactiveOverrideFromWindowManager);
3780             proto.write(
3781                     PowerServiceSettingsAndConfigurationDumpProto
3782                             .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
3783                     mDozeScreenStateOverrideFromDreamManager);
3784             proto.write(
3785                     PowerServiceSettingsAndConfigurationDumpProto
3786                             .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
3787                     mDrawWakeLockOverrideFromSidekick);
3788             proto.write(
3789                     PowerServiceSettingsAndConfigurationDumpProto
3790                             .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
3791                     mDozeScreenBrightnessOverrideFromDreamManager);
3792 
3793             final long screenBrightnessSettingLimitsToken =
3794                     proto.start(
3795                             PowerServiceSettingsAndConfigurationDumpProto
3796                                     .SCREEN_BRIGHTNESS_SETTING_LIMITS);
3797             proto.write(
3798                     PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3799                             .SETTING_MINIMUM,
3800                     mScreenBrightnessSettingMinimum);
3801             proto.write(
3802                     PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3803                             .SETTING_MAXIMUM,
3804                     mScreenBrightnessSettingMaximum);
3805             proto.write(
3806                     PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3807                             .SETTING_DEFAULT,
3808                     mScreenBrightnessSettingDefault);
3809             proto.end(screenBrightnessSettingLimitsToken);
3810 
3811             proto.write(
3812                     PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
3813                     mDoubleTapWakeEnabled);
3814             proto.write(
3815                     PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
3816                     mIsVrModeEnabled);
3817             proto.end(settingsAndConfigurationToken);
3818 
3819             final long sleepTimeout = getSleepTimeoutLocked();
3820             final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3821             final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
3822             proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
3823             proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
3824             proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
3825             proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
3826             proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
3827 
3828             for (int i = 0; i < mUidState.size(); i++) {
3829                 final UidState state = mUidState.valueAt(i);
3830                 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
3831                 final int uid = mUidState.keyAt(i);
3832                 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
3833                 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
3834                 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
3835                 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
3836                 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
3837                         ActivityManager.processStateAmToProto(state.mProcState));
3838                 proto.end(uIDToken);
3839             }
3840 
3841             mBatterySaverStateMachine.dumpProto(proto,
3842                     PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
3843 
3844             mHandler.getLooper().writeToProto(proto, PowerManagerServiceDumpProto.LOOPER);
3845 
3846             for (WakeLock wl : mWakeLocks) {
3847                 wl.writeToProto(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
3848             }
3849 
3850             for (SuspendBlocker sb : mSuspendBlockers) {
3851                 sb.writeToProto(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
3852             }
3853             wcd = mWirelessChargerDetector;
3854         }
3855 
3856         if (wcd != null) {
3857             wcd.writeToProto(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
3858         }
3859         proto.flush();
3860     }
3861 
incrementBootCount()3862     private void incrementBootCount() {
3863         synchronized (mLock) {
3864             int count;
3865             try {
3866                 count = Settings.Global.getInt(
3867                         getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
3868             } catch (SettingNotFoundException e) {
3869                 count = 0;
3870             }
3871             Settings.Global.putInt(
3872                     getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
3873         }
3874     }
3875 
copyWorkSource(WorkSource workSource)3876     private static WorkSource copyWorkSource(WorkSource workSource) {
3877         return workSource != null ? new WorkSource(workSource) : null;
3878     }
3879 
3880     @VisibleForTesting
3881     final class BatteryReceiver extends BroadcastReceiver {
3882         @Override
onReceive(Context context, Intent intent)3883         public void onReceive(Context context, Intent intent) {
3884             synchronized (mLock) {
3885                 handleBatteryStateChangedLocked();
3886             }
3887         }
3888     }
3889 
3890     private final class DreamReceiver extends BroadcastReceiver {
3891         @Override
onReceive(Context context, Intent intent)3892         public void onReceive(Context context, Intent intent) {
3893             synchronized (mLock) {
3894                 scheduleSandmanLocked();
3895             }
3896         }
3897     }
3898 
3899     @VisibleForTesting
3900     final class UserSwitchedReceiver extends BroadcastReceiver {
3901         @Override
onReceive(Context context, Intent intent)3902         public void onReceive(Context context, Intent intent) {
3903             synchronized (mLock) {
3904                 handleSettingsChangedLocked();
3905             }
3906         }
3907     }
3908 
3909     private final class DockReceiver extends BroadcastReceiver {
3910         @Override
onReceive(Context context, Intent intent)3911         public void onReceive(Context context, Intent intent) {
3912             synchronized (mLock) {
3913                 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3914                         Intent.EXTRA_DOCK_STATE_UNDOCKED);
3915                 if (mDockState != dockState) {
3916                     mDockState = dockState;
3917                     mDirty |= DIRTY_DOCK_STATE;
3918                     updatePowerStateLocked();
3919                 }
3920             }
3921         }
3922     }
3923 
3924     private final class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler)3925         public SettingsObserver(Handler handler) {
3926             super(handler);
3927         }
3928 
3929         @Override
onChange(boolean selfChange, Uri uri)3930         public void onChange(boolean selfChange, Uri uri) {
3931             synchronized (mLock) {
3932                 handleSettingsChangedLocked();
3933             }
3934         }
3935     }
3936 
3937     private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
3938         @Override
3939         public void onVrStateChanged(boolean enabled) {
3940             powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
3941 
3942             synchronized (mLock) {
3943                 if (mIsVrModeEnabled != enabled) {
3944                     setVrModeEnabled(enabled);
3945                     mDirty |= DIRTY_VR_MODE_CHANGED;
3946                     updatePowerStateLocked();
3947                 }
3948             }
3949         }
3950     };
3951 
3952     /**
3953      * Handler for asynchronous operations performed by the power manager.
3954      */
3955     private final class PowerManagerHandler extends Handler {
PowerManagerHandler(Looper looper)3956         public PowerManagerHandler(Looper looper) {
3957             super(looper, null, true /*async*/);
3958         }
3959 
3960         @Override
handleMessage(Message msg)3961         public void handleMessage(Message msg) {
3962             switch (msg.what) {
3963                 case MSG_USER_ACTIVITY_TIMEOUT:
3964                     handleUserActivityTimeout();
3965                     break;
3966                 case MSG_SANDMAN:
3967                     handleSandman();
3968                     break;
3969                 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
3970                     handleScreenBrightnessBoostTimeout();
3971                     break;
3972                 case MSG_CHECK_FOR_LONG_WAKELOCKS:
3973                     checkForLongWakeLocks();
3974                     break;
3975             }
3976         }
3977     }
3978 
3979     /**
3980      * Represents a wake lock that has been acquired by an application.
3981      */
3982     private final class WakeLock implements IBinder.DeathRecipient {
3983         public final IBinder mLock;
3984         public int mFlags;
3985         public String mTag;
3986         public final String mPackageName;
3987         public WorkSource mWorkSource;
3988         public String mHistoryTag;
3989         public final int mOwnerUid;
3990         public final int mOwnerPid;
3991         public final UidState mUidState;
3992         public long mAcquireTime;
3993         public boolean mNotifiedAcquired;
3994         public boolean mNotifiedLong;
3995         public boolean mDisabled;
3996 
WakeLock(IBinder lock, int flags, String tag, String packageName, WorkSource workSource, String historyTag, int ownerUid, int ownerPid, UidState uidState)3997         public WakeLock(IBinder lock, int flags, String tag, String packageName,
3998                 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
3999                 UidState uidState) {
4000             mLock = lock;
4001             mFlags = flags;
4002             mTag = tag;
4003             mPackageName = packageName;
4004             mWorkSource = copyWorkSource(workSource);
4005             mHistoryTag = historyTag;
4006             mOwnerUid = ownerUid;
4007             mOwnerPid = ownerPid;
4008             mUidState = uidState;
4009         }
4010 
4011         @Override
binderDied()4012         public void binderDied() {
4013             PowerManagerService.this.handleWakeLockDeath(this);
4014         }
4015 
hasSameProperties(int flags, String tag, WorkSource workSource, int ownerUid, int ownerPid)4016         public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
4017                 int ownerUid, int ownerPid) {
4018             return mFlags == flags
4019                     && mTag.equals(tag)
4020                     && hasSameWorkSource(workSource)
4021                     && mOwnerUid == ownerUid
4022                     && mOwnerPid == ownerPid;
4023         }
4024 
updateProperties(int flags, String tag, String packageName, WorkSource workSource, String historyTag, int ownerUid, int ownerPid)4025         public void updateProperties(int flags, String tag, String packageName,
4026                 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
4027             if (!mPackageName.equals(packageName)) {
4028                 throw new IllegalStateException("Existing wake lock package name changed: "
4029                         + mPackageName + " to " + packageName);
4030             }
4031             if (mOwnerUid != ownerUid) {
4032                 throw new IllegalStateException("Existing wake lock uid changed: "
4033                         + mOwnerUid + " to " + ownerUid);
4034             }
4035             if (mOwnerPid != ownerPid) {
4036                 throw new IllegalStateException("Existing wake lock pid changed: "
4037                         + mOwnerPid + " to " + ownerPid);
4038             }
4039             mFlags = flags;
4040             mTag = tag;
4041             updateWorkSource(workSource);
4042             mHistoryTag = historyTag;
4043         }
4044 
hasSameWorkSource(WorkSource workSource)4045         public boolean hasSameWorkSource(WorkSource workSource) {
4046             return Objects.equals(mWorkSource, workSource);
4047         }
4048 
updateWorkSource(WorkSource workSource)4049         public void updateWorkSource(WorkSource workSource) {
4050             mWorkSource = copyWorkSource(workSource);
4051         }
4052 
4053         @Override
toString()4054         public String toString() {
4055             StringBuilder sb = new StringBuilder();
4056             sb.append(getLockLevelString());
4057             sb.append(" '");
4058             sb.append(mTag);
4059             sb.append("'");
4060             sb.append(getLockFlagsString());
4061             if (mDisabled) {
4062                 sb.append(" DISABLED");
4063             }
4064             if (mNotifiedAcquired) {
4065                 sb.append(" ACQ=");
4066                 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
4067             }
4068             if (mNotifiedLong) {
4069                 sb.append(" LONG");
4070             }
4071             sb.append(" (uid=");
4072             sb.append(mOwnerUid);
4073             if (mOwnerPid != 0) {
4074                 sb.append(" pid=");
4075                 sb.append(mOwnerPid);
4076             }
4077             if (mWorkSource != null) {
4078                 sb.append(" ws=");
4079                 sb.append(mWorkSource);
4080             }
4081             sb.append(")");
4082             return sb.toString();
4083         }
4084 
writeToProto(ProtoOutputStream proto, long fieldId)4085         public void writeToProto(ProtoOutputStream proto, long fieldId) {
4086             final long wakeLockToken = proto.start(fieldId);
4087             proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
4088             proto.write(WakeLockProto.TAG, mTag);
4089 
4090             final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
4091             proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
4092                     (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
4093             proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
4094                     (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
4095             proto.end(wakeLockFlagsToken);
4096 
4097             proto.write(WakeLockProto.IS_DISABLED, mDisabled);
4098             if (mNotifiedAcquired) {
4099                 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
4100             }
4101             proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
4102             proto.write(WakeLockProto.UID, mOwnerUid);
4103             proto.write(WakeLockProto.PID, mOwnerPid);
4104 
4105             if (mWorkSource != null) {
4106                 mWorkSource.writeToProto(proto, WakeLockProto.WORK_SOURCE);
4107             }
4108             proto.end(wakeLockToken);
4109         }
4110 
4111         @SuppressWarnings("deprecation")
getLockLevelString()4112         private String getLockLevelString() {
4113             switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
4114                 case PowerManager.FULL_WAKE_LOCK:
4115                     return "FULL_WAKE_LOCK                ";
4116                 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
4117                     return "SCREEN_BRIGHT_WAKE_LOCK       ";
4118                 case PowerManager.SCREEN_DIM_WAKE_LOCK:
4119                     return "SCREEN_DIM_WAKE_LOCK          ";
4120                 case PowerManager.PARTIAL_WAKE_LOCK:
4121                     return "PARTIAL_WAKE_LOCK             ";
4122                 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4123                     return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
4124                 case PowerManager.DOZE_WAKE_LOCK:
4125                     return "DOZE_WAKE_LOCK                ";
4126                 case PowerManager.DRAW_WAKE_LOCK:
4127                     return "DRAW_WAKE_LOCK                ";
4128                 default:
4129                     return "???                           ";
4130             }
4131         }
4132 
getLockFlagsString()4133         private String getLockFlagsString() {
4134             String result = "";
4135             if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4136                 result += " ACQUIRE_CAUSES_WAKEUP";
4137             }
4138             if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4139                 result += " ON_AFTER_RELEASE";
4140             }
4141             return result;
4142         }
4143     }
4144 
4145     private final class SuspendBlockerImpl implements SuspendBlocker {
4146         private final String mName;
4147         private final String mTraceName;
4148         private int mReferenceCount;
4149 
SuspendBlockerImpl(String name)4150         public SuspendBlockerImpl(String name) {
4151             mName = name;
4152             mTraceName = "SuspendBlocker (" + name + ")";
4153         }
4154 
4155         @Override
finalize()4156         protected void finalize() throws Throwable {
4157             try {
4158                 if (mReferenceCount != 0) {
4159                     Slog.wtf(TAG, "Suspend blocker \"" + mName
4160                             + "\" was finalized without being released!");
4161                     mReferenceCount = 0;
4162                     mNativeWrapper.nativeReleaseSuspendBlocker(mName);
4163                     Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
4164                 }
4165             } finally {
4166                 super.finalize();
4167             }
4168         }
4169 
4170         @Override
acquire()4171         public void acquire() {
4172             synchronized (this) {
4173                 mReferenceCount += 1;
4174                 if (mReferenceCount == 1) {
4175                     if (DEBUG_SPEW) {
4176                         Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4177                     }
4178                     Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
4179                     mNativeWrapper.nativeAcquireSuspendBlocker(mName);
4180                 }
4181             }
4182         }
4183 
4184         @Override
release()4185         public void release() {
4186             synchronized (this) {
4187                 mReferenceCount -= 1;
4188                 if (mReferenceCount == 0) {
4189                     if (DEBUG_SPEW) {
4190                         Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4191                     }
4192                     mNativeWrapper.nativeReleaseSuspendBlocker(mName);
4193                     Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
4194                 } else if (mReferenceCount < 0) {
4195                     Slog.wtf(TAG, "Suspend blocker \"" + mName
4196                             + "\" was released without being acquired!", new Throwable());
4197                     mReferenceCount = 0;
4198                 }
4199             }
4200         }
4201 
4202         @Override
toString()4203         public String toString() {
4204             synchronized (this) {
4205                 return mName + ": ref count=" + mReferenceCount;
4206             }
4207         }
4208 
writeToProto(ProtoOutputStream proto, long fieldId)4209         public void writeToProto(ProtoOutputStream proto, long fieldId) {
4210             final long sbToken = proto.start(fieldId);
4211             synchronized (this) {
4212                 proto.write(SuspendBlockerProto.NAME, mName);
4213                 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4214             }
4215             proto.end(sbToken);
4216         }
4217     }
4218 
4219     static final class UidState {
4220         final int mUid;
4221         int mNumWakeLocks;
4222         int mProcState;
4223         boolean mActive;
4224 
UidState(int uid)4225         UidState(int uid) {
4226             mUid = uid;
4227         }
4228     }
4229 
4230     @VisibleForTesting
4231     final class BinderService extends IPowerManager.Stub {
4232         @Override
onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)4233         public void onShellCommand(FileDescriptor in, FileDescriptor out,
4234                 FileDescriptor err, String[] args, ShellCallback callback,
4235                 ResultReceiver resultReceiver) {
4236             (new PowerManagerShellCommand(this)).exec(
4237                     this, in, out, err, args, callback, resultReceiver);
4238         }
4239 
4240         @Override // Binder call
acquireWakeLockWithUid(IBinder lock, int flags, String tag, String packageName, int uid)4241         public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4242                 String packageName, int uid) {
4243             if (uid < 0) {
4244                 uid = Binder.getCallingUid();
4245             }
4246             acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
4247         }
4248 
4249         @Override // Binder call
powerHint(int hintId, int data)4250         public void powerHint(int hintId, int data) {
4251             if (!mSystemReady) {
4252                 // Service not ready yet, so who the heck cares about power hints, bah.
4253                 return;
4254             }
4255             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
4256             powerHintInternal(hintId, data);
4257         }
4258 
4259         @Override // Binder call
acquireWakeLock(IBinder lock, int flags, String tag, String packageName, WorkSource ws, String historyTag)4260         public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
4261                 WorkSource ws, String historyTag) {
4262             if (lock == null) {
4263                 throw new IllegalArgumentException("lock must not be null");
4264             }
4265             if (packageName == null) {
4266                 throw new IllegalArgumentException("packageName must not be null");
4267             }
4268             PowerManager.validateWakeLockParameters(flags, tag);
4269 
4270             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4271             if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4272                 mContext.enforceCallingOrSelfPermission(
4273                         android.Manifest.permission.DEVICE_POWER, null);
4274             }
4275             if (ws != null && !ws.isEmpty()) {
4276                 mContext.enforceCallingOrSelfPermission(
4277                         android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4278             } else {
4279                 ws = null;
4280             }
4281 
4282             final int uid = Binder.getCallingUid();
4283             final int pid = Binder.getCallingPid();
4284             final long ident = Binder.clearCallingIdentity();
4285             try {
4286                 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
4287             } finally {
4288                 Binder.restoreCallingIdentity(ident);
4289             }
4290         }
4291 
4292         @Override // Binder call
releaseWakeLock(IBinder lock, int flags)4293         public void releaseWakeLock(IBinder lock, int flags) {
4294             if (lock == null) {
4295                 throw new IllegalArgumentException("lock must not be null");
4296             }
4297 
4298             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4299 
4300             final long ident = Binder.clearCallingIdentity();
4301             try {
4302                 releaseWakeLockInternal(lock, flags);
4303             } finally {
4304                 Binder.restoreCallingIdentity(ident);
4305             }
4306         }
4307 
4308         @Override // Binder call
updateWakeLockUids(IBinder lock, int[] uids)4309         public void updateWakeLockUids(IBinder lock, int[] uids) {
4310             WorkSource ws = null;
4311 
4312             if (uids != null) {
4313                 ws = new WorkSource();
4314                 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4315                 // one at a time?
4316                 for (int i = 0; i < uids.length; i++) {
4317                     ws.add(uids[i]);
4318                 }
4319             }
4320             updateWakeLockWorkSource(lock, ws, null);
4321         }
4322 
4323         @Override // Binder call
updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag)4324         public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
4325             if (lock == null) {
4326                 throw new IllegalArgumentException("lock must not be null");
4327             }
4328 
4329             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4330             if (ws != null && !ws.isEmpty()) {
4331                 mContext.enforceCallingOrSelfPermission(
4332                         android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4333             } else {
4334                 ws = null;
4335             }
4336 
4337             final int callingUid = Binder.getCallingUid();
4338             final long ident = Binder.clearCallingIdentity();
4339             try {
4340                 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
4341             } finally {
4342                 Binder.restoreCallingIdentity(ident);
4343             }
4344         }
4345 
4346         @Override // Binder call
isWakeLockLevelSupported(int level)4347         public boolean isWakeLockLevelSupported(int level) {
4348             final long ident = Binder.clearCallingIdentity();
4349             try {
4350                 return isWakeLockLevelSupportedInternal(level);
4351             } finally {
4352                 Binder.restoreCallingIdentity(ident);
4353             }
4354         }
4355 
4356         @Override // Binder call
userActivity(long eventTime, int event, int flags)4357         public void userActivity(long eventTime, int event, int flags) {
4358             final long now = SystemClock.uptimeMillis();
4359             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
4360                     != PackageManager.PERMISSION_GRANTED
4361                     && mContext.checkCallingOrSelfPermission(
4362                             android.Manifest.permission.USER_ACTIVITY)
4363                             != PackageManager.PERMISSION_GRANTED) {
4364                 // Once upon a time applications could call userActivity().
4365                 // Now we require the DEVICE_POWER permission.  Log a warning and ignore the
4366                 // request instead of throwing a SecurityException so we don't break old apps.
4367                 synchronized (mLock) {
4368                     if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4369                         mLastWarningAboutUserActivityPermission = now;
4370                         Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
4371                                 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4372                                 + "permission.  Please fix your app!  "
4373                                 + " pid=" + Binder.getCallingPid()
4374                                 + " uid=" + Binder.getCallingUid());
4375                     }
4376                 }
4377                 return;
4378             }
4379 
4380             if (eventTime > now) {
4381                 throw new IllegalArgumentException("event time must not be in the future");
4382             }
4383 
4384             final int uid = Binder.getCallingUid();
4385             final long ident = Binder.clearCallingIdentity();
4386             try {
4387                 userActivityInternal(eventTime, event, flags, uid);
4388             } finally {
4389                 Binder.restoreCallingIdentity(ident);
4390             }
4391         }
4392 
4393         @Override // Binder call
wakeUp(long eventTime, @WakeReason int reason, String details, String opPackageName)4394         public void wakeUp(long eventTime, @WakeReason int reason, String details,
4395                 String opPackageName) {
4396             if (eventTime > SystemClock.uptimeMillis()) {
4397                 throw new IllegalArgumentException("event time must not be in the future");
4398             }
4399 
4400             mContext.enforceCallingOrSelfPermission(
4401                     android.Manifest.permission.DEVICE_POWER, null);
4402 
4403             final int uid = Binder.getCallingUid();
4404             final long ident = Binder.clearCallingIdentity();
4405             try {
4406                 wakeUpInternal(eventTime, reason, details, uid, opPackageName, uid);
4407             } finally {
4408                 Binder.restoreCallingIdentity(ident);
4409             }
4410         }
4411 
4412         @Override // Binder call
goToSleep(long eventTime, int reason, int flags)4413         public void goToSleep(long eventTime, int reason, int flags) {
4414             if (eventTime > SystemClock.uptimeMillis()) {
4415                 throw new IllegalArgumentException("event time must not be in the future");
4416             }
4417 
4418             mContext.enforceCallingOrSelfPermission(
4419                     android.Manifest.permission.DEVICE_POWER, null);
4420 
4421             final int uid = Binder.getCallingUid();
4422             final long ident = Binder.clearCallingIdentity();
4423             try {
4424                 goToSleepInternal(eventTime, reason, flags, uid);
4425             } finally {
4426                 Binder.restoreCallingIdentity(ident);
4427             }
4428         }
4429 
4430         @Override // Binder call
nap(long eventTime)4431         public void nap(long eventTime) {
4432             if (eventTime > SystemClock.uptimeMillis()) {
4433                 throw new IllegalArgumentException("event time must not be in the future");
4434             }
4435 
4436             mContext.enforceCallingOrSelfPermission(
4437                     android.Manifest.permission.DEVICE_POWER, null);
4438 
4439             final int uid = Binder.getCallingUid();
4440             final long ident = Binder.clearCallingIdentity();
4441             try {
4442                 napInternal(eventTime, uid);
4443             } finally {
4444                 Binder.restoreCallingIdentity(ident);
4445             }
4446         }
4447 
4448         @Override // Binder call
isInteractive()4449         public boolean isInteractive() {
4450             final long ident = Binder.clearCallingIdentity();
4451             try {
4452                 return isInteractiveInternal();
4453             } finally {
4454                 Binder.restoreCallingIdentity(ident);
4455             }
4456         }
4457 
4458         @Override // Binder call
isPowerSaveMode()4459         public boolean isPowerSaveMode() {
4460             final long ident = Binder.clearCallingIdentity();
4461             try {
4462                 return mBatterySaverController.isEnabled();
4463             } finally {
4464                 Binder.restoreCallingIdentity(ident);
4465             }
4466         }
4467 
4468         // Binder call
getPowerSaveState(@erviceType int serviceType)4469         public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4470             final long ident = Binder.clearCallingIdentity();
4471             try {
4472                 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
4473             } finally {
4474                 Binder.restoreCallingIdentity(ident);
4475             }
4476         }
4477 
4478         @Override // Binder call
setPowerSaveModeEnabled(boolean enabled)4479         public boolean setPowerSaveModeEnabled(boolean enabled) {
4480             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4481                     != PackageManager.PERMISSION_GRANTED) {
4482                 mContext.enforceCallingOrSelfPermission(
4483                         android.Manifest.permission.DEVICE_POWER, null);
4484             }
4485             final long ident = Binder.clearCallingIdentity();
4486             try {
4487                 return setLowPowerModeInternal(enabled);
4488             } finally {
4489                 Binder.restoreCallingIdentity(ident);
4490             }
4491         }
4492 
4493         @Override // Binder call
setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold)4494         public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
4495             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER,
4496                     "updateDynamicPowerSavings");
4497             final long ident = Binder.clearCallingIdentity();
4498             try {
4499                 final ContentResolver resolver = mContext.getContentResolver();
4500                 boolean success = Settings.Global.putInt(resolver,
4501                         Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
4502                         disableThreshold);
4503                 if (success) {
4504                     // abort updating if we weren't able to succeed on the threshold
4505                     success &= Settings.Global.putInt(resolver,
4506                             Settings.Global.DYNAMIC_POWER_SAVINGS_ENABLED,
4507                             powerSaveHint ? 1 : 0);
4508                 }
4509                 return success;
4510             } finally {
4511                 Binder.restoreCallingIdentity(ident);
4512             }
4513         }
4514 
4515         @Override // Binder call
setAdaptivePowerSavePolicy(@onNull BatterySaverPolicyConfig config)4516         public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
4517             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4518                     != PackageManager.PERMISSION_GRANTED) {
4519                 mContext.enforceCallingOrSelfPermission(
4520                         android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSavePolicy");
4521             }
4522             final long ident = Binder.clearCallingIdentity();
4523             try {
4524                 return mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
4525             } finally {
4526                 Binder.restoreCallingIdentity(ident);
4527             }
4528         }
4529 
4530         @Override // Binder call
setAdaptivePowerSaveEnabled(boolean enabled)4531         public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
4532             if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4533                     != PackageManager.PERMISSION_GRANTED) {
4534                 mContext.enforceCallingOrSelfPermission(
4535                         android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSaveEnabled");
4536             }
4537             final long ident = Binder.clearCallingIdentity();
4538             try {
4539                 return mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
4540             } finally {
4541                 Binder.restoreCallingIdentity(ident);
4542             }
4543         }
4544 
4545         @Override // Binder call
getPowerSaveModeTrigger()4546         public int getPowerSaveModeTrigger() {
4547             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER, null);
4548             final long ident = Binder.clearCallingIdentity();
4549             try {
4550                 return Settings.Global.getInt(mContext.getContentResolver(),
4551                         Settings.Global.AUTOMATIC_POWER_SAVE_MODE,
4552                         PowerManager.POWER_SAVE_MODE_TRIGGER_PERCENTAGE);
4553             } finally {
4554                 Binder.restoreCallingIdentity(ident);
4555             }
4556         }
4557 
4558         @Override // Binder call
isDeviceIdleMode()4559         public boolean isDeviceIdleMode() {
4560             final long ident = Binder.clearCallingIdentity();
4561             try {
4562                 return isDeviceIdleModeInternal();
4563             } finally {
4564                 Binder.restoreCallingIdentity(ident);
4565             }
4566         }
4567 
4568         @Override // Binder call
isLightDeviceIdleMode()4569         public boolean isLightDeviceIdleMode() {
4570             final long ident = Binder.clearCallingIdentity();
4571             try {
4572                 return isLightDeviceIdleModeInternal();
4573             } finally {
4574                 Binder.restoreCallingIdentity(ident);
4575             }
4576         }
4577 
4578         /**
4579          * Gets the reason for the last time the phone had to reboot.
4580          *
4581          * @return The reason the phone last shut down as an int or
4582          * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
4583          */
4584         @Override // Binder call
getLastShutdownReason()4585         public int getLastShutdownReason() {
4586             mContext.enforceCallingOrSelfPermission(
4587                     android.Manifest.permission.DEVICE_POWER, null);
4588 
4589             final long ident = Binder.clearCallingIdentity();
4590             try {
4591                 return getLastShutdownReasonInternal(REBOOT_PROPERTY);
4592             } finally {
4593                 Binder.restoreCallingIdentity(ident);
4594             }
4595         }
4596 
4597         @Override // Binder call
getLastSleepReason()4598         public int getLastSleepReason() {
4599             mContext.enforceCallingOrSelfPermission(
4600                     android.Manifest.permission.DEVICE_POWER, null);
4601 
4602             final long ident = Binder.clearCallingIdentity();
4603             try {
4604                 return getLastSleepReasonInternal();
4605             } finally {
4606                 Binder.restoreCallingIdentity(ident);
4607             }
4608         }
4609 
4610         /**
4611          * Reboots the device.
4612          *
4613          * @param confirm If true, shows a reboot confirmation dialog.
4614          * @param reason The reason for the reboot, or null if none.
4615          * @param wait If true, this call waits for the reboot to complete and does not return.
4616          */
4617         @Override // Binder call
reboot(boolean confirm, String reason, boolean wait)4618         public void reboot(boolean confirm, String reason, boolean wait) {
4619             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4620             if (PowerManager.REBOOT_RECOVERY.equals(reason)
4621                     || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
4622                 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
4623             }
4624 
4625             final long ident = Binder.clearCallingIdentity();
4626             try {
4627                 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
4628             } finally {
4629                 Binder.restoreCallingIdentity(ident);
4630             }
4631         }
4632 
4633         /**
4634          * Reboots the device into safe mode
4635          *
4636          * @param confirm If true, shows a reboot confirmation dialog.
4637          * @param wait If true, this call waits for the reboot to complete and does not return.
4638          */
4639         @Override // Binder call
rebootSafeMode(boolean confirm, boolean wait)4640         public void rebootSafeMode(boolean confirm, boolean wait) {
4641             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4642 
4643             final long ident = Binder.clearCallingIdentity();
4644             try {
4645                 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
4646                         PowerManager.REBOOT_SAFE_MODE, wait);
4647             } finally {
4648                 Binder.restoreCallingIdentity(ident);
4649             }
4650         }
4651 
4652         /**
4653          * Shuts down the device.
4654          *
4655          * @param confirm If true, shows a shutdown confirmation dialog.
4656          * @param wait If true, this call waits for the shutdown to complete and does not return.
4657          */
4658         @Override // Binder call
shutdown(boolean confirm, String reason, boolean wait)4659         public void shutdown(boolean confirm, String reason, boolean wait) {
4660             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4661 
4662             final long ident = Binder.clearCallingIdentity();
4663             try {
4664                 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
4665             } finally {
4666                 Binder.restoreCallingIdentity(ident);
4667             }
4668         }
4669 
4670         /**
4671          * Crash the runtime (causing a complete restart of the Android framework).
4672          * Requires REBOOT permission.  Mostly for testing.  Should not return.
4673          */
4674         @Override // Binder call
crash(String message)4675         public void crash(String message) {
4676             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4677 
4678             final long ident = Binder.clearCallingIdentity();
4679             try {
4680                 crashInternal(message);
4681             } finally {
4682                 Binder.restoreCallingIdentity(ident);
4683             }
4684         }
4685 
4686         /**
4687          * Set the setting that determines whether the device stays on when plugged in.
4688          * The argument is a bit string, with each bit specifying a power source that,
4689          * when the device is connected to that source, causes the device to stay on.
4690          * See {@link android.os.BatteryManager} for the list of power sources that
4691          * can be specified. Current values include
4692          * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
4693          * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
4694          *
4695          * Used by "adb shell svc power stayon ..."
4696          *
4697          * @param val an {@code int} containing the bits that specify which power sources
4698          * should cause the device to stay on.
4699          */
4700         @Override // Binder call
setStayOnSetting(int val)4701         public void setStayOnSetting(int val) {
4702             int uid = Binder.getCallingUid();
4703             // if uid is of root's, we permit this operation straight away
4704             if (uid != Process.ROOT_UID) {
4705                 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
4706                         Settings.getPackageNameForUid(mContext, uid), true)) {
4707                     return;
4708                 }
4709             }
4710 
4711             final long ident = Binder.clearCallingIdentity();
4712             try {
4713                 setStayOnSettingInternal(val);
4714             } finally {
4715                 Binder.restoreCallingIdentity(ident);
4716             }
4717         }
4718 
4719         /**
4720          * Used by the phone application to make the attention LED flash when ringing.
4721          */
4722         @Override // Binder call
setAttentionLight(boolean on, int color)4723         public void setAttentionLight(boolean on, int color) {
4724             mContext.enforceCallingOrSelfPermission(
4725                     android.Manifest.permission.DEVICE_POWER, null);
4726 
4727             final long ident = Binder.clearCallingIdentity();
4728             try {
4729                 setAttentionLightInternal(on, color);
4730             } finally {
4731                 Binder.restoreCallingIdentity(ident);
4732             }
4733         }
4734 
4735         @Override // Binder call
setDozeAfterScreenOff(boolean on)4736         public void setDozeAfterScreenOff(boolean on) {
4737             mContext.enforceCallingOrSelfPermission(
4738                     android.Manifest.permission.DEVICE_POWER, null);
4739 
4740             final long ident = Binder.clearCallingIdentity();
4741             try {
4742                 setDozeAfterScreenOffInternal(on);
4743             } finally {
4744                 Binder.restoreCallingIdentity(ident);
4745             }
4746         }
4747 
4748         @Override // Binder call
boostScreenBrightness(long eventTime)4749         public void boostScreenBrightness(long eventTime) {
4750             if (eventTime > SystemClock.uptimeMillis()) {
4751                 throw new IllegalArgumentException("event time must not be in the future");
4752             }
4753 
4754             mContext.enforceCallingOrSelfPermission(
4755                     android.Manifest.permission.DEVICE_POWER, null);
4756 
4757             final int uid = Binder.getCallingUid();
4758             final long ident = Binder.clearCallingIdentity();
4759             try {
4760                 boostScreenBrightnessInternal(eventTime, uid);
4761             } finally {
4762                 Binder.restoreCallingIdentity(ident);
4763             }
4764         }
4765 
4766         @Override // Binder call
isScreenBrightnessBoosted()4767         public boolean isScreenBrightnessBoosted() {
4768             final long ident = Binder.clearCallingIdentity();
4769             try {
4770                 return isScreenBrightnessBoostedInternal();
4771             } finally {
4772                 Binder.restoreCallingIdentity(ident);
4773             }
4774         }
4775 
4776         @Override // binder call
forceSuspend()4777         public boolean forceSuspend() {
4778             mContext.enforceCallingOrSelfPermission(
4779                     android.Manifest.permission.DEVICE_POWER, null);
4780 
4781             final int uid = Binder.getCallingUid();
4782             final long ident = Binder.clearCallingIdentity();
4783             try {
4784                 return forceSuspendInternal(uid);
4785             } finally {
4786                 Binder.restoreCallingIdentity(ident);
4787             }
4788         }
4789 
4790         @Override // Binder call
dump(FileDescriptor fd, PrintWriter pw, String[] args)4791         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4792             if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
4793 
4794             final long ident = Binder.clearCallingIdentity();
4795 
4796             boolean isDumpProto = false;
4797             for (String arg : args) {
4798                 if (arg.equals("--proto")) {
4799                     isDumpProto = true;
4800                 }
4801             }
4802             try {
4803                 if (isDumpProto) {
4804                     dumpProto(fd);
4805                 } else {
4806                     dumpInternal(pw);
4807                 }
4808             } finally {
4809                 Binder.restoreCallingIdentity(ident);
4810             }
4811         }
4812     }
4813 
4814     @VisibleForTesting
getBinderServiceInstance()4815     BinderService getBinderServiceInstance() {
4816         return mBinderService;
4817     }
4818 
4819     @VisibleForTesting
getLocalServiceInstance()4820     LocalService getLocalServiceInstance() {
4821         return mLocalService;
4822     }
4823 
4824     @VisibleForTesting
4825     // lastRebootReasonProperty argument to permit testing
getLastShutdownReasonInternal(String lastRebootReasonProperty)4826     int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
4827         String line = SystemProperties.get(lastRebootReasonProperty);
4828         if (line == null) {
4829             return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4830         }
4831         switch (line) {
4832             case REASON_SHUTDOWN:
4833                 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
4834             case REASON_REBOOT:
4835                 return PowerManager.SHUTDOWN_REASON_REBOOT;
4836             case REASON_USERREQUESTED:
4837                 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
4838             case REASON_THERMAL_SHUTDOWN:
4839                 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
4840             case REASON_LOW_BATTERY:
4841                 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
4842             case REASON_BATTERY_THERMAL_STATE:
4843                 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
4844             default:
4845                 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4846         }
4847     }
4848 
getLastSleepReasonInternal()4849     private int getLastSleepReasonInternal() {
4850         synchronized (mLock) {
4851             return mLastSleepReason;
4852         }
4853     }
4854 
getLastWakeupInternal()4855     private PowerManager.WakeData getLastWakeupInternal() {
4856         synchronized (mLock) {
4857             return new WakeData(mLastWakeTime, mLastWakeReason);
4858         }
4859     }
4860 
4861     private final class LocalService extends PowerManagerInternal {
4862         @Override
setScreenBrightnessOverrideFromWindowManager(int screenBrightness)4863         public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
4864             if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4865                     || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4866                 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
4867             }
4868             setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
4869         }
4870 
4871         @Override
setDozeOverrideFromDreamManager(int screenState, int screenBrightness)4872         public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
4873             switch (screenState) {
4874                 case Display.STATE_UNKNOWN:
4875                 case Display.STATE_OFF:
4876                 case Display.STATE_DOZE:
4877                 case Display.STATE_DOZE_SUSPEND:
4878                 case Display.STATE_ON_SUSPEND:
4879                 case Display.STATE_ON:
4880                 case Display.STATE_VR:
4881                     break;
4882                 default:
4883                     screenState = Display.STATE_UNKNOWN;
4884                     break;
4885             }
4886             if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4887                     || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4888                 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
4889             }
4890             setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
4891         }
4892 
4893         @Override
setUserInactiveOverrideFromWindowManager()4894         public void setUserInactiveOverrideFromWindowManager() {
4895             setUserInactiveOverrideFromWindowManagerInternal();
4896         }
4897 
4898         @Override
setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis)4899         public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
4900             setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
4901         }
4902 
4903         @Override
setDrawWakeLockOverrideFromSidekick(boolean keepState)4904         public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
4905             setDrawWakeLockOverrideFromSidekickInternal(keepState);
4906         }
4907 
4908         @Override
setMaximumScreenOffTimeoutFromDeviceAdmin(@serIdInt int userId, long timeMs)4909         public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
4910             setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
4911         }
4912 
4913         @Override
getLowPowerState(@erviceType int serviceType)4914         public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
4915             return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
4916         }
4917 
4918         @Override
registerLowPowerModeObserver(LowPowerModeListener listener)4919         public void registerLowPowerModeObserver(LowPowerModeListener listener) {
4920             mBatterySaverController.addListener(listener);
4921         }
4922 
4923         @Override
setDeviceIdleMode(boolean enabled)4924         public boolean setDeviceIdleMode(boolean enabled) {
4925             return setDeviceIdleModeInternal(enabled);
4926         }
4927 
4928         @Override
setLightDeviceIdleMode(boolean enabled)4929         public boolean setLightDeviceIdleMode(boolean enabled) {
4930             return setLightDeviceIdleModeInternal(enabled);
4931         }
4932 
4933         @Override
setDeviceIdleWhitelist(int[] appids)4934         public void setDeviceIdleWhitelist(int[] appids) {
4935             setDeviceIdleWhitelistInternal(appids);
4936         }
4937 
4938         @Override
setDeviceIdleTempWhitelist(int[] appids)4939         public void setDeviceIdleTempWhitelist(int[] appids) {
4940             setDeviceIdleTempWhitelistInternal(appids);
4941         }
4942 
4943         @Override
startUidChanges()4944         public void startUidChanges() {
4945             startUidChangesInternal();
4946         }
4947 
4948         @Override
finishUidChanges()4949         public void finishUidChanges() {
4950             finishUidChangesInternal();
4951         }
4952 
4953         @Override
updateUidProcState(int uid, int procState)4954         public void updateUidProcState(int uid, int procState) {
4955             updateUidProcStateInternal(uid, procState);
4956         }
4957 
4958         @Override
uidGone(int uid)4959         public void uidGone(int uid) {
4960             uidGoneInternal(uid);
4961         }
4962 
4963         @Override
uidActive(int uid)4964         public void uidActive(int uid) {
4965             uidActiveInternal(uid);
4966         }
4967 
4968         @Override
uidIdle(int uid)4969         public void uidIdle(int uid) {
4970             uidIdleInternal(uid);
4971         }
4972 
4973         @Override
powerHint(int hintId, int data)4974         public void powerHint(int hintId, int data) {
4975             powerHintInternal(hintId, data);
4976         }
4977 
4978         @Override
wasDeviceIdleFor(long ms)4979         public boolean wasDeviceIdleFor(long ms) {
4980             return wasDeviceIdleForInternal(ms);
4981         }
4982 
4983         @Override
getLastWakeup()4984         public WakeData getLastWakeup() {
4985             return getLastWakeupInternal();
4986         }
4987     }
4988 }
4989