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