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