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.net.Uri; 35 import android.os.BatteryManager; 36 import android.os.BatteryManagerInternal; 37 import android.os.Binder; 38 import android.os.Handler; 39 import android.os.IBinder; 40 import android.os.IPowerManager; 41 import android.os.Looper; 42 import android.os.Message; 43 import android.os.PowerManager; 44 import android.os.PowerManagerInternal; 45 import android.os.Process; 46 import android.os.RemoteException; 47 import android.os.SystemClock; 48 import android.os.SystemProperties; 49 import android.os.Trace; 50 import android.os.UserHandle; 51 import android.os.WorkSource; 52 import android.provider.Settings; 53 import android.provider.Settings.Secure; 54 import android.provider.Settings.SettingNotFoundException; 55 import android.service.dreams.DreamManagerInternal; 56 import android.service.vr.IVrManager; 57 import android.service.vr.IVrStateCallbacks; 58 import android.util.EventLog; 59 import android.util.Slog; 60 import android.util.SparseIntArray; 61 import android.util.TimeUtils; 62 import android.view.Display; 63 import android.view.WindowManagerPolicy; 64 65 import com.android.internal.app.IAppOpsService; 66 import com.android.internal.app.IBatteryStats; 67 import com.android.internal.os.BackgroundThread; 68 import com.android.internal.util.ArrayUtils; 69 import com.android.server.EventLogTags; 70 import com.android.server.ServiceThread; 71 import com.android.server.SystemService; 72 import com.android.server.Watchdog; 73 import com.android.server.am.BatteryStatsService; 74 import com.android.server.lights.Light; 75 import com.android.server.lights.LightsManager; 76 import com.android.server.vr.VrManagerInternal; 77 import com.android.server.vr.VrManagerService; 78 import com.android.server.vr.VrStateListener; 79 import libcore.util.Objects; 80 81 import java.io.FileDescriptor; 82 import java.io.PrintWriter; 83 import java.lang.annotation.Retention; 84 import java.lang.annotation.RetentionPolicy; 85 import java.util.ArrayList; 86 import java.util.Arrays; 87 88 import static android.os.PowerManagerInternal.POWER_HINT_INTERACTION; 89 import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP; 90 import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE; 91 import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING; 92 import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING; 93 94 /** 95 * The power manager service is responsible for coordinating power management 96 * functions on the device. 97 */ 98 public final class PowerManagerService extends SystemService 99 implements Watchdog.Monitor { 100 private static final String TAG = "PowerManagerService"; 101 102 private static final boolean DEBUG = false; 103 private static final boolean DEBUG_SPEW = DEBUG && true; 104 105 // Message: Sent when a user activity timeout occurs to update the power state. 106 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1; 107 // Message: Sent when the device enters or exits a dreaming or dozing state. 108 private static final int MSG_SANDMAN = 2; 109 // Message: Sent when the screen brightness boost expires. 110 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3; 111 112 // Dirty bit: mWakeLocks changed 113 private static final int DIRTY_WAKE_LOCKS = 1 << 0; 114 // Dirty bit: mWakefulness changed 115 private static final int DIRTY_WAKEFULNESS = 1 << 1; 116 // Dirty bit: user activity was poked or may have timed out 117 private static final int DIRTY_USER_ACTIVITY = 1 << 2; 118 // Dirty bit: actual display power state was updated asynchronously 119 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3; 120 // Dirty bit: mBootCompleted changed 121 private static final int DIRTY_BOOT_COMPLETED = 1 << 4; 122 // Dirty bit: settings changed 123 private static final int DIRTY_SETTINGS = 1 << 5; 124 // Dirty bit: mIsPowered changed 125 private static final int DIRTY_IS_POWERED = 1 << 6; 126 // Dirty bit: mStayOn changed 127 private static final int DIRTY_STAY_ON = 1 << 7; 128 // Dirty bit: battery state changed 129 private static final int DIRTY_BATTERY_STATE = 1 << 8; 130 // Dirty bit: proximity state changed 131 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9; 132 // Dirty bit: dock state changed 133 private static final int DIRTY_DOCK_STATE = 1 << 10; 134 // Dirty bit: brightness boost changed 135 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11; 136 137 // Summarizes the state of all active wakelocks. 138 private static final int WAKE_LOCK_CPU = 1 << 0; 139 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1; 140 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2; 141 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3; 142 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4; 143 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake 144 private static final int WAKE_LOCK_DOZE = 1 << 6; 145 private static final int WAKE_LOCK_DRAW = 1 << 7; 146 147 // Summarizes the user activity state. 148 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0; 149 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1; 150 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2; 151 152 // Default timeout in milliseconds. This is only used until the settings 153 // provider populates the actual default value (R.integer.def_screen_off_timeout). 154 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000; 155 private static final int DEFAULT_SLEEP_TIMEOUT = -1; 156 157 // Screen brightness boost timeout. 158 // Hardcoded for now until we decide what the right policy should be. 159 // This should perhaps be a setting. 160 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000; 161 162 // Power hints defined in hardware/libhardware/include/hardware/power.h. 163 private static final int POWER_HINT_LOW_POWER = 5; 164 private static final int POWER_HINT_VR_MODE = 7; 165 166 // Power features defined in hardware/libhardware/include/hardware/power.h. 167 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1; 168 169 // Default setting for double tap to wake. 170 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0; 171 172 /** Constants for {@link #shutdownOrRebootInternal} */ 173 @Retention(RetentionPolicy.SOURCE) 174 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE}) 175 public @interface HaltMode {} 176 private static final int HALT_MODE_SHUTDOWN = 0; 177 private static final int HALT_MODE_REBOOT = 1; 178 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2; 179 180 private final Context mContext; 181 private final ServiceThread mHandlerThread; 182 private final PowerManagerHandler mHandler; 183 184 private LightsManager mLightsManager; 185 private BatteryManagerInternal mBatteryManagerInternal; 186 private DisplayManagerInternal mDisplayManagerInternal; 187 private IBatteryStats mBatteryStats; 188 private IAppOpsService mAppOps; 189 private WindowManagerPolicy mPolicy; 190 private Notifier mNotifier; 191 private WirelessChargerDetector mWirelessChargerDetector; 192 private SettingsObserver mSettingsObserver; 193 private DreamManagerInternal mDreamManager; 194 private Light mAttentionLight; 195 196 private final Object mLock = new Object(); 197 198 // A bitfield that indicates what parts of the power state have 199 // changed and need to be recalculated. 200 private int mDirty; 201 202 // Indicates whether the device is awake or asleep or somewhere in between. 203 // This is distinct from the screen power state, which is managed separately. 204 private int mWakefulness; 205 private boolean mWakefulnessChanging; 206 207 // True if the sandman has just been summoned for the first time since entering the 208 // dreaming or dozing state. Indicates whether a new dream should begin. 209 private boolean mSandmanSummoned; 210 211 // True if MSG_SANDMAN has been scheduled. 212 private boolean mSandmanScheduled; 213 214 // Table of all suspend blockers. 215 // There should only be a few of these. 216 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>(); 217 218 // Table of all wake locks acquired by applications. 219 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>(); 220 221 // A bitfield that summarizes the state of all active wakelocks. 222 private int mWakeLockSummary; 223 224 // If true, instructs the display controller to wait for the proximity sensor to 225 // go negative before turning the screen on. 226 private boolean mRequestWaitForNegativeProximity; 227 228 // Timestamp of the last time the device was awoken or put to sleep. 229 private long mLastWakeTime; 230 private long mLastSleepTime; 231 232 // Timestamp of the last call to user activity. 233 private long mLastUserActivityTime; 234 private long mLastUserActivityTimeNoChangeLights; 235 236 // Timestamp of last interactive power hint. 237 private long mLastInteractivePowerHintTime; 238 239 // Timestamp of the last screen brightness boost. 240 private long mLastScreenBrightnessBoostTime; 241 private boolean mScreenBrightnessBoostInProgress; 242 243 // A bitfield that summarizes the effect of the user activity timer. 244 private int mUserActivitySummary; 245 246 // The desired display power state. The actual state may lag behind the 247 // requested because it is updated asynchronously by the display power controller. 248 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest(); 249 250 // True if the display power state has been fully applied, which means the display 251 // is actually on or actually off or whatever was requested. 252 private boolean mDisplayReady; 253 254 // The suspend blocker used to keep the CPU alive when an application has acquired 255 // a wake lock. 256 private final SuspendBlocker mWakeLockSuspendBlocker; 257 258 // True if the wake lock suspend blocker has been acquired. 259 private boolean mHoldingWakeLockSuspendBlocker; 260 261 // The suspend blocker used to keep the CPU alive when the display is on, the 262 // display is getting ready or there is user activity (in which case the display 263 // must be on). 264 private final SuspendBlocker mDisplaySuspendBlocker; 265 266 // True if the display suspend blocker has been acquired. 267 private boolean mHoldingDisplaySuspendBlocker; 268 269 // True if systemReady() has been called. 270 private boolean mSystemReady; 271 272 // True if boot completed occurred. We keep the screen on until this happens. 273 private boolean mBootCompleted; 274 275 // Runnables that should be triggered on boot completed 276 private Runnable[] mBootCompletedRunnables; 277 278 // True if auto-suspend mode is enabled. 279 // Refer to autosuspend.h. 280 private boolean mHalAutoSuspendModeEnabled; 281 282 // True if interactive mode is enabled. 283 // Refer to power.h. 284 private boolean mHalInteractiveModeEnabled; 285 286 // True if the device is plugged into a power source. 287 private boolean mIsPowered; 288 289 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS. 290 private int mPlugType; 291 292 // The current battery level percentage. 293 private int mBatteryLevel; 294 295 // The battery level percentage at the time the dream started. 296 // This is used to terminate a dream and go to sleep if the battery is 297 // draining faster than it is charging and the user activity timeout has expired. 298 private int mBatteryLevelWhenDreamStarted; 299 300 // The current dock state. 301 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; 302 303 // True to decouple auto-suspend mode from the display state. 304 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig; 305 306 // True to decouple interactive mode from the display state. 307 private boolean mDecoupleHalInteractiveModeFromDisplayConfig; 308 309 // True if the device should wake up when plugged or unplugged. 310 private boolean mWakeUpWhenPluggedOrUnpluggedConfig; 311 312 // True if the device should wake up when plugged or unplugged in theater mode. 313 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig; 314 315 // True if the device should suspend when the screen is off due to proximity. 316 private boolean mSuspendWhenScreenOffDueToProximityConfig; 317 318 // True if dreams are supported on this device. 319 private boolean mDreamsSupportedConfig; 320 321 // Default value for dreams enabled 322 private boolean mDreamsEnabledByDefaultConfig; 323 324 // Default value for dreams activate-on-sleep 325 private boolean mDreamsActivatedOnSleepByDefaultConfig; 326 327 // Default value for dreams activate-on-dock 328 private boolean mDreamsActivatedOnDockByDefaultConfig; 329 330 // True if dreams can run while not plugged in. 331 private boolean mDreamsEnabledOnBatteryConfig; 332 333 // Minimum battery level to allow dreaming when powered. 334 // Use -1 to disable this safety feature. 335 private int mDreamsBatteryLevelMinimumWhenPoweredConfig; 336 337 // Minimum battery level to allow dreaming when not powered. 338 // Use -1 to disable this safety feature. 339 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig; 340 341 // If the battery level drops by this percentage and the user activity timeout 342 // has expired, then assume the device is receiving insufficient current to charge 343 // effectively and terminate the dream. Use -1 to disable this safety feature. 344 private int mDreamsBatteryLevelDrainCutoffConfig; 345 346 // True if dreams are enabled by the user. 347 private boolean mDreamsEnabledSetting; 348 349 // True if dreams should be activated on sleep. 350 private boolean mDreamsActivateOnSleepSetting; 351 352 // True if dreams should be activated on dock. 353 private boolean mDreamsActivateOnDockSetting; 354 355 // True if doze should not be started until after the screen off transition. 356 private boolean mDozeAfterScreenOffConfig; 357 358 // The minimum screen off timeout, in milliseconds. 359 private int mMinimumScreenOffTimeoutConfig; 360 361 // The screen dim duration, in milliseconds. 362 // This is subtracted from the end of the screen off timeout so the 363 // minimum screen off timeout should be longer than this. 364 private int mMaximumScreenDimDurationConfig; 365 366 // The maximum screen dim time expressed as a ratio relative to the screen 367 // off timeout. If the screen off timeout is very short then we want the 368 // dim timeout to also be quite short so that most of the time is spent on. 369 // Otherwise the user won't get much screen on time before dimming occurs. 370 private float mMaximumScreenDimRatioConfig; 371 372 // Whether device supports double tap to wake. 373 private boolean mSupportsDoubleTapWakeConfig; 374 375 // The screen off timeout setting value in milliseconds. 376 private int mScreenOffTimeoutSetting; 377 378 // The sleep timeout setting value in milliseconds. 379 private int mSleepTimeoutSetting; 380 381 // The maximum allowable screen off timeout according to the device 382 // administration policy. Overrides other settings. 383 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE; 384 385 // The stay on while plugged in setting. 386 // A bitfield of battery conditions under which to make the screen stay on. 387 private int mStayOnWhilePluggedInSetting; 388 389 // True if the device should stay on. 390 private boolean mStayOn; 391 392 // True if the proximity sensor reads a positive result. 393 private boolean mProximityPositive; 394 395 // Screen brightness setting limits. 396 private int mScreenBrightnessSettingMinimum; 397 private int mScreenBrightnessSettingMaximum; 398 private int mScreenBrightnessSettingDefault; 399 400 // The screen brightness setting, from 0 to 255. 401 // Use -1 if no value has been set. 402 private int mScreenBrightnessSetting; 403 404 // The screen auto-brightness adjustment setting, from -1 to 1. 405 // Use 0 if there is no adjustment. 406 private float mScreenAutoBrightnessAdjustmentSetting; 407 408 // The screen brightness mode. 409 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants. 410 private int mScreenBrightnessModeSetting; 411 412 // The screen brightness setting override from the window manager 413 // to allow the current foreground activity to override the brightness. 414 // Use -1 to disable. 415 private int mScreenBrightnessOverrideFromWindowManager = -1; 416 417 // The window manager has determined the user to be inactive via other means. 418 // Set this to false to disable. 419 private boolean mUserInactiveOverrideFromWindowManager; 420 421 // The next possible user activity timeout after being explicitly told the user is inactive. 422 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep. 423 private long mOverriddenTimeout = -1; 424 425 // The user activity timeout override from the window manager 426 // to allow the current foreground activity to override the user activity timeout. 427 // Use -1 to disable. 428 private long mUserActivityTimeoutOverrideFromWindowManager = -1; 429 430 // The screen brightness setting override from the settings application 431 // to temporarily adjust the brightness until next updated, 432 // Use -1 to disable. 433 private int mTemporaryScreenBrightnessSettingOverride = -1; 434 435 // The screen brightness adjustment setting override from the settings 436 // application to temporarily adjust the auto-brightness adjustment factor 437 // until next updated, in the range -1..1. 438 // Use NaN to disable. 439 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 440 441 // The screen state to use while dozing. 442 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN; 443 444 // The screen brightness to use while dozing. 445 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT; 446 447 // Time when we last logged a warning about calling userActivity() without permission. 448 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE; 449 450 // If true, the device is in low power mode. 451 private boolean mLowPowerModeEnabled; 452 453 // Current state of the low power mode setting. 454 private boolean mLowPowerModeSetting; 455 456 // Current state of whether the settings are allowing auto low power mode. 457 private boolean mAutoLowPowerModeConfigured; 458 459 // The user turned off low power mode below the trigger level 460 private boolean mAutoLowPowerModeSnoozing; 461 462 // True if the battery level is currently considered low. 463 private boolean mBatteryLevelLow; 464 465 // True if we are currently in device idle mode. 466 private boolean mDeviceIdleMode; 467 468 // True if we are currently in light device idle mode. 469 private boolean mLightDeviceIdleMode; 470 471 // Set of app ids that we will always respect the wake locks for. 472 int[] mDeviceIdleWhitelist = new int[0]; 473 474 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message 475 int[] mDeviceIdleTempWhitelist = new int[0]; 476 477 private final SparseIntArray mUidState = new SparseIntArray(); 478 479 // True if theater mode is enabled 480 private boolean mTheaterModeEnabled; 481 482 // True if double tap to wake is enabled 483 private boolean mDoubleTapWakeEnabled; 484 485 private final ArrayList<PowerManagerInternal.LowPowerModeListener> mLowPowerModeListeners 486 = new ArrayList<PowerManagerInternal.LowPowerModeListener>(); 487 488 // True if brightness should be affected by twilight. 489 private boolean mBrightnessUseTwilight; 490 491 private native void nativeInit(); 492 493 private static native void nativeAcquireSuspendBlocker(String name); 494 private static native void nativeReleaseSuspendBlocker(String name); 495 private static native void nativeSetInteractive(boolean enable); 496 private static native void nativeSetAutoSuspend(boolean enable); 497 private static native void nativeSendPowerHint(int hintId, int data); 498 private static native void nativeSetFeature(int featureId, int data); 499 500 public PowerManagerService(Context context) { 501 super(context); 502 mContext = context; 503 mHandlerThread = new ServiceThread(TAG, 504 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/); 505 mHandlerThread.start(); 506 mHandler = new PowerManagerHandler(mHandlerThread.getLooper()); 507 508 synchronized (mLock) { 509 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks"); 510 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display"); 511 mDisplaySuspendBlocker.acquire(); 512 mHoldingDisplaySuspendBlocker = true; 513 mHalAutoSuspendModeEnabled = false; 514 mHalInteractiveModeEnabled = true; 515 516 mWakefulness = WAKEFULNESS_AWAKE; 517 518 nativeInit(); 519 nativeSetAutoSuspend(false); 520 nativeSetInteractive(true); 521 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0); 522 } 523 } 524 525 @Override 526 public void onStart() { 527 publishBinderService(Context.POWER_SERVICE, new BinderService()); 528 publishLocalService(PowerManagerInternal.class, new LocalService()); 529 530 Watchdog.getInstance().addMonitor(this); 531 Watchdog.getInstance().addThread(mHandler); 532 } 533 534 @Override 535 public void onBootPhase(int phase) { 536 synchronized (mLock) { 537 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { 538 incrementBootCount(); 539 540 } else if (phase == PHASE_BOOT_COMPLETED) { 541 final long now = SystemClock.uptimeMillis(); 542 mBootCompleted = true; 543 mDirty |= DIRTY_BOOT_COMPLETED; 544 userActivityNoUpdateLocked( 545 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 546 updatePowerStateLocked(); 547 548 if (!ArrayUtils.isEmpty(mBootCompletedRunnables)) { 549 Slog.d(TAG, "Posting " + mBootCompletedRunnables.length + " delayed runnables"); 550 for (Runnable r : mBootCompletedRunnables) { 551 BackgroundThread.getHandler().post(r); 552 } 553 } 554 mBootCompletedRunnables = null; 555 } 556 } 557 } 558 559 public void systemReady(IAppOpsService appOps) { 560 synchronized (mLock) { 561 mSystemReady = true; 562 mAppOps = appOps; 563 mDreamManager = getLocalService(DreamManagerInternal.class); 564 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class); 565 mPolicy = getLocalService(WindowManagerPolicy.class); 566 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class); 567 568 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); 569 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting(); 570 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting(); 571 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting(); 572 573 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper()); 574 575 // The notifier runs on the system server's main looper so as not to interfere 576 // with the animations and other critical functions of the power manager. 577 mBatteryStats = BatteryStatsService.getService(); 578 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats, 579 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"), 580 mPolicy); 581 582 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager, 583 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"), 584 mHandler); 585 mSettingsObserver = new SettingsObserver(mHandler); 586 587 mLightsManager = getLocalService(LightsManager.class); 588 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION); 589 590 // Initialize display power management. 591 mDisplayManagerInternal.initPowerManagement( 592 mDisplayPowerCallbacks, mHandler, sensorManager); 593 594 // Register for broadcasts from other components of the system. 595 IntentFilter filter = new IntentFilter(); 596 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 597 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 598 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler); 599 600 filter = new IntentFilter(); 601 filter.addAction(Intent.ACTION_DREAMING_STARTED); 602 filter.addAction(Intent.ACTION_DREAMING_STOPPED); 603 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler); 604 605 filter = new IntentFilter(); 606 filter.addAction(Intent.ACTION_USER_SWITCHED); 607 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler); 608 609 filter = new IntentFilter(); 610 filter.addAction(Intent.ACTION_DOCK_EVENT); 611 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler); 612 613 // Register for settings changes. 614 final ContentResolver resolver = mContext.getContentResolver(); 615 resolver.registerContentObserver(Settings.Secure.getUriFor( 616 Settings.Secure.SCREENSAVER_ENABLED), 617 false, mSettingsObserver, UserHandle.USER_ALL); 618 resolver.registerContentObserver(Settings.Secure.getUriFor( 619 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP), 620 false, mSettingsObserver, UserHandle.USER_ALL); 621 resolver.registerContentObserver(Settings.Secure.getUriFor( 622 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK), 623 false, mSettingsObserver, UserHandle.USER_ALL); 624 resolver.registerContentObserver(Settings.System.getUriFor( 625 Settings.System.SCREEN_OFF_TIMEOUT), 626 false, mSettingsObserver, UserHandle.USER_ALL); 627 resolver.registerContentObserver(Settings.Secure.getUriFor( 628 Settings.Secure.SLEEP_TIMEOUT), 629 false, mSettingsObserver, UserHandle.USER_ALL); 630 resolver.registerContentObserver(Settings.Global.getUriFor( 631 Settings.Global.STAY_ON_WHILE_PLUGGED_IN), 632 false, mSettingsObserver, UserHandle.USER_ALL); 633 resolver.registerContentObserver(Settings.System.getUriFor( 634 Settings.System.SCREEN_BRIGHTNESS), 635 false, mSettingsObserver, UserHandle.USER_ALL); 636 resolver.registerContentObserver(Settings.System.getUriFor( 637 Settings.System.SCREEN_BRIGHTNESS_MODE), 638 false, mSettingsObserver, UserHandle.USER_ALL); 639 resolver.registerContentObserver(Settings.System.getUriFor( 640 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ), 641 false, mSettingsObserver, UserHandle.USER_ALL); 642 resolver.registerContentObserver(Settings.Global.getUriFor( 643 Settings.Global.LOW_POWER_MODE), 644 false, mSettingsObserver, UserHandle.USER_ALL); 645 resolver.registerContentObserver(Settings.Global.getUriFor( 646 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL), 647 false, mSettingsObserver, UserHandle.USER_ALL); 648 resolver.registerContentObserver(Settings.Global.getUriFor( 649 Settings.Global.THEATER_MODE_ON), 650 false, mSettingsObserver, UserHandle.USER_ALL); 651 resolver.registerContentObserver(Settings.Secure.getUriFor( 652 Settings.Secure.DOUBLE_TAP_TO_WAKE), 653 false, mSettingsObserver, UserHandle.USER_ALL); 654 resolver.registerContentObserver(Settings.Secure.getUriFor( 655 Secure.BRIGHTNESS_USE_TWILIGHT), 656 false, mSettingsObserver, UserHandle.USER_ALL); 657 IVrManager vrManager = 658 (IVrManager) getBinderService(VrManagerService.VR_MANAGER_BINDER_SERVICE); 659 try { 660 vrManager.registerListener(mVrStateCallbacks); 661 } catch (RemoteException e) { 662 Slog.e(TAG, "Failed to register VR mode state listener: " + e); 663 } 664 // Go. 665 readConfigurationLocked(); 666 updateSettingsLocked(); 667 mDirty |= DIRTY_BATTERY_STATE; 668 updatePowerStateLocked(); 669 } 670 } 671 672 private void readConfigurationLocked() { 673 final Resources resources = mContext.getResources(); 674 675 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean( 676 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay); 677 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean( 678 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay); 679 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean( 680 com.android.internal.R.bool.config_unplugTurnsOnScreen); 681 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean( 682 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug); 683 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean( 684 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity); 685 mDreamsSupportedConfig = resources.getBoolean( 686 com.android.internal.R.bool.config_dreamsSupported); 687 mDreamsEnabledByDefaultConfig = resources.getBoolean( 688 com.android.internal.R.bool.config_dreamsEnabledByDefault); 689 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean( 690 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault); 691 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean( 692 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault); 693 mDreamsEnabledOnBatteryConfig = resources.getBoolean( 694 com.android.internal.R.bool.config_dreamsEnabledOnBattery); 695 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger( 696 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered); 697 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger( 698 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered); 699 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger( 700 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff); 701 mDozeAfterScreenOffConfig = resources.getBoolean( 702 com.android.internal.R.bool.config_dozeAfterScreenOff); 703 mMinimumScreenOffTimeoutConfig = resources.getInteger( 704 com.android.internal.R.integer.config_minimumScreenOffTimeout); 705 mMaximumScreenDimDurationConfig = resources.getInteger( 706 com.android.internal.R.integer.config_maximumScreenDimDuration); 707 mMaximumScreenDimRatioConfig = resources.getFraction( 708 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1); 709 mSupportsDoubleTapWakeConfig = resources.getBoolean( 710 com.android.internal.R.bool.config_supportDoubleTapWake); 711 } 712 713 private void updateSettingsLocked() { 714 final ContentResolver resolver = mContext.getContentResolver(); 715 716 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver, 717 Settings.Secure.SCREENSAVER_ENABLED, 718 mDreamsEnabledByDefaultConfig ? 1 : 0, 719 UserHandle.USER_CURRENT) != 0); 720 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver, 721 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 722 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0, 723 UserHandle.USER_CURRENT) != 0); 724 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver, 725 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK, 726 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0, 727 UserHandle.USER_CURRENT) != 0); 728 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver, 729 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT, 730 UserHandle.USER_CURRENT); 731 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver, 732 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT, 733 UserHandle.USER_CURRENT); 734 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver, 735 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC); 736 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(), 737 Settings.Global.THEATER_MODE_ON, 0) == 1; 738 739 if (mSupportsDoubleTapWakeConfig) { 740 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver, 741 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE, 742 UserHandle.USER_CURRENT) != 0; 743 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) { 744 mDoubleTapWakeEnabled = doubleTapWakeEnabled; 745 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0); 746 } 747 } 748 749 final int oldScreenBrightnessSetting = mScreenBrightnessSetting; 750 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver, 751 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault, 752 UserHandle.USER_CURRENT); 753 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) { 754 mTemporaryScreenBrightnessSettingOverride = -1; 755 } 756 757 final float oldScreenAutoBrightnessAdjustmentSetting = 758 mScreenAutoBrightnessAdjustmentSetting; 759 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver, 760 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f, 761 UserHandle.USER_CURRENT); 762 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) { 763 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 764 } 765 766 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver, 767 Settings.System.SCREEN_BRIGHTNESS_MODE, 768 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT); 769 770 mBrightnessUseTwilight = Settings.Secure.getIntForUser(resolver, 771 Secure.BRIGHTNESS_USE_TWILIGHT, 0, UserHandle.USER_CURRENT) != 0; 772 773 final boolean lowPowerModeEnabled = Settings.Global.getInt(resolver, 774 Settings.Global.LOW_POWER_MODE, 0) != 0; 775 final boolean autoLowPowerModeConfigured = Settings.Global.getInt(resolver, 776 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0) != 0; 777 if (lowPowerModeEnabled != mLowPowerModeSetting 778 || autoLowPowerModeConfigured != mAutoLowPowerModeConfigured) { 779 mLowPowerModeSetting = lowPowerModeEnabled; 780 mAutoLowPowerModeConfigured = autoLowPowerModeConfigured; 781 updateLowPowerModeLocked(); 782 } 783 784 mDirty |= DIRTY_SETTINGS; 785 } 786 787 private void postAfterBootCompleted(Runnable r) { 788 if (mBootCompleted) { 789 BackgroundThread.getHandler().post(r); 790 } else { 791 Slog.d(TAG, "Delaying runnable until system is booted"); 792 mBootCompletedRunnables = ArrayUtils.appendElement(Runnable.class, 793 mBootCompletedRunnables, r); 794 } 795 } 796 797 private void updateLowPowerModeLocked() { 798 if (mIsPowered && mLowPowerModeSetting) { 799 if (DEBUG_SPEW) { 800 Slog.d(TAG, "updateLowPowerModeLocked: powered, turning setting off"); 801 } 802 // Turn setting off if powered 803 Settings.Global.putInt(mContext.getContentResolver(), 804 Settings.Global.LOW_POWER_MODE, 0); 805 mLowPowerModeSetting = false; 806 } 807 final boolean autoLowPowerModeEnabled = !mIsPowered && mAutoLowPowerModeConfigured 808 && !mAutoLowPowerModeSnoozing && mBatteryLevelLow; 809 final boolean lowPowerModeEnabled = mLowPowerModeSetting || autoLowPowerModeEnabled; 810 811 if (mLowPowerModeEnabled != lowPowerModeEnabled) { 812 mLowPowerModeEnabled = lowPowerModeEnabled; 813 powerHintInternal(POWER_HINT_LOW_POWER, lowPowerModeEnabled ? 1 : 0); 814 postAfterBootCompleted(new Runnable() { 815 @Override 816 public void run() { 817 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING) 818 .putExtra(PowerManager.EXTRA_POWER_SAVE_MODE, mLowPowerModeEnabled) 819 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 820 mContext.sendBroadcast(intent); 821 ArrayList<PowerManagerInternal.LowPowerModeListener> listeners; 822 synchronized (mLock) { 823 listeners = new ArrayList<PowerManagerInternal.LowPowerModeListener>( 824 mLowPowerModeListeners); 825 } 826 for (int i=0; i<listeners.size(); i++) { 827 listeners.get(i).onLowPowerModeChanged(lowPowerModeEnabled); 828 } 829 intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); 830 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 831 mContext.sendBroadcast(intent); 832 // Send internal version that requires signature permission. 833 mContext.sendBroadcastAsUser(new Intent( 834 PowerManager.ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL), UserHandle.ALL, 835 Manifest.permission.DEVICE_POWER); 836 } 837 }); 838 } 839 } 840 841 private void handleSettingsChangedLocked() { 842 updateSettingsLocked(); 843 updatePowerStateLocked(); 844 } 845 846 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName, 847 WorkSource ws, String historyTag, int uid, int pid) { 848 synchronized (mLock) { 849 if (DEBUG_SPEW) { 850 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock) 851 + ", flags=0x" + Integer.toHexString(flags) 852 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid); 853 } 854 855 WakeLock wakeLock; 856 int index = findWakeLockIndexLocked(lock); 857 boolean notifyAcquire; 858 if (index >= 0) { 859 wakeLock = mWakeLocks.get(index); 860 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) { 861 // Update existing wake lock. This shouldn't happen but is harmless. 862 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName, 863 uid, pid, ws, historyTag); 864 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid); 865 } 866 notifyAcquire = false; 867 } else { 868 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid); 869 try { 870 lock.linkToDeath(wakeLock, 0); 871 } catch (RemoteException ex) { 872 throw new IllegalArgumentException("Wake lock is already dead."); 873 } 874 mWakeLocks.add(wakeLock); 875 setWakeLockDisabledStateLocked(wakeLock); 876 notifyAcquire = true; 877 } 878 879 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid); 880 mDirty |= DIRTY_WAKE_LOCKS; 881 updatePowerStateLocked(); 882 if (notifyAcquire) { 883 // This needs to be done last so we are sure we have acquired the 884 // kernel wake lock. Otherwise we have a race where the system may 885 // go to sleep between the time we start the accounting in battery 886 // stats and when we actually get around to telling the kernel to 887 // stay awake. 888 notifyWakeLockAcquiredLocked(wakeLock); 889 } 890 } 891 } 892 893 @SuppressWarnings("deprecation") 894 private static boolean isScreenLock(final WakeLock wakeLock) { 895 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 896 case PowerManager.FULL_WAKE_LOCK: 897 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 898 case PowerManager.SCREEN_DIM_WAKE_LOCK: 899 return true; 900 } 901 return false; 902 } 903 904 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) { 905 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0 906 && isScreenLock(wakeLock)) { 907 String opPackageName; 908 int opUid; 909 if (wakeLock.mWorkSource != null && wakeLock.mWorkSource.getName(0) != null) { 910 opPackageName = wakeLock.mWorkSource.getName(0); 911 opUid = wakeLock.mWorkSource.get(0); 912 } else { 913 opPackageName = wakeLock.mPackageName; 914 opUid = wakeLock.mWorkSource != null ? wakeLock.mWorkSource.get(0) 915 : wakeLock.mOwnerUid; 916 } 917 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), wakeLock.mTag, opUid, 918 opPackageName, opUid); 919 } 920 } 921 922 private void releaseWakeLockInternal(IBinder lock, int flags) { 923 synchronized (mLock) { 924 int index = findWakeLockIndexLocked(lock); 925 if (index < 0) { 926 if (DEBUG_SPEW) { 927 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 928 + " [not found], flags=0x" + Integer.toHexString(flags)); 929 } 930 return; 931 } 932 933 WakeLock wakeLock = mWakeLocks.get(index); 934 if (DEBUG_SPEW) { 935 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 936 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags)); 937 } 938 939 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) { 940 mRequestWaitForNegativeProximity = true; 941 } 942 943 wakeLock.mLock.unlinkToDeath(wakeLock, 0); 944 removeWakeLockLocked(wakeLock, index); 945 } 946 } 947 948 private void handleWakeLockDeath(WakeLock wakeLock) { 949 synchronized (mLock) { 950 if (DEBUG_SPEW) { 951 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock) 952 + " [" + wakeLock.mTag + "]"); 953 } 954 955 int index = mWakeLocks.indexOf(wakeLock); 956 if (index < 0) { 957 return; 958 } 959 960 removeWakeLockLocked(wakeLock, index); 961 } 962 } 963 964 private void removeWakeLockLocked(WakeLock wakeLock, int index) { 965 mWakeLocks.remove(index); 966 notifyWakeLockReleasedLocked(wakeLock); 967 968 applyWakeLockFlagsOnReleaseLocked(wakeLock); 969 mDirty |= DIRTY_WAKE_LOCKS; 970 updatePowerStateLocked(); 971 } 972 973 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) { 974 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0 975 && isScreenLock(wakeLock)) { 976 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 977 PowerManager.USER_ACTIVITY_EVENT_OTHER, 978 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS, 979 wakeLock.mOwnerUid); 980 } 981 } 982 983 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag, 984 int callingUid) { 985 synchronized (mLock) { 986 int index = findWakeLockIndexLocked(lock); 987 if (index < 0) { 988 if (DEBUG_SPEW) { 989 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock) 990 + " [not found], ws=" + ws); 991 } 992 throw new IllegalArgumentException("Wake lock not active: " + lock 993 + " from uid " + callingUid); 994 } 995 996 WakeLock wakeLock = mWakeLocks.get(index); 997 if (DEBUG_SPEW) { 998 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock) 999 + " [" + wakeLock.mTag + "], ws=" + ws); 1000 } 1001 1002 if (!wakeLock.hasSameWorkSource(ws)) { 1003 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag, 1004 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid, 1005 ws, historyTag); 1006 wakeLock.mHistoryTag = historyTag; 1007 wakeLock.updateWorkSource(ws); 1008 } 1009 } 1010 } 1011 1012 private int findWakeLockIndexLocked(IBinder lock) { 1013 final int count = mWakeLocks.size(); 1014 for (int i = 0; i < count; i++) { 1015 if (mWakeLocks.get(i).mLock == lock) { 1016 return i; 1017 } 1018 } 1019 return -1; 1020 } 1021 1022 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) { 1023 if (mSystemReady && !wakeLock.mDisabled) { 1024 wakeLock.mNotifiedAcquired = true; 1025 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 1026 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource, 1027 wakeLock.mHistoryTag); 1028 } 1029 } 1030 1031 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag, 1032 String packageName, int uid, int pid, WorkSource ws, String historyTag) { 1033 if (mSystemReady && wakeLock.mNotifiedAcquired) { 1034 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 1035 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource, 1036 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag); 1037 } 1038 } 1039 1040 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) { 1041 if (mSystemReady && wakeLock.mNotifiedAcquired) { 1042 wakeLock.mNotifiedAcquired = false; 1043 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, 1044 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid, 1045 wakeLock.mWorkSource, wakeLock.mHistoryTag); 1046 } 1047 } 1048 1049 @SuppressWarnings("deprecation") 1050 private boolean isWakeLockLevelSupportedInternal(int level) { 1051 synchronized (mLock) { 1052 switch (level) { 1053 case PowerManager.PARTIAL_WAKE_LOCK: 1054 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1055 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1056 case PowerManager.FULL_WAKE_LOCK: 1057 case PowerManager.DOZE_WAKE_LOCK: 1058 case PowerManager.DRAW_WAKE_LOCK: 1059 return true; 1060 1061 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1062 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable(); 1063 1064 default: 1065 return false; 1066 } 1067 } 1068 } 1069 1070 // Called from native code. 1071 private void userActivityFromNative(long eventTime, int event, int flags) { 1072 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID); 1073 } 1074 1075 private void userActivityInternal(long eventTime, int event, int flags, int uid) { 1076 synchronized (mLock) { 1077 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) { 1078 updatePowerStateLocked(); 1079 } 1080 } 1081 } 1082 1083 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) { 1084 if (DEBUG_SPEW) { 1085 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime 1086 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags) 1087 + ", uid=" + uid); 1088 } 1089 1090 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime 1091 || !mBootCompleted || !mSystemReady) { 1092 return false; 1093 } 1094 1095 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity"); 1096 try { 1097 if (eventTime > mLastInteractivePowerHintTime) { 1098 powerHintInternal(POWER_HINT_INTERACTION, 0); 1099 mLastInteractivePowerHintTime = eventTime; 1100 } 1101 1102 mNotifier.onUserActivity(event, uid); 1103 1104 if (mUserInactiveOverrideFromWindowManager) { 1105 mUserInactiveOverrideFromWindowManager = false; 1106 mOverriddenTimeout = -1; 1107 } 1108 1109 if (mWakefulness == WAKEFULNESS_ASLEEP 1110 || mWakefulness == WAKEFULNESS_DOZING 1111 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) { 1112 return false; 1113 } 1114 1115 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) { 1116 if (eventTime > mLastUserActivityTimeNoChangeLights 1117 && eventTime > mLastUserActivityTime) { 1118 mLastUserActivityTimeNoChangeLights = eventTime; 1119 mDirty |= DIRTY_USER_ACTIVITY; 1120 return true; 1121 } 1122 } else { 1123 if (eventTime > mLastUserActivityTime) { 1124 mLastUserActivityTime = eventTime; 1125 mDirty |= DIRTY_USER_ACTIVITY; 1126 return true; 1127 } 1128 } 1129 } finally { 1130 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1131 } 1132 return false; 1133 } 1134 1135 private void wakeUpInternal(long eventTime, String reason, int uid, String opPackageName, 1136 int opUid) { 1137 synchronized (mLock) { 1138 if (wakeUpNoUpdateLocked(eventTime, reason, uid, opPackageName, opUid)) { 1139 updatePowerStateLocked(); 1140 } 1141 } 1142 } 1143 1144 private boolean wakeUpNoUpdateLocked(long eventTime, String reason, int reasonUid, 1145 String opPackageName, int opUid) { 1146 if (DEBUG_SPEW) { 1147 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid); 1148 } 1149 1150 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE 1151 || !mBootCompleted || !mSystemReady) { 1152 return false; 1153 } 1154 1155 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp"); 1156 try { 1157 switch (mWakefulness) { 1158 case WAKEFULNESS_ASLEEP: 1159 Slog.i(TAG, "Waking up from sleep (uid " + reasonUid +")..."); 1160 break; 1161 case WAKEFULNESS_DREAMING: 1162 Slog.i(TAG, "Waking up from dream (uid " + reasonUid +")..."); 1163 break; 1164 case WAKEFULNESS_DOZING: 1165 Slog.i(TAG, "Waking up from dozing (uid " + reasonUid +")..."); 1166 break; 1167 } 1168 1169 mLastWakeTime = eventTime; 1170 setWakefulnessLocked(WAKEFULNESS_AWAKE, 0); 1171 1172 mNotifier.onWakeUp(reason, reasonUid, opPackageName, opUid); 1173 userActivityNoUpdateLocked( 1174 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid); 1175 } finally { 1176 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1177 } 1178 return true; 1179 } 1180 1181 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) { 1182 synchronized (mLock) { 1183 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) { 1184 updatePowerStateLocked(); 1185 } 1186 } 1187 } 1188 1189 // This method is called goToSleep for historical reasons but we actually start 1190 // dozing before really going to sleep. 1191 @SuppressWarnings("deprecation") 1192 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) { 1193 if (DEBUG_SPEW) { 1194 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime 1195 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid); 1196 } 1197 1198 if (eventTime < mLastWakeTime 1199 || mWakefulness == WAKEFULNESS_ASLEEP 1200 || mWakefulness == WAKEFULNESS_DOZING 1201 || !mBootCompleted || !mSystemReady) { 1202 return false; 1203 } 1204 1205 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep"); 1206 try { 1207 switch (reason) { 1208 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN: 1209 Slog.i(TAG, "Going to sleep due to device administration policy " 1210 + "(uid " + uid +")..."); 1211 break; 1212 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT: 1213 Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")..."); 1214 break; 1215 case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH: 1216 Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")..."); 1217 break; 1218 case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON: 1219 Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")..."); 1220 break; 1221 case PowerManager.GO_TO_SLEEP_REASON_SLEEP_BUTTON: 1222 Slog.i(TAG, "Going to sleep due to sleep button (uid " + uid +")..."); 1223 break; 1224 case PowerManager.GO_TO_SLEEP_REASON_HDMI: 1225 Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")..."); 1226 break; 1227 default: 1228 Slog.i(TAG, "Going to sleep by application request (uid " + uid +")..."); 1229 reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION; 1230 break; 1231 } 1232 1233 mLastSleepTime = eventTime; 1234 mSandmanSummoned = true; 1235 setWakefulnessLocked(WAKEFULNESS_DOZING, reason); 1236 1237 // Report the number of wake locks that will be cleared by going to sleep. 1238 int numWakeLocksCleared = 0; 1239 final int numWakeLocks = mWakeLocks.size(); 1240 for (int i = 0; i < numWakeLocks; i++) { 1241 final WakeLock wakeLock = mWakeLocks.get(i); 1242 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 1243 case PowerManager.FULL_WAKE_LOCK: 1244 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1245 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1246 numWakeLocksCleared += 1; 1247 break; 1248 } 1249 } 1250 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared); 1251 1252 // Skip dozing if requested. 1253 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) { 1254 reallyGoToSleepNoUpdateLocked(eventTime, uid); 1255 } 1256 } finally { 1257 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1258 } 1259 return true; 1260 } 1261 1262 private void napInternal(long eventTime, int uid) { 1263 synchronized (mLock) { 1264 if (napNoUpdateLocked(eventTime, uid)) { 1265 updatePowerStateLocked(); 1266 } 1267 } 1268 } 1269 1270 private boolean napNoUpdateLocked(long eventTime, int uid) { 1271 if (DEBUG_SPEW) { 1272 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid); 1273 } 1274 1275 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE 1276 || !mBootCompleted || !mSystemReady) { 1277 return false; 1278 } 1279 1280 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap"); 1281 try { 1282 Slog.i(TAG, "Nap time (uid " + uid +")..."); 1283 1284 mSandmanSummoned = true; 1285 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0); 1286 } finally { 1287 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1288 } 1289 return true; 1290 } 1291 1292 // Done dozing, drop everything and go to sleep. 1293 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) { 1294 if (DEBUG_SPEW) { 1295 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime 1296 + ", uid=" + uid); 1297 } 1298 1299 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP 1300 || !mBootCompleted || !mSystemReady) { 1301 return false; 1302 } 1303 1304 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep"); 1305 try { 1306 Slog.i(TAG, "Sleeping (uid " + uid +")..."); 1307 1308 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1309 } finally { 1310 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1311 } 1312 return true; 1313 } 1314 1315 private void setWakefulnessLocked(int wakefulness, int reason) { 1316 if (mWakefulness != wakefulness) { 1317 mWakefulness = wakefulness; 1318 mWakefulnessChanging = true; 1319 mDirty |= DIRTY_WAKEFULNESS; 1320 mNotifier.onWakefulnessChangeStarted(wakefulness, reason); 1321 } 1322 } 1323 1324 /** 1325 * Logs the time the device would have spent awake before user activity timeout, 1326 * had the system not been told the user was inactive. 1327 */ 1328 private void logSleepTimeoutRecapturedLocked() { 1329 final long now = SystemClock.uptimeMillis(); 1330 final long savedWakeTimeMs = mOverriddenTimeout - now; 1331 if (savedWakeTimeMs >= 0) { 1332 EventLog.writeEvent(EventLogTags.POWER_SOFT_SLEEP_REQUESTED, savedWakeTimeMs); 1333 mOverriddenTimeout = -1; 1334 } 1335 } 1336 1337 private void finishWakefulnessChangeIfNeededLocked() { 1338 if (mWakefulnessChanging && mDisplayReady) { 1339 if (mWakefulness == WAKEFULNESS_DOZING 1340 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) { 1341 return; // wait until dream has enabled dozing 1342 } 1343 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) { 1344 logSleepTimeoutRecapturedLocked(); 1345 } 1346 mWakefulnessChanging = false; 1347 mNotifier.onWakefulnessChangeFinished(); 1348 } 1349 } 1350 1351 /** 1352 * Updates the global power state based on dirty bits recorded in mDirty. 1353 * 1354 * This is the main function that performs power state transitions. 1355 * We centralize them here so that we can recompute the power state completely 1356 * each time something important changes, and ensure that we do it the same 1357 * way each time. The point is to gather all of the transition logic here. 1358 */ 1359 private void updatePowerStateLocked() { 1360 if (!mSystemReady || mDirty == 0) { 1361 return; 1362 } 1363 if (!Thread.holdsLock(mLock)) { 1364 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked"); 1365 } 1366 1367 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState"); 1368 try { 1369 // Phase 0: Basic state updates. 1370 updateIsPoweredLocked(mDirty); 1371 updateStayOnLocked(mDirty); 1372 updateScreenBrightnessBoostLocked(mDirty); 1373 1374 // Phase 1: Update wakefulness. 1375 // Loop because the wake lock and user activity computations are influenced 1376 // by changes in wakefulness. 1377 final long now = SystemClock.uptimeMillis(); 1378 int dirtyPhase2 = 0; 1379 for (;;) { 1380 int dirtyPhase1 = mDirty; 1381 dirtyPhase2 |= dirtyPhase1; 1382 mDirty = 0; 1383 1384 updateWakeLockSummaryLocked(dirtyPhase1); 1385 updateUserActivitySummaryLocked(now, dirtyPhase1); 1386 if (!updateWakefulnessLocked(dirtyPhase1)) { 1387 break; 1388 } 1389 } 1390 1391 // Phase 2: Update display power state. 1392 boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2); 1393 1394 // Phase 3: Update dream state (depends on display ready signal). 1395 updateDreamLocked(dirtyPhase2, displayBecameReady); 1396 1397 // Phase 4: Send notifications, if needed. 1398 finishWakefulnessChangeIfNeededLocked(); 1399 1400 // Phase 5: Update suspend blocker. 1401 // Because we might release the last suspend blocker here, we need to make sure 1402 // we finished everything else first! 1403 updateSuspendBlockerLocked(); 1404 } finally { 1405 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1406 } 1407 } 1408 1409 /** 1410 * Updates the value of mIsPowered. 1411 * Sets DIRTY_IS_POWERED if a change occurred. 1412 */ 1413 private void updateIsPoweredLocked(int dirty) { 1414 if ((dirty & DIRTY_BATTERY_STATE) != 0) { 1415 final boolean wasPowered = mIsPowered; 1416 final int oldPlugType = mPlugType; 1417 final boolean oldLevelLow = mBatteryLevelLow; 1418 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY); 1419 mPlugType = mBatteryManagerInternal.getPlugType(); 1420 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel(); 1421 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow(); 1422 1423 if (DEBUG_SPEW) { 1424 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered 1425 + ", mIsPowered=" + mIsPowered 1426 + ", oldPlugType=" + oldPlugType 1427 + ", mPlugType=" + mPlugType 1428 + ", mBatteryLevel=" + mBatteryLevel); 1429 } 1430 1431 if (wasPowered != mIsPowered || oldPlugType != mPlugType) { 1432 mDirty |= DIRTY_IS_POWERED; 1433 1434 // Update wireless dock detection state. 1435 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update( 1436 mIsPowered, mPlugType, mBatteryLevel); 1437 1438 // Treat plugging and unplugging the devices as a user activity. 1439 // Users find it disconcerting when they plug or unplug the device 1440 // and it shuts off right away. 1441 // Some devices also wake the device when plugged or unplugged because 1442 // they don't have a charging LED. 1443 final long now = SystemClock.uptimeMillis(); 1444 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType, 1445 dockedOnWirelessCharger)) { 1446 wakeUpNoUpdateLocked(now, "android.server.power:POWER", Process.SYSTEM_UID, 1447 mContext.getOpPackageName(), Process.SYSTEM_UID); 1448 } 1449 userActivityNoUpdateLocked( 1450 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1451 1452 // Tell the notifier whether wireless charging has started so that 1453 // it can provide feedback to the user. 1454 if (dockedOnWirelessCharger) { 1455 mNotifier.onWirelessChargingStarted(); 1456 } 1457 } 1458 1459 if (wasPowered != mIsPowered || oldLevelLow != mBatteryLevelLow) { 1460 if (oldLevelLow != mBatteryLevelLow && !mBatteryLevelLow) { 1461 if (DEBUG_SPEW) { 1462 Slog.d(TAG, "updateIsPoweredLocked: resetting low power snooze"); 1463 } 1464 mAutoLowPowerModeSnoozing = false; 1465 } 1466 updateLowPowerModeLocked(); 1467 } 1468 } 1469 } 1470 1471 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked( 1472 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) { 1473 // Don't wake when powered unless configured to do so. 1474 if (!mWakeUpWhenPluggedOrUnpluggedConfig) { 1475 return false; 1476 } 1477 1478 // Don't wake when undocked from wireless charger. 1479 // See WirelessChargerDetector for justification. 1480 if (wasPowered && !mIsPowered 1481 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) { 1482 return false; 1483 } 1484 1485 // Don't wake when docked on wireless charger unless we are certain of it. 1486 // See WirelessChargerDetector for justification. 1487 if (!wasPowered && mIsPowered 1488 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS 1489 && !dockedOnWirelessCharger) { 1490 return false; 1491 } 1492 1493 // If already dreaming and becoming powered, then don't wake. 1494 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) { 1495 return false; 1496 } 1497 1498 // Don't wake while theater mode is enabled. 1499 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) { 1500 return false; 1501 } 1502 1503 // Otherwise wake up! 1504 return true; 1505 } 1506 1507 /** 1508 * Updates the value of mStayOn. 1509 * Sets DIRTY_STAY_ON if a change occurred. 1510 */ 1511 private void updateStayOnLocked(int dirty) { 1512 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) { 1513 final boolean wasStayOn = mStayOn; 1514 if (mStayOnWhilePluggedInSetting != 0 1515 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1516 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting); 1517 } else { 1518 mStayOn = false; 1519 } 1520 1521 if (mStayOn != wasStayOn) { 1522 mDirty |= DIRTY_STAY_ON; 1523 } 1524 } 1525 } 1526 1527 /** 1528 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks. 1529 * Note that most wake-locks are ignored when the system is asleep. 1530 * 1531 * This function must have no other side-effects. 1532 */ 1533 @SuppressWarnings("deprecation") 1534 private void updateWakeLockSummaryLocked(int dirty) { 1535 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) { 1536 mWakeLockSummary = 0; 1537 1538 final int numWakeLocks = mWakeLocks.size(); 1539 for (int i = 0; i < numWakeLocks; i++) { 1540 final WakeLock wakeLock = mWakeLocks.get(i); 1541 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 1542 case PowerManager.PARTIAL_WAKE_LOCK: 1543 if (!wakeLock.mDisabled) { 1544 // We only respect this if the wake lock is not disabled. 1545 mWakeLockSummary |= WAKE_LOCK_CPU; 1546 } 1547 break; 1548 case PowerManager.FULL_WAKE_LOCK: 1549 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT; 1550 break; 1551 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1552 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT; 1553 break; 1554 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1555 mWakeLockSummary |= WAKE_LOCK_SCREEN_DIM; 1556 break; 1557 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1558 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF; 1559 break; 1560 case PowerManager.DOZE_WAKE_LOCK: 1561 mWakeLockSummary |= WAKE_LOCK_DOZE; 1562 break; 1563 case PowerManager.DRAW_WAKE_LOCK: 1564 mWakeLockSummary |= WAKE_LOCK_DRAW; 1565 break; 1566 } 1567 } 1568 1569 // Cancel wake locks that make no sense based on the current state. 1570 if (mWakefulness != WAKEFULNESS_DOZING) { 1571 mWakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW); 1572 } 1573 if (mWakefulness == WAKEFULNESS_ASLEEP 1574 || (mWakeLockSummary & WAKE_LOCK_DOZE) != 0) { 1575 mWakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM 1576 | WAKE_LOCK_BUTTON_BRIGHT); 1577 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1578 mWakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF; 1579 } 1580 } 1581 1582 // Infer implied wake locks where necessary based on the current state. 1583 if ((mWakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) { 1584 if (mWakefulness == WAKEFULNESS_AWAKE) { 1585 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE; 1586 } else if (mWakefulness == WAKEFULNESS_DREAMING) { 1587 mWakeLockSummary |= WAKE_LOCK_CPU; 1588 } 1589 } 1590 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0) { 1591 mWakeLockSummary |= WAKE_LOCK_CPU; 1592 } 1593 1594 if (DEBUG_SPEW) { 1595 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness=" 1596 + PowerManagerInternal.wakefulnessToString(mWakefulness) 1597 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1598 } 1599 } 1600 } 1601 1602 /** 1603 * Updates the value of mUserActivitySummary to summarize the user requested 1604 * state of the system such as whether the screen should be bright or dim. 1605 * Note that user activity is ignored when the system is asleep. 1606 * 1607 * This function must have no other side-effects. 1608 */ 1609 private void updateUserActivitySummaryLocked(long now, int dirty) { 1610 // Update the status of the user activity timeout timer. 1611 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY 1612 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) { 1613 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT); 1614 1615 long nextTimeout = 0; 1616 if (mWakefulness == WAKEFULNESS_AWAKE 1617 || mWakefulness == WAKEFULNESS_DREAMING 1618 || mWakefulness == WAKEFULNESS_DOZING) { 1619 final int sleepTimeout = getSleepTimeoutLocked(); 1620 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout); 1621 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 1622 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager; 1623 1624 mUserActivitySummary = 0; 1625 if (mLastUserActivityTime >= mLastWakeTime) { 1626 nextTimeout = mLastUserActivityTime 1627 + screenOffTimeout - screenDimDuration; 1628 if (now < nextTimeout) { 1629 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT; 1630 } else { 1631 nextTimeout = mLastUserActivityTime + screenOffTimeout; 1632 if (now < nextTimeout) { 1633 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM; 1634 } 1635 } 1636 } 1637 if (mUserActivitySummary == 0 1638 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) { 1639 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout; 1640 if (now < nextTimeout) { 1641 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT) { 1642 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT; 1643 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) { 1644 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM; 1645 } 1646 } 1647 } 1648 1649 if (mUserActivitySummary == 0) { 1650 if (sleepTimeout >= 0) { 1651 final long anyUserActivity = Math.max(mLastUserActivityTime, 1652 mLastUserActivityTimeNoChangeLights); 1653 if (anyUserActivity >= mLastWakeTime) { 1654 nextTimeout = anyUserActivity + sleepTimeout; 1655 if (now < nextTimeout) { 1656 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM; 1657 } 1658 } 1659 } else { 1660 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM; 1661 nextTimeout = -1; 1662 } 1663 } 1664 1665 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) { 1666 if ((mUserActivitySummary & 1667 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) { 1668 // Device is being kept awake by recent user activity 1669 if (nextTimeout >= now && mOverriddenTimeout == -1) { 1670 // Save when the next timeout would have occurred 1671 mOverriddenTimeout = nextTimeout; 1672 } 1673 } 1674 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM; 1675 nextTimeout = -1; 1676 } 1677 1678 if (mUserActivitySummary != 0 && nextTimeout >= 0) { 1679 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT); 1680 msg.setAsynchronous(true); 1681 mHandler.sendMessageAtTime(msg, nextTimeout); 1682 } 1683 } else { 1684 mUserActivitySummary = 0; 1685 } 1686 1687 if (DEBUG_SPEW) { 1688 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness=" 1689 + PowerManagerInternal.wakefulnessToString(mWakefulness) 1690 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1691 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout)); 1692 } 1693 } 1694 } 1695 1696 /** 1697 * Called when a user activity timeout has occurred. 1698 * Simply indicates that something about user activity has changed so that the new 1699 * state can be recomputed when the power state is updated. 1700 * 1701 * This function must have no other side-effects besides setting the dirty 1702 * bit and calling update power state. Wakefulness transitions are handled elsewhere. 1703 */ 1704 private void handleUserActivityTimeout() { // runs on handler thread 1705 synchronized (mLock) { 1706 if (DEBUG_SPEW) { 1707 Slog.d(TAG, "handleUserActivityTimeout"); 1708 } 1709 1710 mDirty |= DIRTY_USER_ACTIVITY; 1711 updatePowerStateLocked(); 1712 } 1713 } 1714 1715 private int getSleepTimeoutLocked() { 1716 int timeout = mSleepTimeoutSetting; 1717 if (timeout <= 0) { 1718 return -1; 1719 } 1720 return Math.max(timeout, mMinimumScreenOffTimeoutConfig); 1721 } 1722 1723 private int getScreenOffTimeoutLocked(int sleepTimeout) { 1724 int timeout = mScreenOffTimeoutSetting; 1725 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1726 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin); 1727 } 1728 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) { 1729 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager); 1730 } 1731 if (sleepTimeout >= 0) { 1732 timeout = Math.min(timeout, sleepTimeout); 1733 } 1734 return Math.max(timeout, mMinimumScreenOffTimeoutConfig); 1735 } 1736 1737 private int getScreenDimDurationLocked(int screenOffTimeout) { 1738 return Math.min(mMaximumScreenDimDurationConfig, 1739 (int)(screenOffTimeout * mMaximumScreenDimRatioConfig)); 1740 } 1741 1742 /** 1743 * Updates the wakefulness of the device. 1744 * 1745 * This is the function that decides whether the device should start dreaming 1746 * based on the current wake locks and user activity state. It may modify mDirty 1747 * if the wakefulness changes. 1748 * 1749 * Returns true if the wakefulness changed and we need to restart power state calculation. 1750 */ 1751 private boolean updateWakefulnessLocked(int dirty) { 1752 boolean changed = false; 1753 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED 1754 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE 1755 | DIRTY_DOCK_STATE)) != 0) { 1756 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) { 1757 if (DEBUG_SPEW) { 1758 Slog.d(TAG, "updateWakefulnessLocked: Bed time..."); 1759 } 1760 final long time = SystemClock.uptimeMillis(); 1761 if (shouldNapAtBedTimeLocked()) { 1762 changed = napNoUpdateLocked(time, Process.SYSTEM_UID); 1763 } else { 1764 changed = goToSleepNoUpdateLocked(time, 1765 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID); 1766 } 1767 } 1768 } 1769 return changed; 1770 } 1771 1772 /** 1773 * Returns true if the device should automatically nap and start dreaming when the user 1774 * activity timeout has expired and it's bedtime. 1775 */ 1776 private boolean shouldNapAtBedTimeLocked() { 1777 return mDreamsActivateOnSleepSetting 1778 || (mDreamsActivateOnDockSetting 1779 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED); 1780 } 1781 1782 /** 1783 * Returns true if the device should go to sleep now. 1784 * Also used when exiting a dream to determine whether we should go back 1785 * to being fully awake or else go to sleep for good. 1786 */ 1787 private boolean isItBedTimeYetLocked() { 1788 return mBootCompleted && !isBeingKeptAwakeLocked(); 1789 } 1790 1791 /** 1792 * Returns true if the device is being kept awake by a wake lock, user activity 1793 * or the stay on while powered setting. We also keep the phone awake when 1794 * the proximity sensor returns a positive result so that the device does not 1795 * lock while in a phone call. This function only controls whether the device 1796 * will go to sleep or dream which is independent of whether it will be allowed 1797 * to suspend. 1798 */ 1799 private boolean isBeingKeptAwakeLocked() { 1800 return mStayOn 1801 || mProximityPositive 1802 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0 1803 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT 1804 | USER_ACTIVITY_SCREEN_DIM)) != 0 1805 || mScreenBrightnessBoostInProgress; 1806 } 1807 1808 /** 1809 * Determines whether to post a message to the sandman to update the dream state. 1810 */ 1811 private void updateDreamLocked(int dirty, boolean displayBecameReady) { 1812 if ((dirty & (DIRTY_WAKEFULNESS 1813 | DIRTY_USER_ACTIVITY 1814 | DIRTY_WAKE_LOCKS 1815 | DIRTY_BOOT_COMPLETED 1816 | DIRTY_SETTINGS 1817 | DIRTY_IS_POWERED 1818 | DIRTY_STAY_ON 1819 | DIRTY_PROXIMITY_POSITIVE 1820 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) { 1821 if (mDisplayReady) { 1822 scheduleSandmanLocked(); 1823 } 1824 } 1825 } 1826 1827 private void scheduleSandmanLocked() { 1828 if (!mSandmanScheduled) { 1829 mSandmanScheduled = true; 1830 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1831 msg.setAsynchronous(true); 1832 mHandler.sendMessage(msg); 1833 } 1834 } 1835 1836 /** 1837 * Called when the device enters or exits a dreaming or dozing state. 1838 * 1839 * We do this asynchronously because we must call out of the power manager to start 1840 * the dream and we don't want to hold our lock while doing so. There is a risk that 1841 * the device will wake or go to sleep in the meantime so we have to handle that case. 1842 */ 1843 private void handleSandman() { // runs on handler thread 1844 // Handle preconditions. 1845 final boolean startDreaming; 1846 final int wakefulness; 1847 synchronized (mLock) { 1848 mSandmanScheduled = false; 1849 wakefulness = mWakefulness; 1850 if (mSandmanSummoned && mDisplayReady) { 1851 startDreaming = canDreamLocked() || canDozeLocked(); 1852 mSandmanSummoned = false; 1853 } else { 1854 startDreaming = false; 1855 } 1856 } 1857 1858 // Start dreaming if needed. 1859 // We only control the dream on the handler thread, so we don't need to worry about 1860 // concurrent attempts to start or stop the dream. 1861 final boolean isDreaming; 1862 if (mDreamManager != null) { 1863 // Restart the dream whenever the sandman is summoned. 1864 if (startDreaming) { 1865 mDreamManager.stopDream(false /*immediate*/); 1866 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING); 1867 } 1868 isDreaming = mDreamManager.isDreaming(); 1869 } else { 1870 isDreaming = false; 1871 } 1872 1873 // Update dream state. 1874 synchronized (mLock) { 1875 // Remember the initial battery level when the dream started. 1876 if (startDreaming && isDreaming) { 1877 mBatteryLevelWhenDreamStarted = mBatteryLevel; 1878 if (wakefulness == WAKEFULNESS_DOZING) { 1879 Slog.i(TAG, "Dozing..."); 1880 } else { 1881 Slog.i(TAG, "Dreaming..."); 1882 } 1883 } 1884 1885 // If preconditions changed, wait for the next iteration to determine 1886 // whether the dream should continue (or be restarted). 1887 if (mSandmanSummoned || mWakefulness != wakefulness) { 1888 return; // wait for next cycle 1889 } 1890 1891 // Determine whether the dream should continue. 1892 if (wakefulness == WAKEFULNESS_DREAMING) { 1893 if (isDreaming && canDreamLocked()) { 1894 if (mDreamsBatteryLevelDrainCutoffConfig >= 0 1895 && mBatteryLevel < mBatteryLevelWhenDreamStarted 1896 - mDreamsBatteryLevelDrainCutoffConfig 1897 && !isBeingKeptAwakeLocked()) { 1898 // If the user activity timeout expired and the battery appears 1899 // to be draining faster than it is charging then stop dreaming 1900 // and go to sleep. 1901 Slog.i(TAG, "Stopping dream because the battery appears to " 1902 + "be draining faster than it is charging. " 1903 + "Battery level when dream started: " 1904 + mBatteryLevelWhenDreamStarted + "%. " 1905 + "Battery level now: " + mBatteryLevel + "%."); 1906 } else { 1907 return; // continue dreaming 1908 } 1909 } 1910 1911 // Dream has ended or will be stopped. Update the power state. 1912 if (isItBedTimeYetLocked()) { 1913 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(), 1914 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID); 1915 updatePowerStateLocked(); 1916 } else { 1917 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), "android.server.power:DREAM", 1918 Process.SYSTEM_UID, mContext.getOpPackageName(), Process.SYSTEM_UID); 1919 updatePowerStateLocked(); 1920 } 1921 } else if (wakefulness == WAKEFULNESS_DOZING) { 1922 if (isDreaming) { 1923 return; // continue dozing 1924 } 1925 1926 // Doze has ended or will be stopped. Update the power state. 1927 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID); 1928 updatePowerStateLocked(); 1929 } 1930 } 1931 1932 // Stop dream. 1933 if (isDreaming) { 1934 mDreamManager.stopDream(false /*immediate*/); 1935 } 1936 } 1937 1938 /** 1939 * Returns true if the device is allowed to dream in its current state. 1940 */ 1941 private boolean canDreamLocked() { 1942 if (mWakefulness != WAKEFULNESS_DREAMING 1943 || !mDreamsSupportedConfig 1944 || !mDreamsEnabledSetting 1945 || !mDisplayPowerRequest.isBrightOrDim() 1946 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT 1947 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0 1948 || !mBootCompleted) { 1949 return false; 1950 } 1951 if (!isBeingKeptAwakeLocked()) { 1952 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) { 1953 return false; 1954 } 1955 if (!mIsPowered 1956 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0 1957 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) { 1958 return false; 1959 } 1960 if (mIsPowered 1961 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0 1962 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) { 1963 return false; 1964 } 1965 } 1966 return true; 1967 } 1968 1969 /** 1970 * Returns true if the device is allowed to doze in its current state. 1971 */ 1972 private boolean canDozeLocked() { 1973 return mWakefulness == WAKEFULNESS_DOZING; 1974 } 1975 1976 /** 1977 * Updates the display power state asynchronously. 1978 * When the update is finished, mDisplayReady will be set to true. The display 1979 * controller posts a message to tell us when the actual display power state 1980 * has been updated so we come back here to double-check and finish up. 1981 * 1982 * This function recalculates the display power state each time. 1983 * 1984 * @return True if the display became ready. 1985 */ 1986 private boolean updateDisplayPowerStateLocked(int dirty) { 1987 final boolean oldDisplayReady = mDisplayReady; 1988 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS 1989 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED 1990 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST)) != 0) { 1991 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked(); 1992 1993 // Determine appropriate screen brightness and auto-brightness adjustments. 1994 boolean brightnessSetByUser = true; 1995 int screenBrightness = mScreenBrightnessSettingDefault; 1996 float screenAutoBrightnessAdjustment = 0.0f; 1997 boolean autoBrightness = (mScreenBrightnessModeSetting == 1998 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 1999 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) { 2000 screenBrightness = mScreenBrightnessOverrideFromWindowManager; 2001 autoBrightness = false; 2002 brightnessSetByUser = false; 2003 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) { 2004 screenBrightness = mTemporaryScreenBrightnessSettingOverride; 2005 } else if (isValidBrightness(mScreenBrightnessSetting)) { 2006 screenBrightness = mScreenBrightnessSetting; 2007 } 2008 if (autoBrightness) { 2009 screenBrightness = mScreenBrightnessSettingDefault; 2010 if (isValidAutoBrightnessAdjustment( 2011 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) { 2012 screenAutoBrightnessAdjustment = 2013 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride; 2014 } else if (isValidAutoBrightnessAdjustment( 2015 mScreenAutoBrightnessAdjustmentSetting)) { 2016 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting; 2017 } 2018 } 2019 screenBrightness = Math.max(Math.min(screenBrightness, 2020 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum); 2021 screenAutoBrightnessAdjustment = Math.max(Math.min( 2022 screenAutoBrightnessAdjustment, 1.0f), -1.0f); 2023 2024 // Update display power request. 2025 mDisplayPowerRequest.screenBrightness = screenBrightness; 2026 mDisplayPowerRequest.screenAutoBrightnessAdjustment = 2027 screenAutoBrightnessAdjustment; 2028 mDisplayPowerRequest.brightnessSetByUser = brightnessSetByUser; 2029 mDisplayPowerRequest.useAutoBrightness = autoBrightness; 2030 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked(); 2031 mDisplayPowerRequest.lowPowerMode = mLowPowerModeEnabled; 2032 mDisplayPowerRequest.boostScreenBrightness = mScreenBrightnessBoostInProgress; 2033 mDisplayPowerRequest.useTwilight = mBrightnessUseTwilight; 2034 2035 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) { 2036 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager; 2037 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND 2038 && (mWakeLockSummary & WAKE_LOCK_DRAW) != 0) { 2039 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE; 2040 } 2041 mDisplayPowerRequest.dozeScreenBrightness = 2042 mDozeScreenBrightnessOverrideFromDreamManager; 2043 } else { 2044 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN; 2045 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 2046 } 2047 2048 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest, 2049 mRequestWaitForNegativeProximity); 2050 mRequestWaitForNegativeProximity = false; 2051 2052 if (DEBUG_SPEW) { 2053 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady 2054 + ", policy=" + mDisplayPowerRequest.policy 2055 + ", mWakefulness=" + mWakefulness 2056 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary) 2057 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 2058 + ", mBootCompleted=" + mBootCompleted 2059 + ", mScreenBrightnessBoostInProgress=" 2060 + mScreenBrightnessBoostInProgress); 2061 } 2062 } 2063 return mDisplayReady && !oldDisplayReady; 2064 } 2065 2066 private void updateScreenBrightnessBoostLocked(int dirty) { 2067 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) { 2068 if (mScreenBrightnessBoostInProgress) { 2069 final long now = SystemClock.uptimeMillis(); 2070 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT); 2071 if (mLastScreenBrightnessBoostTime > mLastSleepTime) { 2072 final long boostTimeout = mLastScreenBrightnessBoostTime + 2073 SCREEN_BRIGHTNESS_BOOST_TIMEOUT; 2074 if (boostTimeout > now) { 2075 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT); 2076 msg.setAsynchronous(true); 2077 mHandler.sendMessageAtTime(msg, boostTimeout); 2078 return; 2079 } 2080 } 2081 mScreenBrightnessBoostInProgress = false; 2082 mNotifier.onScreenBrightnessBoostChanged(); 2083 userActivityNoUpdateLocked(now, 2084 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 2085 } 2086 } 2087 } 2088 2089 private static boolean isValidBrightness(int value) { 2090 return value >= 0 && value <= 255; 2091 } 2092 2093 private static boolean isValidAutoBrightnessAdjustment(float value) { 2094 // Handles NaN by always returning false. 2095 return value >= -1.0f && value <= 1.0f; 2096 } 2097 2098 private int getDesiredScreenPolicyLocked() { 2099 if (mWakefulness == WAKEFULNESS_ASLEEP) { 2100 return DisplayPowerRequest.POLICY_OFF; 2101 } 2102 2103 if (mWakefulness == WAKEFULNESS_DOZING) { 2104 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) { 2105 return DisplayPowerRequest.POLICY_DOZE; 2106 } 2107 if (mDozeAfterScreenOffConfig) { 2108 return DisplayPowerRequest.POLICY_OFF; 2109 } 2110 // Fall through and preserve the current screen policy if not configured to 2111 // doze after screen off. This causes the screen off transition to be skipped. 2112 } 2113 2114 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0 2115 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0 2116 || !mBootCompleted 2117 || mScreenBrightnessBoostInProgress) { 2118 return DisplayPowerRequest.POLICY_BRIGHT; 2119 } 2120 2121 return DisplayPowerRequest.POLICY_DIM; 2122 } 2123 2124 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks = 2125 new DisplayManagerInternal.DisplayPowerCallbacks() { 2126 private int mDisplayState = Display.STATE_UNKNOWN; 2127 2128 @Override 2129 public void onStateChanged() { 2130 synchronized (mLock) { 2131 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED; 2132 updatePowerStateLocked(); 2133 } 2134 } 2135 2136 @Override 2137 public void onProximityPositive() { 2138 synchronized (mLock) { 2139 mProximityPositive = true; 2140 mDirty |= DIRTY_PROXIMITY_POSITIVE; 2141 updatePowerStateLocked(); 2142 } 2143 } 2144 2145 @Override 2146 public void onProximityNegative() { 2147 synchronized (mLock) { 2148 mProximityPositive = false; 2149 mDirty |= DIRTY_PROXIMITY_POSITIVE; 2150 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 2151 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 2152 updatePowerStateLocked(); 2153 } 2154 } 2155 2156 @Override 2157 public void onDisplayStateChange(int state) { 2158 // This method is only needed to support legacy display blanking behavior 2159 // where the display's power state is coupled to suspend or to the power HAL. 2160 // The order of operations matters here. 2161 synchronized (mLock) { 2162 if (mDisplayState != state) { 2163 mDisplayState = state; 2164 if (state == Display.STATE_OFF) { 2165 if (!mDecoupleHalInteractiveModeFromDisplayConfig) { 2166 setHalInteractiveModeLocked(false); 2167 } 2168 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2169 setHalAutoSuspendModeLocked(true); 2170 } 2171 } else { 2172 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2173 setHalAutoSuspendModeLocked(false); 2174 } 2175 if (!mDecoupleHalInteractiveModeFromDisplayConfig) { 2176 setHalInteractiveModeLocked(true); 2177 } 2178 } 2179 } 2180 } 2181 } 2182 2183 @Override 2184 public void acquireSuspendBlocker() { 2185 mDisplaySuspendBlocker.acquire(); 2186 } 2187 2188 @Override 2189 public void releaseSuspendBlocker() { 2190 mDisplaySuspendBlocker.release(); 2191 } 2192 2193 @Override 2194 public String toString() { 2195 synchronized (this) { 2196 return "state=" + Display.stateToString(mDisplayState); 2197 } 2198 } 2199 }; 2200 2201 private boolean shouldUseProximitySensorLocked() { 2202 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0; 2203 } 2204 2205 /** 2206 * Updates the suspend blocker that keeps the CPU alive. 2207 * 2208 * This function must have no other side-effects. 2209 */ 2210 private void updateSuspendBlockerLocked() { 2211 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0); 2212 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked(); 2213 final boolean autoSuspend = !needDisplaySuspendBlocker; 2214 final boolean interactive = mDisplayPowerRequest.isBrightOrDim(); 2215 2216 // Disable auto-suspend if needed. 2217 // FIXME We should consider just leaving auto-suspend enabled forever since 2218 // we already hold the necessary wakelocks. 2219 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2220 setHalAutoSuspendModeLocked(false); 2221 } 2222 2223 // First acquire suspend blockers if needed. 2224 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) { 2225 mWakeLockSuspendBlocker.acquire(); 2226 mHoldingWakeLockSuspendBlocker = true; 2227 } 2228 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) { 2229 mDisplaySuspendBlocker.acquire(); 2230 mHoldingDisplaySuspendBlocker = true; 2231 } 2232 2233 // Inform the power HAL about interactive mode. 2234 // Although we could set interactive strictly based on the wakefulness 2235 // as reported by isInteractive(), it is actually more desirable to track 2236 // the display policy state instead so that the interactive state observed 2237 // by the HAL more accurately tracks transitions between AWAKE and DOZING. 2238 // Refer to getDesiredScreenPolicyLocked() for details. 2239 if (mDecoupleHalInteractiveModeFromDisplayConfig) { 2240 // When becoming non-interactive, we want to defer sending this signal 2241 // until the display is actually ready so that all transitions have 2242 // completed. This is probably a good sign that things have gotten 2243 // too tangled over here... 2244 if (interactive || mDisplayReady) { 2245 setHalInteractiveModeLocked(interactive); 2246 } 2247 } 2248 2249 // Then release suspend blockers if needed. 2250 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) { 2251 mWakeLockSuspendBlocker.release(); 2252 mHoldingWakeLockSuspendBlocker = false; 2253 } 2254 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) { 2255 mDisplaySuspendBlocker.release(); 2256 mHoldingDisplaySuspendBlocker = false; 2257 } 2258 2259 // Enable auto-suspend if needed. 2260 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2261 setHalAutoSuspendModeLocked(true); 2262 } 2263 } 2264 2265 /** 2266 * Return true if we must keep a suspend blocker active on behalf of the display. 2267 * We do so if the screen is on or is in transition between states. 2268 */ 2269 private boolean needDisplaySuspendBlockerLocked() { 2270 if (!mDisplayReady) { 2271 return true; 2272 } 2273 if (mDisplayPowerRequest.isBrightOrDim()) { 2274 // If we asked for the screen to be on but it is off due to the proximity 2275 // sensor then we may suspend but only if the configuration allows it. 2276 // On some hardware it may not be safe to suspend because the proximity 2277 // sensor may not be correctly configured as a wake-up source. 2278 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive 2279 || !mSuspendWhenScreenOffDueToProximityConfig) { 2280 return true; 2281 } 2282 } 2283 if (mScreenBrightnessBoostInProgress) { 2284 return true; 2285 } 2286 // Let the system suspend if the screen is off or dozing. 2287 return false; 2288 } 2289 2290 private void setHalAutoSuspendModeLocked(boolean enable) { 2291 if (enable != mHalAutoSuspendModeEnabled) { 2292 if (DEBUG) { 2293 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable); 2294 } 2295 mHalAutoSuspendModeEnabled = enable; 2296 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")"); 2297 try { 2298 nativeSetAutoSuspend(enable); 2299 } finally { 2300 Trace.traceEnd(Trace.TRACE_TAG_POWER); 2301 } 2302 } 2303 } 2304 2305 private void setHalInteractiveModeLocked(boolean enable) { 2306 if (enable != mHalInteractiveModeEnabled) { 2307 if (DEBUG) { 2308 Slog.d(TAG, "Setting HAL interactive mode to " + enable); 2309 } 2310 mHalInteractiveModeEnabled = enable; 2311 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")"); 2312 try { 2313 nativeSetInteractive(enable); 2314 } finally { 2315 Trace.traceEnd(Trace.TRACE_TAG_POWER); 2316 } 2317 } 2318 } 2319 2320 private boolean isInteractiveInternal() { 2321 synchronized (mLock) { 2322 return PowerManagerInternal.isInteractive(mWakefulness); 2323 } 2324 } 2325 2326 private boolean isLowPowerModeInternal() { 2327 synchronized (mLock) { 2328 return mLowPowerModeEnabled; 2329 } 2330 } 2331 2332 private boolean setLowPowerModeInternal(boolean mode) { 2333 synchronized (mLock) { 2334 if (DEBUG) Slog.d(TAG, "setLowPowerModeInternal " + mode + " mIsPowered=" + mIsPowered); 2335 if (mIsPowered) { 2336 return false; 2337 } 2338 Settings.Global.putInt(mContext.getContentResolver(), 2339 Settings.Global.LOW_POWER_MODE, mode ? 1 : 0); 2340 mLowPowerModeSetting = mode; 2341 2342 if (mAutoLowPowerModeConfigured && mBatteryLevelLow) { 2343 if (mode && mAutoLowPowerModeSnoozing) { 2344 if (DEBUG_SPEW) { 2345 Slog.d(TAG, "setLowPowerModeInternal: clearing low power mode snooze"); 2346 } 2347 mAutoLowPowerModeSnoozing = false; 2348 } else if (!mode && !mAutoLowPowerModeSnoozing) { 2349 if (DEBUG_SPEW) { 2350 Slog.d(TAG, "setLowPowerModeInternal: snoozing low power mode"); 2351 } 2352 mAutoLowPowerModeSnoozing = true; 2353 } 2354 } 2355 2356 updateLowPowerModeLocked(); 2357 return true; 2358 } 2359 } 2360 2361 boolean isDeviceIdleModeInternal() { 2362 synchronized (mLock) { 2363 return mDeviceIdleMode; 2364 } 2365 } 2366 2367 boolean isLightDeviceIdleModeInternal() { 2368 synchronized (mLock) { 2369 return mLightDeviceIdleMode; 2370 } 2371 } 2372 2373 private void handleBatteryStateChangedLocked() { 2374 mDirty |= DIRTY_BATTERY_STATE; 2375 updatePowerStateLocked(); 2376 } 2377 2378 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm, 2379 final String reason, boolean wait) { 2380 if (mHandler == null || !mSystemReady) { 2381 throw new IllegalStateException("Too early to call shutdown() or reboot()"); 2382 } 2383 2384 Runnable runnable = new Runnable() { 2385 @Override 2386 public void run() { 2387 synchronized (this) { 2388 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) { 2389 ShutdownThread.rebootSafeMode(mContext, confirm); 2390 } else if (haltMode == HALT_MODE_REBOOT) { 2391 ShutdownThread.reboot(mContext, reason, confirm); 2392 } else { 2393 ShutdownThread.shutdown(mContext, reason, confirm); 2394 } 2395 } 2396 } 2397 }; 2398 2399 // ShutdownThread must run on a looper capable of displaying the UI. 2400 Message msg = Message.obtain(mHandler, runnable); 2401 msg.setAsynchronous(true); 2402 mHandler.sendMessage(msg); 2403 2404 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 2405 if (wait) { 2406 synchronized (runnable) { 2407 while (true) { 2408 try { 2409 runnable.wait(); 2410 } catch (InterruptedException e) { 2411 } 2412 } 2413 } 2414 } 2415 } 2416 2417 private void crashInternal(final String message) { 2418 Thread t = new Thread("PowerManagerService.crash()") { 2419 @Override 2420 public void run() { 2421 throw new RuntimeException(message); 2422 } 2423 }; 2424 try { 2425 t.start(); 2426 t.join(); 2427 } catch (InterruptedException e) { 2428 Slog.wtf(TAG, e); 2429 } 2430 } 2431 2432 void setStayOnSettingInternal(int val) { 2433 Settings.Global.putInt(mContext.getContentResolver(), 2434 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val); 2435 } 2436 2437 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) { 2438 synchronized (mLock) { 2439 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs; 2440 mDirty |= DIRTY_SETTINGS; 2441 updatePowerStateLocked(); 2442 } 2443 } 2444 2445 boolean setDeviceIdleModeInternal(boolean enabled) { 2446 synchronized (mLock) { 2447 if (mDeviceIdleMode != enabled) { 2448 mDeviceIdleMode = enabled; 2449 updateWakeLockDisabledStatesLocked(); 2450 if (enabled) { 2451 EventLogTags.writeDeviceIdleOnPhase("power"); 2452 } else { 2453 EventLogTags.writeDeviceIdleOffPhase("power"); 2454 } 2455 return true; 2456 } 2457 return false; 2458 } 2459 } 2460 2461 boolean setLightDeviceIdleModeInternal(boolean enabled) { 2462 synchronized (mLock) { 2463 if (mLightDeviceIdleMode != enabled) { 2464 mLightDeviceIdleMode = enabled; 2465 return true; 2466 } 2467 return false; 2468 } 2469 } 2470 2471 void setDeviceIdleWhitelistInternal(int[] appids) { 2472 synchronized (mLock) { 2473 mDeviceIdleWhitelist = appids; 2474 if (mDeviceIdleMode) { 2475 updateWakeLockDisabledStatesLocked(); 2476 } 2477 } 2478 } 2479 2480 void setDeviceIdleTempWhitelistInternal(int[] appids) { 2481 synchronized (mLock) { 2482 mDeviceIdleTempWhitelist = appids; 2483 if (mDeviceIdleMode) { 2484 updateWakeLockDisabledStatesLocked(); 2485 } 2486 } 2487 } 2488 2489 void updateUidProcStateInternal(int uid, int procState) { 2490 synchronized (mLock) { 2491 mUidState.put(uid, procState); 2492 if (mDeviceIdleMode) { 2493 updateWakeLockDisabledStatesLocked(); 2494 } 2495 } 2496 } 2497 2498 void uidGoneInternal(int uid) { 2499 synchronized (mLock) { 2500 mUidState.delete(uid); 2501 if (mDeviceIdleMode) { 2502 updateWakeLockDisabledStatesLocked(); 2503 } 2504 } 2505 } 2506 2507 private void updateWakeLockDisabledStatesLocked() { 2508 boolean changed = false; 2509 final int numWakeLocks = mWakeLocks.size(); 2510 for (int i = 0; i < numWakeLocks; i++) { 2511 final WakeLock wakeLock = mWakeLocks.get(i); 2512 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) 2513 == PowerManager.PARTIAL_WAKE_LOCK) { 2514 if (setWakeLockDisabledStateLocked(wakeLock)) { 2515 changed = true; 2516 if (wakeLock.mDisabled) { 2517 // This wake lock is no longer being respected. 2518 notifyWakeLockReleasedLocked(wakeLock); 2519 } else { 2520 notifyWakeLockAcquiredLocked(wakeLock); 2521 } 2522 } 2523 } 2524 } 2525 if (changed) { 2526 mDirty |= DIRTY_WAKE_LOCKS; 2527 updatePowerStateLocked(); 2528 } 2529 } 2530 2531 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) { 2532 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) 2533 == PowerManager.PARTIAL_WAKE_LOCK) { 2534 boolean disabled = false; 2535 if (mDeviceIdleMode) { 2536 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid); 2537 // If we are in idle mode, we will ignore all partial wake locks that are 2538 // for application uids that are not whitelisted. 2539 if (appid >= Process.FIRST_APPLICATION_UID && 2540 Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 && 2541 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 && 2542 mUidState.get(wakeLock.mOwnerUid, 2543 ActivityManager.PROCESS_STATE_CACHED_EMPTY) 2544 > ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) { 2545 disabled = true; 2546 } 2547 } 2548 if (wakeLock.mDisabled != disabled) { 2549 wakeLock.mDisabled = disabled; 2550 return true; 2551 } 2552 } 2553 return false; 2554 } 2555 2556 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() { 2557 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0 2558 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE; 2559 } 2560 2561 private void setAttentionLightInternal(boolean on, int color) { 2562 Light light; 2563 synchronized (mLock) { 2564 if (!mSystemReady) { 2565 return; 2566 } 2567 light = mAttentionLight; 2568 } 2569 2570 // Control light outside of lock. 2571 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 2572 } 2573 2574 private void boostScreenBrightnessInternal(long eventTime, int uid) { 2575 synchronized (mLock) { 2576 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP 2577 || eventTime < mLastScreenBrightnessBoostTime) { 2578 return; 2579 } 2580 2581 Slog.i(TAG, "Brightness boost activated (uid " + uid +")..."); 2582 mLastScreenBrightnessBoostTime = eventTime; 2583 if (!mScreenBrightnessBoostInProgress) { 2584 mScreenBrightnessBoostInProgress = true; 2585 mNotifier.onScreenBrightnessBoostChanged(); 2586 } 2587 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST; 2588 2589 userActivityNoUpdateLocked(eventTime, 2590 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid); 2591 updatePowerStateLocked(); 2592 } 2593 } 2594 2595 private boolean isScreenBrightnessBoostedInternal() { 2596 synchronized (mLock) { 2597 return mScreenBrightnessBoostInProgress; 2598 } 2599 } 2600 2601 /** 2602 * Called when a screen brightness boost timeout has occurred. 2603 * 2604 * This function must have no other side-effects besides setting the dirty 2605 * bit and calling update power state. 2606 */ 2607 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread 2608 synchronized (mLock) { 2609 if (DEBUG_SPEW) { 2610 Slog.d(TAG, "handleScreenBrightnessBoostTimeout"); 2611 } 2612 2613 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST; 2614 updatePowerStateLocked(); 2615 } 2616 } 2617 2618 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) { 2619 synchronized (mLock) { 2620 if (mScreenBrightnessOverrideFromWindowManager != brightness) { 2621 mScreenBrightnessOverrideFromWindowManager = brightness; 2622 mDirty |= DIRTY_SETTINGS; 2623 updatePowerStateLocked(); 2624 } 2625 } 2626 } 2627 2628 private void setUserInactiveOverrideFromWindowManagerInternal() { 2629 synchronized (mLock) { 2630 mUserInactiveOverrideFromWindowManager = true; 2631 mDirty |= DIRTY_USER_ACTIVITY; 2632 updatePowerStateLocked(); 2633 } 2634 } 2635 2636 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) { 2637 synchronized (mLock) { 2638 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) { 2639 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis; 2640 mDirty |= DIRTY_SETTINGS; 2641 updatePowerStateLocked(); 2642 } 2643 } 2644 } 2645 2646 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) { 2647 synchronized (mLock) { 2648 if (mTemporaryScreenBrightnessSettingOverride != brightness) { 2649 mTemporaryScreenBrightnessSettingOverride = brightness; 2650 mDirty |= DIRTY_SETTINGS; 2651 updatePowerStateLocked(); 2652 } 2653 } 2654 } 2655 2656 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) { 2657 synchronized (mLock) { 2658 // Note: This condition handles NaN because NaN is not equal to any other 2659 // value, including itself. 2660 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) { 2661 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj; 2662 mDirty |= DIRTY_SETTINGS; 2663 updatePowerStateLocked(); 2664 } 2665 } 2666 } 2667 2668 private void setDozeOverrideFromDreamManagerInternal( 2669 int screenState, int screenBrightness) { 2670 synchronized (mLock) { 2671 if (mDozeScreenStateOverrideFromDreamManager != screenState 2672 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) { 2673 mDozeScreenStateOverrideFromDreamManager = screenState; 2674 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness; 2675 mDirty |= DIRTY_SETTINGS; 2676 updatePowerStateLocked(); 2677 } 2678 } 2679 } 2680 2681 private void powerHintInternal(int hintId, int data) { 2682 nativeSendPowerHint(hintId, data); 2683 } 2684 2685 /** 2686 * Low-level function turn the device off immediately, without trying 2687 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown. 2688 * 2689 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null. 2690 */ 2691 public static void lowLevelShutdown(String reason) { 2692 if (reason == null) { 2693 reason = ""; 2694 } 2695 SystemProperties.set("sys.powerctl", "shutdown," + reason); 2696 } 2697 2698 /** 2699 * Low-level function to reboot the device. On success, this 2700 * function doesn't return. If more than 20 seconds passes from 2701 * the time a reboot is requested, this method returns. 2702 * 2703 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 2704 */ 2705 public static void lowLevelReboot(String reason) { 2706 if (reason == null) { 2707 reason = ""; 2708 } 2709 if (reason.equals(PowerManager.REBOOT_RECOVERY) 2710 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) { 2711 SystemProperties.set("sys.powerctl", "reboot,recovery"); 2712 } else { 2713 SystemProperties.set("sys.powerctl", "reboot," + reason); 2714 } 2715 try { 2716 Thread.sleep(20 * 1000L); 2717 } catch (InterruptedException e) { 2718 Thread.currentThread().interrupt(); 2719 } 2720 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!"); 2721 } 2722 2723 @Override // Watchdog.Monitor implementation 2724 public void monitor() { 2725 // Grab and release lock for watchdog monitor to detect deadlocks. 2726 synchronized (mLock) { 2727 } 2728 } 2729 2730 private void dumpInternal(PrintWriter pw) { 2731 pw.println("POWER MANAGER (dumpsys power)\n"); 2732 2733 final WirelessChargerDetector wcd; 2734 synchronized (mLock) { 2735 pw.println("Power Manager State:"); 2736 pw.println(" mDirty=0x" + Integer.toHexString(mDirty)); 2737 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness)); 2738 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging); 2739 pw.println(" mIsPowered=" + mIsPowered); 2740 pw.println(" mPlugType=" + mPlugType); 2741 pw.println(" mBatteryLevel=" + mBatteryLevel); 2742 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted); 2743 pw.println(" mDockState=" + mDockState); 2744 pw.println(" mStayOn=" + mStayOn); 2745 pw.println(" mProximityPositive=" + mProximityPositive); 2746 pw.println(" mBootCompleted=" + mBootCompleted); 2747 pw.println(" mSystemReady=" + mSystemReady); 2748 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled); 2749 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled); 2750 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 2751 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)); 2752 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity); 2753 pw.println(" mSandmanScheduled=" + mSandmanScheduled); 2754 pw.println(" mSandmanSummoned=" + mSandmanSummoned); 2755 pw.println(" mLowPowerModeEnabled=" + mLowPowerModeEnabled); 2756 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow); 2757 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode); 2758 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode); 2759 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist)); 2760 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist)); 2761 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime)); 2762 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime)); 2763 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime)); 2764 pw.println(" mLastUserActivityTimeNoChangeLights=" 2765 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights)); 2766 pw.println(" mLastInteractivePowerHintTime=" 2767 + TimeUtils.formatUptime(mLastInteractivePowerHintTime)); 2768 pw.println(" mLastScreenBrightnessBoostTime=" 2769 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime)); 2770 pw.println(" mScreenBrightnessBoostInProgress=" 2771 + mScreenBrightnessBoostInProgress); 2772 pw.println(" mDisplayReady=" + mDisplayReady); 2773 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker); 2774 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker); 2775 2776 pw.println(); 2777 pw.println("Settings and Configuration:"); 2778 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig=" 2779 + mDecoupleHalAutoSuspendModeFromDisplayConfig); 2780 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig=" 2781 + mDecoupleHalInteractiveModeFromDisplayConfig); 2782 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig=" 2783 + mWakeUpWhenPluggedOrUnpluggedConfig); 2784 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig=" 2785 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig); 2786 pw.println(" mTheaterModeEnabled=" 2787 + mTheaterModeEnabled); 2788 pw.println(" mSuspendWhenScreenOffDueToProximityConfig=" 2789 + mSuspendWhenScreenOffDueToProximityConfig); 2790 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig); 2791 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig); 2792 pw.println(" mDreamsActivatedOnSleepByDefaultConfig=" 2793 + mDreamsActivatedOnSleepByDefaultConfig); 2794 pw.println(" mDreamsActivatedOnDockByDefaultConfig=" 2795 + mDreamsActivatedOnDockByDefaultConfig); 2796 pw.println(" mDreamsEnabledOnBatteryConfig=" 2797 + mDreamsEnabledOnBatteryConfig); 2798 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig=" 2799 + mDreamsBatteryLevelMinimumWhenPoweredConfig); 2800 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig=" 2801 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig); 2802 pw.println(" mDreamsBatteryLevelDrainCutoffConfig=" 2803 + mDreamsBatteryLevelDrainCutoffConfig); 2804 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting); 2805 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting); 2806 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting); 2807 pw.println(" mDozeAfterScreenOffConfig=" + mDozeAfterScreenOffConfig); 2808 pw.println(" mLowPowerModeSetting=" + mLowPowerModeSetting); 2809 pw.println(" mAutoLowPowerModeConfigured=" + mAutoLowPowerModeConfigured); 2810 pw.println(" mAutoLowPowerModeSnoozing=" + mAutoLowPowerModeSnoozing); 2811 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig); 2812 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig); 2813 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig); 2814 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting); 2815 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting); 2816 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin=" 2817 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced=" 2818 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")"); 2819 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting); 2820 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting); 2821 pw.println(" mScreenAutoBrightnessAdjustmentSetting=" 2822 + mScreenAutoBrightnessAdjustmentSetting); 2823 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting); 2824 pw.println(" mScreenBrightnessOverrideFromWindowManager=" 2825 + mScreenBrightnessOverrideFromWindowManager); 2826 pw.println(" mUserActivityTimeoutOverrideFromWindowManager=" 2827 + mUserActivityTimeoutOverrideFromWindowManager); 2828 pw.println(" mUserInactiveOverrideFromWindowManager=" 2829 + mUserInactiveOverrideFromWindowManager); 2830 pw.println(" mTemporaryScreenBrightnessSettingOverride=" 2831 + mTemporaryScreenBrightnessSettingOverride); 2832 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=" 2833 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride); 2834 pw.println(" mDozeScreenStateOverrideFromDreamManager=" 2835 + mDozeScreenStateOverrideFromDreamManager); 2836 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager=" 2837 + mDozeScreenBrightnessOverrideFromDreamManager); 2838 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum); 2839 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum); 2840 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault); 2841 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled); 2842 2843 final int sleepTimeout = getSleepTimeoutLocked(); 2844 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout); 2845 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 2846 pw.println(); 2847 pw.println("Sleep timeout: " + sleepTimeout + " ms"); 2848 pw.println("Screen off timeout: " + screenOffTimeout + " ms"); 2849 pw.println("Screen dim duration: " + screenDimDuration + " ms"); 2850 2851 pw.println(); 2852 pw.println("UID states:"); 2853 for (int i=0; i<mUidState.size(); i++) { 2854 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i)); 2855 pw.print(": "); pw.println(mUidState.valueAt(i)); 2856 } 2857 2858 pw.println(); 2859 pw.println("Wake Locks: size=" + mWakeLocks.size()); 2860 for (WakeLock wl : mWakeLocks) { 2861 pw.println(" " + wl); 2862 } 2863 2864 pw.println(); 2865 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size()); 2866 for (SuspendBlocker sb : mSuspendBlockers) { 2867 pw.println(" " + sb); 2868 } 2869 2870 pw.println(); 2871 pw.println("Display Power: " + mDisplayPowerCallbacks); 2872 2873 wcd = mWirelessChargerDetector; 2874 } 2875 2876 if (wcd != null) { 2877 wcd.dump(pw); 2878 } 2879 } 2880 2881 private SuspendBlocker createSuspendBlockerLocked(String name) { 2882 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name); 2883 mSuspendBlockers.add(suspendBlocker); 2884 return suspendBlocker; 2885 } 2886 2887 private void incrementBootCount() { 2888 synchronized (mLock) { 2889 int count; 2890 try { 2891 count = Settings.Global.getInt( 2892 getContext().getContentResolver(), Settings.Global.BOOT_COUNT); 2893 } catch (SettingNotFoundException e) { 2894 count = 0; 2895 } 2896 Settings.Global.putInt( 2897 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1); 2898 } 2899 } 2900 2901 private static WorkSource copyWorkSource(WorkSource workSource) { 2902 return workSource != null ? new WorkSource(workSource) : null; 2903 } 2904 2905 private final class BatteryReceiver extends BroadcastReceiver { 2906 @Override 2907 public void onReceive(Context context, Intent intent) { 2908 synchronized (mLock) { 2909 handleBatteryStateChangedLocked(); 2910 } 2911 } 2912 } 2913 2914 private final class DreamReceiver extends BroadcastReceiver { 2915 @Override 2916 public void onReceive(Context context, Intent intent) { 2917 synchronized (mLock) { 2918 scheduleSandmanLocked(); 2919 } 2920 } 2921 } 2922 2923 private final class UserSwitchedReceiver extends BroadcastReceiver { 2924 @Override 2925 public void onReceive(Context context, Intent intent) { 2926 synchronized (mLock) { 2927 handleSettingsChangedLocked(); 2928 } 2929 } 2930 } 2931 2932 private final class DockReceiver extends BroadcastReceiver { 2933 @Override 2934 public void onReceive(Context context, Intent intent) { 2935 synchronized (mLock) { 2936 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 2937 Intent.EXTRA_DOCK_STATE_UNDOCKED); 2938 if (mDockState != dockState) { 2939 mDockState = dockState; 2940 mDirty |= DIRTY_DOCK_STATE; 2941 updatePowerStateLocked(); 2942 } 2943 } 2944 } 2945 } 2946 2947 private final class SettingsObserver extends ContentObserver { 2948 public SettingsObserver(Handler handler) { 2949 super(handler); 2950 } 2951 2952 @Override 2953 public void onChange(boolean selfChange, Uri uri) { 2954 synchronized (mLock) { 2955 handleSettingsChangedLocked(); 2956 } 2957 } 2958 } 2959 2960 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() { 2961 @Override 2962 public void onVrStateChanged(boolean enabled) { 2963 powerHintInternal(POWER_HINT_VR_MODE, enabled ? 1 : 0); 2964 } 2965 }; 2966 2967 /** 2968 * Handler for asynchronous operations performed by the power manager. 2969 */ 2970 private final class PowerManagerHandler extends Handler { 2971 public PowerManagerHandler(Looper looper) { 2972 super(looper, null, true /*async*/); 2973 } 2974 2975 @Override 2976 public void handleMessage(Message msg) { 2977 switch (msg.what) { 2978 case MSG_USER_ACTIVITY_TIMEOUT: 2979 handleUserActivityTimeout(); 2980 break; 2981 case MSG_SANDMAN: 2982 handleSandman(); 2983 break; 2984 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT: 2985 handleScreenBrightnessBoostTimeout(); 2986 break; 2987 } 2988 } 2989 } 2990 2991 /** 2992 * Represents a wake lock that has been acquired by an application. 2993 */ 2994 private final class WakeLock implements IBinder.DeathRecipient { 2995 public final IBinder mLock; 2996 public int mFlags; 2997 public String mTag; 2998 public final String mPackageName; 2999 public WorkSource mWorkSource; 3000 public String mHistoryTag; 3001 public final int mOwnerUid; 3002 public final int mOwnerPid; 3003 public boolean mNotifiedAcquired; 3004 public boolean mDisabled; 3005 3006 public WakeLock(IBinder lock, int flags, String tag, String packageName, 3007 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) { 3008 mLock = lock; 3009 mFlags = flags; 3010 mTag = tag; 3011 mPackageName = packageName; 3012 mWorkSource = copyWorkSource(workSource); 3013 mHistoryTag = historyTag; 3014 mOwnerUid = ownerUid; 3015 mOwnerPid = ownerPid; 3016 } 3017 3018 @Override 3019 public void binderDied() { 3020 PowerManagerService.this.handleWakeLockDeath(this); 3021 } 3022 3023 public boolean hasSameProperties(int flags, String tag, WorkSource workSource, 3024 int ownerUid, int ownerPid) { 3025 return mFlags == flags 3026 && mTag.equals(tag) 3027 && hasSameWorkSource(workSource) 3028 && mOwnerUid == ownerUid 3029 && mOwnerPid == ownerPid; 3030 } 3031 3032 public void updateProperties(int flags, String tag, String packageName, 3033 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) { 3034 if (!mPackageName.equals(packageName)) { 3035 throw new IllegalStateException("Existing wake lock package name changed: " 3036 + mPackageName + " to " + packageName); 3037 } 3038 if (mOwnerUid != ownerUid) { 3039 throw new IllegalStateException("Existing wake lock uid changed: " 3040 + mOwnerUid + " to " + ownerUid); 3041 } 3042 if (mOwnerPid != ownerPid) { 3043 throw new IllegalStateException("Existing wake lock pid changed: " 3044 + mOwnerPid + " to " + ownerPid); 3045 } 3046 mFlags = flags; 3047 mTag = tag; 3048 updateWorkSource(workSource); 3049 mHistoryTag = historyTag; 3050 } 3051 3052 public boolean hasSameWorkSource(WorkSource workSource) { 3053 return Objects.equal(mWorkSource, workSource); 3054 } 3055 3056 public void updateWorkSource(WorkSource workSource) { 3057 mWorkSource = copyWorkSource(workSource); 3058 } 3059 3060 @Override 3061 public String toString() { 3062 return getLockLevelString() 3063 + " '" + mTag + "'" + getLockFlagsString() + (mDisabled ? " DISABLED" : "") 3064 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")"; 3065 } 3066 3067 @SuppressWarnings("deprecation") 3068 private String getLockLevelString() { 3069 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 3070 case PowerManager.FULL_WAKE_LOCK: 3071 return "FULL_WAKE_LOCK "; 3072 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 3073 return "SCREEN_BRIGHT_WAKE_LOCK "; 3074 case PowerManager.SCREEN_DIM_WAKE_LOCK: 3075 return "SCREEN_DIM_WAKE_LOCK "; 3076 case PowerManager.PARTIAL_WAKE_LOCK: 3077 return "PARTIAL_WAKE_LOCK "; 3078 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 3079 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 3080 case PowerManager.DOZE_WAKE_LOCK: 3081 return "DOZE_WAKE_LOCK "; 3082 case PowerManager.DRAW_WAKE_LOCK: 3083 return "DRAW_WAKE_LOCK "; 3084 default: 3085 return "??? "; 3086 } 3087 } 3088 3089 private String getLockFlagsString() { 3090 String result = ""; 3091 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 3092 result += " ACQUIRE_CAUSES_WAKEUP"; 3093 } 3094 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 3095 result += " ON_AFTER_RELEASE"; 3096 } 3097 return result; 3098 } 3099 } 3100 3101 private final class SuspendBlockerImpl implements SuspendBlocker { 3102 private final String mName; 3103 private final String mTraceName; 3104 private int mReferenceCount; 3105 3106 public SuspendBlockerImpl(String name) { 3107 mName = name; 3108 mTraceName = "SuspendBlocker (" + name + ")"; 3109 } 3110 3111 @Override 3112 protected void finalize() throws Throwable { 3113 try { 3114 if (mReferenceCount != 0) { 3115 Slog.wtf(TAG, "Suspend blocker \"" + mName 3116 + "\" was finalized without being released!"); 3117 mReferenceCount = 0; 3118 nativeReleaseSuspendBlocker(mName); 3119 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0); 3120 } 3121 } finally { 3122 super.finalize(); 3123 } 3124 } 3125 3126 @Override 3127 public void acquire() { 3128 synchronized (this) { 3129 mReferenceCount += 1; 3130 if (mReferenceCount == 1) { 3131 if (DEBUG_SPEW) { 3132 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\"."); 3133 } 3134 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0); 3135 nativeAcquireSuspendBlocker(mName); 3136 } 3137 } 3138 } 3139 3140 @Override 3141 public void release() { 3142 synchronized (this) { 3143 mReferenceCount -= 1; 3144 if (mReferenceCount == 0) { 3145 if (DEBUG_SPEW) { 3146 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\"."); 3147 } 3148 nativeReleaseSuspendBlocker(mName); 3149 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0); 3150 } else if (mReferenceCount < 0) { 3151 Slog.wtf(TAG, "Suspend blocker \"" + mName 3152 + "\" was released without being acquired!", new Throwable()); 3153 mReferenceCount = 0; 3154 } 3155 } 3156 } 3157 3158 @Override 3159 public String toString() { 3160 synchronized (this) { 3161 return mName + ": ref count=" + mReferenceCount; 3162 } 3163 } 3164 } 3165 3166 private final class BinderService extends IPowerManager.Stub { 3167 @Override // Binder call 3168 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag, 3169 String packageName, int uid) { 3170 if (uid < 0) { 3171 uid = Binder.getCallingUid(); 3172 } 3173 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null); 3174 } 3175 3176 @Override // Binder call 3177 public void powerHint(int hintId, int data) { 3178 if (!mSystemReady) { 3179 // Service not ready yet, so who the heck cares about power hints, bah. 3180 return; 3181 } 3182 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 3183 powerHintInternal(hintId, data); 3184 } 3185 3186 @Override // Binder call 3187 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName, 3188 WorkSource ws, String historyTag) { 3189 if (lock == null) { 3190 throw new IllegalArgumentException("lock must not be null"); 3191 } 3192 if (packageName == null) { 3193 throw new IllegalArgumentException("packageName must not be null"); 3194 } 3195 PowerManager.validateWakeLockParameters(flags, tag); 3196 3197 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 3198 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) { 3199 mContext.enforceCallingOrSelfPermission( 3200 android.Manifest.permission.DEVICE_POWER, null); 3201 } 3202 if (ws != null && ws.size() != 0) { 3203 mContext.enforceCallingOrSelfPermission( 3204 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 3205 } else { 3206 ws = null; 3207 } 3208 3209 final int uid = Binder.getCallingUid(); 3210 final int pid = Binder.getCallingPid(); 3211 final long ident = Binder.clearCallingIdentity(); 3212 try { 3213 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid); 3214 } finally { 3215 Binder.restoreCallingIdentity(ident); 3216 } 3217 } 3218 3219 @Override // Binder call 3220 public void releaseWakeLock(IBinder lock, int flags) { 3221 if (lock == null) { 3222 throw new IllegalArgumentException("lock must not be null"); 3223 } 3224 3225 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 3226 3227 final long ident = Binder.clearCallingIdentity(); 3228 try { 3229 releaseWakeLockInternal(lock, flags); 3230 } finally { 3231 Binder.restoreCallingIdentity(ident); 3232 } 3233 } 3234 3235 @Override // Binder call 3236 public void updateWakeLockUids(IBinder lock, int[] uids) { 3237 WorkSource ws = null; 3238 3239 if (uids != null) { 3240 ws = new WorkSource(); 3241 // XXX should WorkSource have a way to set uids as an int[] instead of adding them 3242 // one at a time? 3243 for (int i = 0; i < uids.length; i++) { 3244 ws.add(uids[i]); 3245 } 3246 } 3247 updateWakeLockWorkSource(lock, ws, null); 3248 } 3249 3250 @Override // Binder call 3251 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) { 3252 if (lock == null) { 3253 throw new IllegalArgumentException("lock must not be null"); 3254 } 3255 3256 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 3257 if (ws != null && ws.size() != 0) { 3258 mContext.enforceCallingOrSelfPermission( 3259 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 3260 } else { 3261 ws = null; 3262 } 3263 3264 final int callingUid = Binder.getCallingUid(); 3265 final long ident = Binder.clearCallingIdentity(); 3266 try { 3267 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid); 3268 } finally { 3269 Binder.restoreCallingIdentity(ident); 3270 } 3271 } 3272 3273 @Override // Binder call 3274 public boolean isWakeLockLevelSupported(int level) { 3275 final long ident = Binder.clearCallingIdentity(); 3276 try { 3277 return isWakeLockLevelSupportedInternal(level); 3278 } finally { 3279 Binder.restoreCallingIdentity(ident); 3280 } 3281 } 3282 3283 @Override // Binder call 3284 public void userActivity(long eventTime, int event, int flags) { 3285 final long now = SystemClock.uptimeMillis(); 3286 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER) 3287 != PackageManager.PERMISSION_GRANTED 3288 && mContext.checkCallingOrSelfPermission( 3289 android.Manifest.permission.USER_ACTIVITY) 3290 != PackageManager.PERMISSION_GRANTED) { 3291 // Once upon a time applications could call userActivity(). 3292 // Now we require the DEVICE_POWER permission. Log a warning and ignore the 3293 // request instead of throwing a SecurityException so we don't break old apps. 3294 synchronized (mLock) { 3295 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) { 3296 mLastWarningAboutUserActivityPermission = now; 3297 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the " 3298 + "caller does not have DEVICE_POWER or USER_ACTIVITY " 3299 + "permission. Please fix your app! " 3300 + " pid=" + Binder.getCallingPid() 3301 + " uid=" + Binder.getCallingUid()); 3302 } 3303 } 3304 return; 3305 } 3306 3307 if (eventTime > now) { 3308 throw new IllegalArgumentException("event time must not be in the future"); 3309 } 3310 3311 final int uid = Binder.getCallingUid(); 3312 final long ident = Binder.clearCallingIdentity(); 3313 try { 3314 userActivityInternal(eventTime, event, flags, uid); 3315 } finally { 3316 Binder.restoreCallingIdentity(ident); 3317 } 3318 } 3319 3320 @Override // Binder call 3321 public void wakeUp(long eventTime, String reason, String opPackageName) { 3322 if (eventTime > SystemClock.uptimeMillis()) { 3323 throw new IllegalArgumentException("event time must not be in the future"); 3324 } 3325 3326 mContext.enforceCallingOrSelfPermission( 3327 android.Manifest.permission.DEVICE_POWER, null); 3328 3329 final int uid = Binder.getCallingUid(); 3330 final long ident = Binder.clearCallingIdentity(); 3331 try { 3332 wakeUpInternal(eventTime, reason, uid, opPackageName, uid); 3333 } finally { 3334 Binder.restoreCallingIdentity(ident); 3335 } 3336 } 3337 3338 @Override // Binder call 3339 public void goToSleep(long eventTime, int reason, int flags) { 3340 if (eventTime > SystemClock.uptimeMillis()) { 3341 throw new IllegalArgumentException("event time must not be in the future"); 3342 } 3343 3344 mContext.enforceCallingOrSelfPermission( 3345 android.Manifest.permission.DEVICE_POWER, null); 3346 3347 final int uid = Binder.getCallingUid(); 3348 final long ident = Binder.clearCallingIdentity(); 3349 try { 3350 goToSleepInternal(eventTime, reason, flags, uid); 3351 } finally { 3352 Binder.restoreCallingIdentity(ident); 3353 } 3354 } 3355 3356 @Override // Binder call 3357 public void nap(long eventTime) { 3358 if (eventTime > SystemClock.uptimeMillis()) { 3359 throw new IllegalArgumentException("event time must not be in the future"); 3360 } 3361 3362 mContext.enforceCallingOrSelfPermission( 3363 android.Manifest.permission.DEVICE_POWER, null); 3364 3365 final int uid = Binder.getCallingUid(); 3366 final long ident = Binder.clearCallingIdentity(); 3367 try { 3368 napInternal(eventTime, uid); 3369 } finally { 3370 Binder.restoreCallingIdentity(ident); 3371 } 3372 } 3373 3374 @Override // Binder call 3375 public boolean isInteractive() { 3376 final long ident = Binder.clearCallingIdentity(); 3377 try { 3378 return isInteractiveInternal(); 3379 } finally { 3380 Binder.restoreCallingIdentity(ident); 3381 } 3382 } 3383 3384 @Override // Binder call 3385 public boolean isPowerSaveMode() { 3386 final long ident = Binder.clearCallingIdentity(); 3387 try { 3388 return isLowPowerModeInternal(); 3389 } finally { 3390 Binder.restoreCallingIdentity(ident); 3391 } 3392 } 3393 3394 @Override // Binder call 3395 public boolean setPowerSaveMode(boolean mode) { 3396 mContext.enforceCallingOrSelfPermission( 3397 android.Manifest.permission.DEVICE_POWER, null); 3398 final long ident = Binder.clearCallingIdentity(); 3399 try { 3400 return setLowPowerModeInternal(mode); 3401 } finally { 3402 Binder.restoreCallingIdentity(ident); 3403 } 3404 } 3405 3406 @Override // Binder call 3407 public boolean isDeviceIdleMode() { 3408 final long ident = Binder.clearCallingIdentity(); 3409 try { 3410 return isDeviceIdleModeInternal(); 3411 } finally { 3412 Binder.restoreCallingIdentity(ident); 3413 } 3414 } 3415 3416 @Override // Binder call 3417 public boolean isLightDeviceIdleMode() { 3418 final long ident = Binder.clearCallingIdentity(); 3419 try { 3420 return isLightDeviceIdleModeInternal(); 3421 } finally { 3422 Binder.restoreCallingIdentity(ident); 3423 } 3424 } 3425 3426 /** 3427 * Reboots the device. 3428 * 3429 * @param confirm If true, shows a reboot confirmation dialog. 3430 * @param reason The reason for the reboot, or null if none. 3431 * @param wait If true, this call waits for the reboot to complete and does not return. 3432 */ 3433 @Override // Binder call 3434 public void reboot(boolean confirm, String reason, boolean wait) { 3435 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3436 if (PowerManager.REBOOT_RECOVERY.equals(reason) 3437 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) { 3438 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null); 3439 } 3440 3441 final long ident = Binder.clearCallingIdentity(); 3442 try { 3443 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait); 3444 } finally { 3445 Binder.restoreCallingIdentity(ident); 3446 } 3447 } 3448 3449 /** 3450 * Reboots the device into safe mode 3451 * 3452 * @param confirm If true, shows a reboot confirmation dialog. 3453 * @param wait If true, this call waits for the reboot to complete and does not return. 3454 */ 3455 @Override // Binder call 3456 public void rebootSafeMode(boolean confirm, boolean wait) { 3457 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3458 3459 final long ident = Binder.clearCallingIdentity(); 3460 try { 3461 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm, 3462 PowerManager.REBOOT_SAFE_MODE, wait); 3463 } finally { 3464 Binder.restoreCallingIdentity(ident); 3465 } 3466 } 3467 3468 /** 3469 * Shuts down the device. 3470 * 3471 * @param confirm If true, shows a shutdown confirmation dialog. 3472 * @param wait If true, this call waits for the shutdown to complete and does not return. 3473 */ 3474 @Override // Binder call 3475 public void shutdown(boolean confirm, String reason, boolean wait) { 3476 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3477 3478 final long ident = Binder.clearCallingIdentity(); 3479 try { 3480 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait); 3481 } finally { 3482 Binder.restoreCallingIdentity(ident); 3483 } 3484 } 3485 3486 /** 3487 * Crash the runtime (causing a complete restart of the Android framework). 3488 * Requires REBOOT permission. Mostly for testing. Should not return. 3489 */ 3490 @Override // Binder call 3491 public void crash(String message) { 3492 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3493 3494 final long ident = Binder.clearCallingIdentity(); 3495 try { 3496 crashInternal(message); 3497 } finally { 3498 Binder.restoreCallingIdentity(ident); 3499 } 3500 } 3501 3502 /** 3503 * Set the setting that determines whether the device stays on when plugged in. 3504 * The argument is a bit string, with each bit specifying a power source that, 3505 * when the device is connected to that source, causes the device to stay on. 3506 * See {@link android.os.BatteryManager} for the list of power sources that 3507 * can be specified. Current values include 3508 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 3509 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 3510 * 3511 * Used by "adb shell svc power stayon ..." 3512 * 3513 * @param val an {@code int} containing the bits that specify which power sources 3514 * should cause the device to stay on. 3515 */ 3516 @Override // Binder call 3517 public void setStayOnSetting(int val) { 3518 int uid = Binder.getCallingUid(); 3519 // if uid is of root's, we permit this operation straight away 3520 if (uid != Process.ROOT_UID) { 3521 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid, 3522 Settings.getPackageNameForUid(mContext, uid), true)) { 3523 return; 3524 } 3525 } 3526 3527 final long ident = Binder.clearCallingIdentity(); 3528 try { 3529 setStayOnSettingInternal(val); 3530 } finally { 3531 Binder.restoreCallingIdentity(ident); 3532 } 3533 } 3534 3535 /** 3536 * Used by the settings application and brightness control widgets to 3537 * temporarily override the current screen brightness setting so that the 3538 * user can observe the effect of an intended settings change without applying 3539 * it immediately. 3540 * 3541 * The override will be canceled when the setting value is next updated. 3542 * 3543 * @param brightness The overridden brightness. 3544 * 3545 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS 3546 */ 3547 @Override // Binder call 3548 public void setTemporaryScreenBrightnessSettingOverride(int brightness) { 3549 mContext.enforceCallingOrSelfPermission( 3550 android.Manifest.permission.DEVICE_POWER, null); 3551 3552 final long ident = Binder.clearCallingIdentity(); 3553 try { 3554 setTemporaryScreenBrightnessSettingOverrideInternal(brightness); 3555 } finally { 3556 Binder.restoreCallingIdentity(ident); 3557 } 3558 } 3559 3560 /** 3561 * Used by the settings application and brightness control widgets to 3562 * temporarily override the current screen auto-brightness adjustment setting so that the 3563 * user can observe the effect of an intended settings change without applying 3564 * it immediately. 3565 * 3566 * The override will be canceled when the setting value is next updated. 3567 * 3568 * @param adj The overridden brightness, or Float.NaN to disable the override. 3569 * 3570 * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ 3571 */ 3572 @Override // Binder call 3573 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) { 3574 mContext.enforceCallingOrSelfPermission( 3575 android.Manifest.permission.DEVICE_POWER, null); 3576 3577 final long ident = Binder.clearCallingIdentity(); 3578 try { 3579 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj); 3580 } finally { 3581 Binder.restoreCallingIdentity(ident); 3582 } 3583 } 3584 3585 /** 3586 * Used by the phone application to make the attention LED flash when ringing. 3587 */ 3588 @Override // Binder call 3589 public void setAttentionLight(boolean on, int color) { 3590 mContext.enforceCallingOrSelfPermission( 3591 android.Manifest.permission.DEVICE_POWER, null); 3592 3593 final long ident = Binder.clearCallingIdentity(); 3594 try { 3595 setAttentionLightInternal(on, color); 3596 } finally { 3597 Binder.restoreCallingIdentity(ident); 3598 } 3599 } 3600 3601 @Override // Binder call 3602 public void boostScreenBrightness(long eventTime) { 3603 if (eventTime > SystemClock.uptimeMillis()) { 3604 throw new IllegalArgumentException("event time must not be in the future"); 3605 } 3606 3607 mContext.enforceCallingOrSelfPermission( 3608 android.Manifest.permission.DEVICE_POWER, null); 3609 3610 final int uid = Binder.getCallingUid(); 3611 final long ident = Binder.clearCallingIdentity(); 3612 try { 3613 boostScreenBrightnessInternal(eventTime, uid); 3614 } finally { 3615 Binder.restoreCallingIdentity(ident); 3616 } 3617 } 3618 3619 @Override // Binder call 3620 public boolean isScreenBrightnessBoosted() { 3621 final long ident = Binder.clearCallingIdentity(); 3622 try { 3623 return isScreenBrightnessBoostedInternal(); 3624 } finally { 3625 Binder.restoreCallingIdentity(ident); 3626 } 3627 } 3628 3629 @Override // Binder call 3630 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3631 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP) 3632 != PackageManager.PERMISSION_GRANTED) { 3633 pw.println("Permission Denial: can't dump PowerManager from from pid=" 3634 + Binder.getCallingPid() 3635 + ", uid=" + Binder.getCallingUid()); 3636 return; 3637 } 3638 3639 final long ident = Binder.clearCallingIdentity(); 3640 try { 3641 dumpInternal(pw); 3642 } finally { 3643 Binder.restoreCallingIdentity(ident); 3644 } 3645 } 3646 } 3647 3648 private final class LocalService extends PowerManagerInternal { 3649 @Override 3650 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) { 3651 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT 3652 || screenBrightness > PowerManager.BRIGHTNESS_ON) { 3653 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 3654 } 3655 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness); 3656 } 3657 3658 @Override 3659 public void setButtonBrightnessOverrideFromWindowManager(int screenBrightness) { 3660 // Do nothing. 3661 // Button lights are not currently supported in the new implementation. 3662 } 3663 3664 @Override 3665 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) { 3666 switch (screenState) { 3667 case Display.STATE_UNKNOWN: 3668 case Display.STATE_OFF: 3669 case Display.STATE_DOZE: 3670 case Display.STATE_DOZE_SUSPEND: 3671 case Display.STATE_ON: 3672 break; 3673 default: 3674 screenState = Display.STATE_UNKNOWN; 3675 break; 3676 } 3677 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT 3678 || screenBrightness > PowerManager.BRIGHTNESS_ON) { 3679 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 3680 } 3681 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness); 3682 } 3683 3684 @Override 3685 public void setUserInactiveOverrideFromWindowManager() { 3686 setUserInactiveOverrideFromWindowManagerInternal(); 3687 } 3688 3689 @Override 3690 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) { 3691 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis); 3692 } 3693 3694 @Override 3695 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { 3696 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); 3697 } 3698 3699 @Override 3700 public boolean getLowPowerModeEnabled() { 3701 synchronized (mLock) { 3702 return mLowPowerModeEnabled; 3703 } 3704 } 3705 3706 @Override 3707 public void registerLowPowerModeObserver(LowPowerModeListener listener) { 3708 synchronized (mLock) { 3709 mLowPowerModeListeners.add(listener); 3710 } 3711 } 3712 3713 @Override 3714 public boolean setDeviceIdleMode(boolean enabled) { 3715 return setDeviceIdleModeInternal(enabled); 3716 } 3717 3718 @Override 3719 public boolean setLightDeviceIdleMode(boolean enabled) { 3720 return setLightDeviceIdleModeInternal(enabled); 3721 } 3722 3723 @Override 3724 public void setDeviceIdleWhitelist(int[] appids) { 3725 setDeviceIdleWhitelistInternal(appids); 3726 } 3727 3728 @Override 3729 public void setDeviceIdleTempWhitelist(int[] appids) { 3730 setDeviceIdleTempWhitelistInternal(appids); 3731 } 3732 3733 @Override 3734 public void updateUidProcState(int uid, int procState) { 3735 updateUidProcStateInternal(uid, procState); 3736 } 3737 3738 @Override 3739 public void uidGone(int uid) { 3740 uidGoneInternal(uid); 3741 } 3742 3743 @Override 3744 public void powerHint(int hintId, int data) { 3745 powerHintInternal(hintId, data); 3746 } 3747 } 3748 } 3749