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