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