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