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