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