PowerManagerService.java revision 1a868b7981ca5f52e893fdf9f8f538c9d5ce241d
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 17package com.android.server.power; 18 19import com.android.internal.app.IBatteryStats; 20import com.android.server.BatteryService; 21import com.android.server.EventLogTags; 22import com.android.server.LightsService; 23import com.android.server.TwilightService; 24import com.android.server.Watchdog; 25import com.android.server.am.ActivityManagerService; 26import com.android.server.display.DisplayManagerService; 27 28import android.Manifest; 29import android.content.BroadcastReceiver; 30import android.content.ContentResolver; 31import android.content.Context; 32import android.content.Intent; 33import android.content.IntentFilter; 34import android.content.pm.PackageManager; 35import android.content.res.Resources; 36import android.database.ContentObserver; 37import android.net.Uri; 38import android.os.BatteryManager; 39import android.os.Binder; 40import android.os.Handler; 41import android.os.HandlerThread; 42import android.os.IBinder; 43import android.os.IPowerManager; 44import android.os.Looper; 45import android.os.Message; 46import android.os.PowerManager; 47import android.os.Process; 48import android.os.RemoteException; 49import android.os.ServiceManager; 50import android.os.SystemClock; 51import android.os.WorkSource; 52import android.provider.Settings; 53import android.service.dreams.IDreamManager; 54import android.util.EventLog; 55import android.util.Log; 56import android.util.Slog; 57import android.util.TimeUtils; 58import android.view.WindowManagerPolicy; 59 60import java.io.FileDescriptor; 61import java.io.IOException; 62import java.io.PrintWriter; 63import java.util.ArrayList; 64 65import libcore.util.Objects; 66 67/** 68 * The power manager service is responsible for coordinating power management 69 * functions on the device. 70 */ 71public final class PowerManagerService extends IPowerManager.Stub 72 implements Watchdog.Monitor { 73 private static final String TAG = "PowerManagerService"; 74 75 private static final boolean DEBUG = false; 76 private static final boolean DEBUG_SPEW = DEBUG && true; 77 78 // Message: Sent when a user activity timeout occurs to update the power state. 79 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1; 80 // Message: Sent when the device enters or exits a napping or dreaming state. 81 private static final int MSG_SANDMAN = 2; 82 83 // Dirty bit: mWakeLocks changed 84 private static final int DIRTY_WAKE_LOCKS = 1 << 0; 85 // Dirty bit: mWakefulness changed 86 private static final int DIRTY_WAKEFULNESS = 1 << 1; 87 // Dirty bit: user activity was poked or may have timed out 88 private static final int DIRTY_USER_ACTIVITY = 1 << 2; 89 // Dirty bit: actual display power state was updated asynchronously 90 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3; 91 // Dirty bit: mBootCompleted changed 92 private static final int DIRTY_BOOT_COMPLETED = 1 << 4; 93 // Dirty bit: settings changed 94 private static final int DIRTY_SETTINGS = 1 << 5; 95 // Dirty bit: mIsPowered changed 96 private static final int DIRTY_IS_POWERED = 1 << 6; 97 // Dirty bit: mStayOn changed 98 private static final int DIRTY_STAY_ON = 1 << 7; 99 // Dirty bit: battery state changed 100 private static final int DIRTY_BATTERY_STATE = 1 << 8; 101 102 // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp(). 103 // The screen should be off or in the process of being turned off by the display controller. 104 private static final int WAKEFULNESS_ASLEEP = 0; 105 // Wakefulness: The device is fully awake. It can be put to sleep by a call to goToSleep(). 106 // When the user activity timeout expires, the device may start napping. 107 private static final int WAKEFULNESS_AWAKE = 1; 108 // Wakefulness: The device is napping. It is deciding whether to dream or go to sleep 109 // but hasn't gotten around to it yet. It can be awoken by a call to wakeUp(), which 110 // ends the nap. User activity may brighten the screen but does not end the nap. 111 private static final int WAKEFULNESS_NAPPING = 2; 112 // Wakefulness: The device is dreaming. It can be awoken by a call to wakeUp(), 113 // which ends the dream. The device goes to sleep when goToSleep() is called, when 114 // the dream ends or when unplugged. 115 // User activity may brighten the screen but does not end the dream. 116 private static final int WAKEFULNESS_DREAMING = 3; 117 118 // Summarizes the state of all active wakelocks. 119 private static final int WAKE_LOCK_CPU = 1 << 0; 120 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1; 121 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2; 122 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3; 123 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4; 124 125 // Summarizes the user activity state. 126 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0; 127 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1; 128 129 // Default and minimum screen off timeout in milliseconds. 130 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000; 131 private static final int MINIMUM_SCREEN_OFF_TIMEOUT = 10 * 1000; 132 133 // The screen dim duration, in seconds. 134 // This is subtracted from the end of the screen off timeout so the 135 // minimum screen off timeout should be longer than this. 136 private static final int SCREEN_DIM_DURATION = 7 * 1000; 137 138 private Context mContext; 139 private LightsService mLightsService; 140 private BatteryService mBatteryService; 141 private IBatteryStats mBatteryStats; 142 private HandlerThread mHandlerThread; 143 private PowerManagerHandler mHandler; 144 private WindowManagerPolicy mPolicy; 145 private Notifier mNotifier; 146 private DisplayPowerController mDisplayPowerController; 147 private SettingsObserver mSettingsObserver; 148 private IDreamManager mDreamManager; 149 private LightsService.Light mAttentionLight; 150 151 private final Object mLock = new Object(); 152 153 // A bitfield that indicates what parts of the power state have 154 // changed and need to be recalculated. 155 private int mDirty; 156 157 // Indicates whether the device is awake or asleep or somewhere in between. 158 // This is distinct from the screen power state, which is managed separately. 159 private int mWakefulness; 160 161 // True if MSG_SANDMAN has been scheduled. 162 private boolean mSandmanScheduled; 163 164 // Table of all suspend blockers. 165 // There should only be a few of these. 166 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>(); 167 168 // Table of all wake locks acquired by applications. 169 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>(); 170 171 // A bitfield that summarizes the state of all active wakelocks. 172 private int mWakeLockSummary; 173 174 // If true, instructs the display controller to wait for the proximity sensor to 175 // go negative before turning the screen on. 176 private boolean mRequestWaitForNegativeProximity; 177 178 // Timestamp of the last time the device was awoken or put to sleep. 179 private long mLastWakeTime; 180 private long mLastSleepTime; 181 182 // True if we need to send a wake up or go to sleep finished notification 183 // when the display is ready. 184 private boolean mSendWakeUpFinishedNotificationWhenReady; 185 private boolean mSendGoToSleepFinishedNotificationWhenReady; 186 187 // Timestamp of the last call to user activity. 188 private long mLastUserActivityTime; 189 private long mLastUserActivityTimeNoChangeLights; 190 191 // A bitfield that summarizes the effect of the user activity timer. 192 // A zero value indicates that the user activity timer has expired. 193 private int mUserActivitySummary; 194 195 // The desired display power state. The actual state may lag behind the 196 // requested because it is updated asynchronously by the display power controller. 197 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest(); 198 199 // The time the screen was last turned off, in elapsedRealtime() timebase. 200 private long mLastScreenOffEventElapsedRealTime; 201 202 // True if the display power state has been fully applied, which means the display 203 // is actually on or actually off or whatever was requested. 204 private boolean mDisplayReady; 205 206 // True if holding a wake-lock to block suspend of the CPU. 207 private boolean mHoldingWakeLockSuspendBlocker; 208 209 // The suspend blocker used to keep the CPU alive when wake locks have been acquired. 210 private final SuspendBlocker mWakeLockSuspendBlocker; 211 212 // True if systemReady() has been called. 213 private boolean mSystemReady; 214 215 // True if boot completed occurred. We keep the screen on until this happens. 216 private boolean mBootCompleted; 217 218 // True if the device is plugged into a power source. 219 private boolean mIsPowered; 220 221 // True if the device should wake up when plugged or unplugged. 222 private boolean mWakeUpWhenPluggedOrUnpluggedConfig; 223 224 // True if dreams are supported on this device. 225 private boolean mDreamsSupportedConfig; 226 227 // True if dreams are enabled by the user. 228 private boolean mDreamsEnabledSetting; 229 230 // True if dreams should be activated on sleep. 231 private boolean mDreamsActivateOnSleepSetting; 232 233 // The screen off timeout setting value in milliseconds. 234 private int mScreenOffTimeoutSetting; 235 236 // The maximum allowable screen off timeout according to the device 237 // administration policy. Overrides other settings. 238 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE; 239 240 // The stay on while plugged in setting. 241 // A bitfield of battery conditions under which to make the screen stay on. 242 private int mStayOnWhilePluggedInSetting; 243 244 // True if the device should stay on. 245 private boolean mStayOn; 246 247 // Screen brightness setting limits. 248 private int mScreenBrightnessSettingMinimum; 249 private int mScreenBrightnessSettingMaximum; 250 private int mScreenBrightnessSettingDefault; 251 252 // The screen brightness setting, from 0 to 255. 253 // Use -1 if no value has been set. 254 private int mScreenBrightnessSetting; 255 256 // The screen auto-brightness adjustment setting, from -1 to 1. 257 // Use 0 if there is no adjustment. 258 private float mScreenAutoBrightnessAdjustmentSetting; 259 260 // The screen brightness mode. 261 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants. 262 private int mScreenBrightnessModeSetting; 263 264 // The screen brightness setting override from the window manager 265 // to allow the current foreground activity to override the brightness. 266 // Use -1 to disable. 267 private int mScreenBrightnessOverrideFromWindowManager = -1; 268 269 // The screen brightness setting override from the settings application 270 // to temporarily adjust the brightness until next updated, 271 // Use -1 to disable. 272 private int mTemporaryScreenBrightnessSettingOverride = -1; 273 274 // The screen brightness adjustment setting override from the settings 275 // application to temporarily adjust the auto-brightness adjustment factor 276 // until next updated, in the range -1..1. 277 // Use NaN to disable. 278 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 279 280 private native void nativeInit(); 281 private static native void nativeShutdown(); 282 private static native void nativeReboot(String reason) throws IOException; 283 284 private static native void nativeSetPowerState(boolean screenOn, boolean screenBright); 285 private static native void nativeAcquireSuspendBlocker(String name); 286 private static native void nativeReleaseSuspendBlocker(String name); 287 288 static native void nativeSetScreenState(boolean on); 289 290 public PowerManagerService() { 291 synchronized (mLock) { 292 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService"); 293 mWakeLockSuspendBlocker.acquire(); 294 mHoldingWakeLockSuspendBlocker = true; 295 mWakefulness = WAKEFULNESS_AWAKE; 296 } 297 298 nativeInit(); 299 } 300 301 /** 302 * Initialize the power manager. 303 * Must be called before any other functions within the power manager are called. 304 */ 305 public void init(Context context, LightsService ls, 306 ActivityManagerService am, BatteryService bs, IBatteryStats bss, 307 DisplayManagerService dm) { 308 mContext = context; 309 mLightsService = ls; 310 mBatteryService = bs; 311 mBatteryStats = bss; 312 mHandlerThread = new HandlerThread(TAG); 313 mHandlerThread.start(); 314 mHandler = new PowerManagerHandler(mHandlerThread.getLooper()); 315 316 Watchdog.getInstance().addMonitor(this); 317 } 318 319 public void setPolicy(WindowManagerPolicy policy) { 320 synchronized (mLock) { 321 mPolicy = policy; 322 } 323 } 324 325 public void systemReady(TwilightService twilight) { 326 synchronized (mLock) { 327 mSystemReady = true; 328 329 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); 330 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting(); 331 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting(); 332 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting(); 333 334 mNotifier = new Notifier(mHandler.getLooper(), mContext, mBatteryStats, 335 createSuspendBlockerLocked("PowerManagerService.Broadcasts"), 336 mPolicy, mScreenOnListener); 337 mDisplayPowerController = new DisplayPowerController(mHandler.getLooper(), 338 mContext, mNotifier, mLightsService, twilight, 339 createSuspendBlockerLocked("PowerManagerService.Display"), 340 mDisplayPowerControllerCallbacks, mHandler); 341 342 mSettingsObserver = new SettingsObserver(mHandler); 343 mAttentionLight = mLightsService.getLight(LightsService.LIGHT_ID_ATTENTION); 344 345 // Register for broadcasts from other components of the system. 346 IntentFilter filter = new IntentFilter(); 347 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 348 mContext.registerReceiver(new BatteryReceiver(), filter); 349 350 filter = new IntentFilter(); 351 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 352 mContext.registerReceiver(new BootCompletedReceiver(), filter); 353 354 filter = new IntentFilter(); 355 filter.addAction(Intent.ACTION_DOCK_EVENT); 356 mContext.registerReceiver(new DockReceiver(), filter); 357 358 // Register for settings changes. 359 final ContentResolver resolver = mContext.getContentResolver(); 360 resolver.registerContentObserver(Settings.Secure.getUriFor( 361 Settings.Secure.SCREENSAVER_ENABLED), false, mSettingsObserver); 362 resolver.registerContentObserver(Settings.Secure.getUriFor( 363 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP), false, mSettingsObserver); 364 resolver.registerContentObserver(Settings.System.getUriFor( 365 Settings.System.SCREEN_OFF_TIMEOUT), false, mSettingsObserver); 366 resolver.registerContentObserver(Settings.System.getUriFor( 367 Settings.System.STAY_ON_WHILE_PLUGGED_IN), false, mSettingsObserver); 368 resolver.registerContentObserver(Settings.System.getUriFor( 369 Settings.System.SCREEN_BRIGHTNESS), false, mSettingsObserver); 370 resolver.registerContentObserver(Settings.System.getUriFor( 371 Settings.System.SCREEN_BRIGHTNESS_MODE), false, mSettingsObserver); 372 373 // Go. 374 readConfigurationLocked(); 375 updateSettingsLocked(); 376 mDirty |= DIRTY_BATTERY_STATE; 377 updatePowerStateLocked(); 378 } 379 } 380 381 private void readConfigurationLocked() { 382 final Resources resources = mContext.getResources(); 383 384 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean( 385 com.android.internal.R.bool.config_unplugTurnsOnScreen); 386 mDreamsSupportedConfig = resources.getBoolean( 387 com.android.internal.R.bool.config_enableDreams); 388 } 389 390 private void updateSettingsLocked() { 391 final ContentResolver resolver = mContext.getContentResolver(); 392 393 mDreamsEnabledSetting = (Settings.Secure.getInt(resolver, 394 Settings.Secure.SCREENSAVER_ENABLED, 0) != 0); 395 mDreamsActivateOnSleepSetting = (Settings.Secure.getInt(resolver, 396 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 0) != 0); 397 mScreenOffTimeoutSetting = Settings.System.getInt(resolver, 398 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT); 399 mStayOnWhilePluggedInSetting = Settings.System.getInt(resolver, 400 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 401 BatteryManager.BATTERY_PLUGGED_AC); 402 403 final int oldScreenBrightnessSetting = mScreenBrightnessSetting; 404 mScreenBrightnessSetting = Settings.System.getInt(resolver, 405 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault); 406 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) { 407 mTemporaryScreenBrightnessSettingOverride = -1; 408 } 409 410 final float oldScreenAutoBrightnessAdjustmentSetting = 411 mScreenAutoBrightnessAdjustmentSetting; 412 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloat(resolver, 413 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f); 414 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) { 415 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = -1; 416 } 417 418 mScreenBrightnessModeSetting = Settings.System.getInt(resolver, 419 Settings.System.SCREEN_BRIGHTNESS_MODE, 420 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); 421 422 mDirty |= DIRTY_SETTINGS; 423 } 424 425 private void handleSettingsChangedLocked() { 426 updateSettingsLocked(); 427 updatePowerStateLocked(); 428 } 429 430 @Override // Binder call 431 public void acquireWakeLock(IBinder lock, int flags, String tag, WorkSource ws) { 432 if (lock == null) { 433 throw new IllegalArgumentException("lock must not be null"); 434 } 435 PowerManager.validateWakeLockParameters(flags, tag); 436 437 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 438 if (ws != null && ws.size() != 0) { 439 mContext.enforceCallingOrSelfPermission( 440 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 441 } else { 442 ws = null; 443 } 444 445 final int uid = Binder.getCallingUid(); 446 final int pid = Binder.getCallingPid(); 447 final long ident = Binder.clearCallingIdentity(); 448 try { 449 acquireWakeLockInternal(lock, flags, tag, ws, uid, pid); 450 } finally { 451 Binder.restoreCallingIdentity(ident); 452 } 453 } 454 455 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, WorkSource ws, 456 int uid, int pid) { 457 synchronized (mLock) { 458 if (DEBUG_SPEW) { 459 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock) 460 + ", flags=0x" + Integer.toHexString(flags) 461 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid); 462 } 463 464 WakeLock wakeLock; 465 int index = findWakeLockIndexLocked(lock); 466 if (index >= 0) { 467 wakeLock = mWakeLocks.get(index); 468 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) { 469 // Update existing wake lock. This shouldn't happen but is harmless. 470 notifyWakeLockReleasedLocked(wakeLock); 471 wakeLock.updateProperties(flags, tag, ws, uid, pid); 472 notifyWakeLockAcquiredLocked(wakeLock); 473 } 474 } else { 475 wakeLock = new WakeLock(lock, flags, tag, ws, uid, pid); 476 try { 477 lock.linkToDeath(wakeLock, 0); 478 } catch (RemoteException ex) { 479 throw new IllegalArgumentException("Wake lock is already dead."); 480 } 481 notifyWakeLockAcquiredLocked(wakeLock); 482 mWakeLocks.add(wakeLock); 483 } 484 485 applyWakeLockFlagsOnAcquireLocked(wakeLock); 486 mDirty |= DIRTY_WAKE_LOCKS; 487 updatePowerStateLocked(); 488 } 489 } 490 491 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) { 492 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 493 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 494 } 495 } 496 497 @Override // Binder call 498 public void releaseWakeLock(IBinder lock, int flags) { 499 if (lock == null) { 500 throw new IllegalArgumentException("lock must not be null"); 501 } 502 503 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 504 505 final long ident = Binder.clearCallingIdentity(); 506 try { 507 releaseWakeLockInternal(lock, flags); 508 } finally { 509 Binder.restoreCallingIdentity(ident); 510 } 511 } 512 513 private void releaseWakeLockInternal(IBinder lock, int flags) { 514 synchronized (mLock) { 515 if (DEBUG_SPEW) { 516 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 517 + ", flags=0x" + Integer.toHexString(flags)); 518 } 519 520 int index = findWakeLockIndexLocked(lock); 521 if (index < 0) { 522 return; 523 } 524 525 WakeLock wakeLock = mWakeLocks.get(index); 526 mWakeLocks.remove(index); 527 notifyWakeLockReleasedLocked(wakeLock); 528 wakeLock.mLock.unlinkToDeath(wakeLock, 0); 529 530 if ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0) { 531 mRequestWaitForNegativeProximity = true; 532 } 533 534 applyWakeLockFlagsOnReleaseLocked(wakeLock); 535 mDirty |= DIRTY_WAKE_LOCKS; 536 updatePowerStateLocked(); 537 } 538 } 539 540 private void handleWakeLockDeath(WakeLock wakeLock) { 541 synchronized (mLock) { 542 if (DEBUG_SPEW) { 543 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)); 544 } 545 546 int index = mWakeLocks.indexOf(wakeLock); 547 if (index < 0) { 548 return; 549 } 550 551 mWakeLocks.remove(index); 552 notifyWakeLockReleasedLocked(wakeLock); 553 554 applyWakeLockFlagsOnReleaseLocked(wakeLock); 555 mDirty |= DIRTY_WAKE_LOCKS; 556 updatePowerStateLocked(); 557 } 558 } 559 560 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) { 561 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 562 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 563 PowerManager.USER_ACTIVITY_EVENT_OTHER, 564 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS, 565 wakeLock.mOwnerUid); 566 } 567 } 568 569 @Override // Binder call 570 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) { 571 if (lock == null) { 572 throw new IllegalArgumentException("lock must not be null"); 573 } 574 575 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 576 if (ws != null && ws.size() != 0) { 577 mContext.enforceCallingOrSelfPermission( 578 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 579 } else { 580 ws = null; 581 } 582 583 final long ident = Binder.clearCallingIdentity(); 584 try { 585 updateWakeLockWorkSourceInternal(lock, ws); 586 } finally { 587 Binder.restoreCallingIdentity(ident); 588 } 589 } 590 591 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws) { 592 synchronized (mLock) { 593 int index = findWakeLockIndexLocked(lock); 594 if (index < 0) { 595 throw new IllegalArgumentException("Wake lock not active"); 596 } 597 598 WakeLock wakeLock = mWakeLocks.get(index); 599 if (!wakeLock.hasSameWorkSource(ws)) { 600 notifyWakeLockReleasedLocked(wakeLock); 601 wakeLock.updateWorkSource(ws); 602 notifyWakeLockAcquiredLocked(wakeLock); 603 } 604 } 605 } 606 607 private int findWakeLockIndexLocked(IBinder lock) { 608 final int count = mWakeLocks.size(); 609 for (int i = 0; i < count; i++) { 610 if (mWakeLocks.get(i).mLock == lock) { 611 return i; 612 } 613 } 614 return -1; 615 } 616 617 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) { 618 if (mSystemReady) { 619 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, 620 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource); 621 } 622 } 623 624 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) { 625 if (mSystemReady) { 626 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, 627 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource); 628 } 629 } 630 631 @Override // Binder call 632 public boolean isWakeLockLevelSupported(int level) { 633 final long ident = Binder.clearCallingIdentity(); 634 try { 635 return isWakeLockLevelSupportedInternal(level); 636 } finally { 637 Binder.restoreCallingIdentity(ident); 638 } 639 } 640 641 private boolean isWakeLockLevelSupportedInternal(int level) { 642 synchronized (mLock) { 643 switch (level) { 644 case PowerManager.PARTIAL_WAKE_LOCK: 645 case PowerManager.SCREEN_DIM_WAKE_LOCK: 646 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 647 case PowerManager.FULL_WAKE_LOCK: 648 return true; 649 650 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 651 return mSystemReady && mDisplayPowerController.isProximitySensorAvailable(); 652 653 default: 654 return false; 655 } 656 } 657 } 658 659 @Override // Binder call 660 public void userActivity(long eventTime, int event, int flags) { 661 if (eventTime > SystemClock.uptimeMillis()) { 662 throw new IllegalArgumentException("event time must not be in the future"); 663 } 664 665 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 666 667 final int uid = Binder.getCallingUid(); 668 final long ident = Binder.clearCallingIdentity(); 669 try { 670 userActivityInternal(eventTime, event, flags, uid); 671 } finally { 672 Binder.restoreCallingIdentity(ident); 673 } 674 } 675 676 // Called from native code. 677 private void userActivityFromNative(long eventTime, int event, int flags) { 678 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID); 679 } 680 681 private void userActivityInternal(long eventTime, int event, int flags, int uid) { 682 synchronized (mLock) { 683 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) { 684 updatePowerStateLocked(); 685 } 686 } 687 } 688 689 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) { 690 if (DEBUG_SPEW) { 691 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime 692 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags) 693 + ", uid=" + uid); 694 } 695 696 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime 697 || mWakefulness == WAKEFULNESS_ASLEEP || !mBootCompleted || !mSystemReady) { 698 return false; 699 } 700 701 mNotifier.onUserActivity(event, uid); 702 703 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) { 704 if (eventTime > mLastUserActivityTimeNoChangeLights 705 && eventTime > mLastUserActivityTime) { 706 mLastUserActivityTimeNoChangeLights = eventTime; 707 mDirty |= DIRTY_USER_ACTIVITY; 708 return true; 709 } 710 } else { 711 if (eventTime > mLastUserActivityTime) { 712 mLastUserActivityTime = eventTime; 713 mDirty |= DIRTY_USER_ACTIVITY; 714 return true; 715 } 716 } 717 return false; 718 } 719 720 @Override // Binder call 721 public void wakeUp(long eventTime) { 722 if (eventTime > SystemClock.uptimeMillis()) { 723 throw new IllegalArgumentException("event time must not be in the future"); 724 } 725 726 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 727 728 final long ident = Binder.clearCallingIdentity(); 729 try { 730 wakeUpInternal(eventTime); 731 } finally { 732 Binder.restoreCallingIdentity(ident); 733 } 734 } 735 736 // Called from native code. 737 private void wakeUpFromNative(long eventTime) { 738 wakeUpInternal(eventTime); 739 } 740 741 private void wakeUpInternal(long eventTime) { 742 synchronized (mLock) { 743 if (wakeUpNoUpdateLocked(eventTime)) { 744 updatePowerStateLocked(); 745 } 746 } 747 } 748 749 private boolean wakeUpNoUpdateLocked(long eventTime) { 750 if (DEBUG_SPEW) { 751 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime); 752 } 753 754 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE 755 || !mBootCompleted || !mSystemReady) { 756 return false; 757 } 758 759 switch (mWakefulness) { 760 case WAKEFULNESS_ASLEEP: 761 Slog.i(TAG, "Waking up from sleep..."); 762 mNotifier.onWakeUpStarted(); 763 mSendWakeUpFinishedNotificationWhenReady = true; 764 mSendGoToSleepFinishedNotificationWhenReady = false; 765 break; 766 case WAKEFULNESS_DREAMING: 767 Slog.i(TAG, "Waking up from dream..."); 768 break; 769 case WAKEFULNESS_NAPPING: 770 Slog.i(TAG, "Waking up from nap..."); 771 break; 772 } 773 774 mLastWakeTime = eventTime; 775 mWakefulness = WAKEFULNESS_AWAKE; 776 mDirty |= DIRTY_WAKEFULNESS; 777 778 userActivityNoUpdateLocked( 779 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 780 return true; 781 } 782 783 @Override // Binder call 784 public void goToSleep(long eventTime, int reason) { 785 if (eventTime > SystemClock.uptimeMillis()) { 786 throw new IllegalArgumentException("event time must not be in the future"); 787 } 788 789 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 790 791 final long ident = Binder.clearCallingIdentity(); 792 try { 793 goToSleepInternal(eventTime, reason); 794 } finally { 795 Binder.restoreCallingIdentity(ident); 796 } 797 } 798 799 // Called from native code. 800 private void goToSleepFromNative(long eventTime, int reason) { 801 goToSleepInternal(eventTime, reason); 802 } 803 804 private void goToSleepInternal(long eventTime, int reason) { 805 synchronized (mLock) { 806 if (goToSleepNoUpdateLocked(eventTime, reason)) { 807 updatePowerStateLocked(); 808 } 809 } 810 } 811 812 private boolean goToSleepNoUpdateLocked(long eventTime, int reason) { 813 if (DEBUG_SPEW) { 814 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime + ", reason=" + reason); 815 } 816 817 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP 818 || !mBootCompleted || !mSystemReady) { 819 return false; 820 } 821 822 switch (reason) { 823 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN: 824 Slog.i(TAG, "Going to sleep due to device administration policy..."); 825 break; 826 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT: 827 Slog.i(TAG, "Going to sleep due to screen timeout..."); 828 break; 829 default: 830 Slog.i(TAG, "Going to sleep by user request..."); 831 reason = PowerManager.GO_TO_SLEEP_REASON_USER; 832 break; 833 } 834 835 mLastSleepTime = eventTime; 836 mDirty |= DIRTY_WAKEFULNESS; 837 mWakefulness = WAKEFULNESS_ASLEEP; 838 mNotifier.onGoToSleepStarted(reason); 839 mSendGoToSleepFinishedNotificationWhenReady = true; 840 mSendWakeUpFinishedNotificationWhenReady = false; 841 842 // Report the number of wake locks that will be cleared by going to sleep. 843 int numWakeLocksCleared = 0; 844 final int numWakeLocks = mWakeLocks.size(); 845 for (int i = 0; i < numWakeLocks; i++) { 846 final WakeLock wakeLock = mWakeLocks.get(i); 847 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 848 case PowerManager.FULL_WAKE_LOCK: 849 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 850 case PowerManager.SCREEN_DIM_WAKE_LOCK: 851 numWakeLocksCleared += 1; 852 break; 853 } 854 } 855 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared); 856 return true; 857 } 858 859 /** 860 * Updates the global power state based on dirty bits recorded in mDirty. 861 * 862 * This is the main function that performs power state transitions. 863 * We centralize them here so that we can recompute the power state completely 864 * each time something important changes, and ensure that we do it the same 865 * way each time. The point is to gather all of the transition logic here. 866 */ 867 private void updatePowerStateLocked() { 868 if (!mSystemReady || mDirty == 0) { 869 return; 870 } 871 872 // Phase 0: Basic state updates. 873 updateIsPoweredLocked(mDirty); 874 updateStayOnLocked(mDirty); 875 876 // Phase 1: Update wakefulness. 877 // Loop because the wake lock and user activity computations are influenced 878 // by changes in wakefulness. 879 final long now = SystemClock.uptimeMillis(); 880 int dirtyPhase2 = 0; 881 for (;;) { 882 int dirtyPhase1 = mDirty; 883 dirtyPhase2 |= dirtyPhase1; 884 mDirty = 0; 885 886 updateWakeLockSummaryLocked(dirtyPhase1); 887 updateUserActivitySummaryLocked(now, dirtyPhase1); 888 if (!updateWakefulnessLocked(dirtyPhase1)) { 889 break; 890 } 891 } 892 893 // Phase 2: Update dreams and display power state. 894 updateDreamLocked(dirtyPhase2); 895 updateDisplayPowerStateLocked(dirtyPhase2); 896 897 // Phase 3: Send notifications, if needed. 898 sendPendingNotificationsLocked(); 899 900 // Phase 4: Update suspend blocker. 901 // Because we might release the last suspend blocker here, we need to make sure 902 // we finished everything else first! 903 updateSuspendBlockerLocked(); 904 } 905 906 private void sendPendingNotificationsLocked() { 907 if (mDisplayReady) { 908 if (mSendWakeUpFinishedNotificationWhenReady) { 909 mSendWakeUpFinishedNotificationWhenReady = false; 910 mNotifier.onWakeUpFinished(); 911 } 912 if (mSendGoToSleepFinishedNotificationWhenReady) { 913 mSendGoToSleepFinishedNotificationWhenReady = false; 914 mNotifier.onGoToSleepFinished(); 915 } 916 } 917 } 918 919 /** 920 * Updates the value of mIsPowered. 921 * Sets DIRTY_IS_POWERED if a change occurred. 922 */ 923 private void updateIsPoweredLocked(int dirty) { 924 if ((dirty & DIRTY_BATTERY_STATE) != 0) { 925 boolean wasPowered = mIsPowered; 926 mIsPowered = mBatteryService.isPowered(); 927 928 if (wasPowered != mIsPowered) { 929 mDirty |= DIRTY_IS_POWERED; 930 931 // Treat plugging and unplugging the devices as a user activity. 932 // Users find it disconcerting when they plug or unplug the device 933 // and it shuts off right away. 934 // Some devices also wake the device when plugged or unplugged because 935 // they don't have a charging LED. 936 final long now = SystemClock.uptimeMillis(); 937 if (mWakeUpWhenPluggedOrUnpluggedConfig) { 938 wakeUpNoUpdateLocked(now); 939 } 940 userActivityNoUpdateLocked( 941 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 942 } 943 } 944 } 945 946 /** 947 * Updates the value of mStayOn. 948 * Sets DIRTY_STAY_ON if a change occurred. 949 */ 950 private void updateStayOnLocked(int dirty) { 951 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) { 952 if (mStayOnWhilePluggedInSetting != 0 953 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 954 mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting); 955 } else { 956 mStayOn = false; 957 } 958 } 959 } 960 961 /** 962 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks. 963 * Note that most wake-locks are ignored when the system is asleep. 964 * 965 * This function must have no other side-effects. 966 */ 967 private void updateWakeLockSummaryLocked(int dirty) { 968 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) { 969 mWakeLockSummary = 0; 970 971 final int numWakeLocks = mWakeLocks.size(); 972 for (int i = 0; i < numWakeLocks; i++) { 973 final WakeLock wakeLock = mWakeLocks.get(i); 974 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 975 case PowerManager.PARTIAL_WAKE_LOCK: 976 mWakeLockSummary |= WAKE_LOCK_CPU; 977 break; 978 case PowerManager.FULL_WAKE_LOCK: 979 if (mWakefulness != WAKEFULNESS_ASLEEP) { 980 mWakeLockSummary |= WAKE_LOCK_CPU 981 | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT; 982 } 983 break; 984 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 985 if (mWakefulness != WAKEFULNESS_ASLEEP) { 986 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT; 987 } 988 break; 989 case PowerManager.SCREEN_DIM_WAKE_LOCK: 990 if (mWakefulness != WAKEFULNESS_ASLEEP) { 991 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM; 992 } 993 break; 994 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 995 if (mWakefulness != WAKEFULNESS_ASLEEP) { 996 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_PROXIMITY_SCREEN_OFF; 997 } 998 break; 999 } 1000 } 1001 1002 if (DEBUG_SPEW) { 1003 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness=" 1004 + wakefulnessToString(mWakefulness) 1005 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1006 } 1007 } 1008 } 1009 1010 /** 1011 * Updates the value of mUserActivitySummary to summarize the user requested 1012 * state of the system such as whether the screen should be bright or dim. 1013 * Note that user activity is ignored when the system is asleep. 1014 * 1015 * This function must have no other side-effects. 1016 */ 1017 private void updateUserActivitySummaryLocked(long now, int dirty) { 1018 // Update the status of the user activity timeout timer. 1019 if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) { 1020 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT); 1021 1022 long nextTimeout = 0; 1023 if (mWakefulness != WAKEFULNESS_ASLEEP) { 1024 final int screenOffTimeout = getScreenOffTimeoutLocked(); 1025 final int screenDimDuration = getScreenDimDurationLocked(); 1026 1027 mUserActivitySummary = 0; 1028 if (mLastUserActivityTime >= mLastWakeTime) { 1029 nextTimeout = mLastUserActivityTime 1030 + screenOffTimeout - screenDimDuration; 1031 if (now < nextTimeout) { 1032 mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT; 1033 } else { 1034 nextTimeout = mLastUserActivityTime + screenOffTimeout; 1035 if (now < nextTimeout) { 1036 mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM; 1037 } 1038 } 1039 } 1040 if (mUserActivitySummary == 0 1041 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) { 1042 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout; 1043 if (now < nextTimeout 1044 && mDisplayPowerRequest.screenState 1045 != DisplayPowerRequest.SCREEN_STATE_OFF) { 1046 mUserActivitySummary = mDisplayPowerRequest.screenState 1047 == DisplayPowerRequest.SCREEN_STATE_BRIGHT ? 1048 USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM; 1049 } 1050 } 1051 if (mUserActivitySummary != 0) { 1052 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT); 1053 msg.setAsynchronous(true); 1054 mHandler.sendMessageAtTime(msg, nextTimeout); 1055 } 1056 } else { 1057 mUserActivitySummary = 0; 1058 } 1059 1060 if (DEBUG_SPEW) { 1061 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness=" 1062 + wakefulnessToString(mWakefulness) 1063 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1064 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout)); 1065 } 1066 } 1067 } 1068 1069 /** 1070 * Called when a user activity timeout has occurred. 1071 * Simply indicates that something about user activity has changed so that the new 1072 * state can be recomputed when the power state is updated. 1073 * 1074 * This function must have no other side-effects besides setting the dirty 1075 * bit and calling update power state. Wakefulness transitions are handled elsewhere. 1076 */ 1077 private void handleUserActivityTimeout() { // runs on handler thread 1078 synchronized (mLock) { 1079 if (DEBUG_SPEW) { 1080 Slog.d(TAG, "handleUserActivityTimeout"); 1081 } 1082 1083 mDirty |= DIRTY_USER_ACTIVITY; 1084 updatePowerStateLocked(); 1085 } 1086 } 1087 1088 private int getScreenOffTimeoutLocked() { 1089 int timeout = mScreenOffTimeoutSetting; 1090 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1091 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin); 1092 } 1093 return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT); 1094 } 1095 1096 private int getScreenDimDurationLocked() { 1097 return SCREEN_DIM_DURATION; 1098 } 1099 1100 /** 1101 * Updates the wakefulness of the device. 1102 * 1103 * This is the function that decides whether the device should start napping 1104 * based on the current wake locks and user activity state. It may modify mDirty 1105 * if the wakefulness changes. 1106 * 1107 * Returns true if the wakefulness changed and we need to restart power state calculation. 1108 */ 1109 private boolean updateWakefulnessLocked(int dirty) { 1110 boolean changed = false; 1111 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED 1112 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON)) != 0) { 1113 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) { 1114 if (DEBUG_SPEW) { 1115 Slog.d(TAG, "updateWakefulnessLocked: Nap time..."); 1116 } 1117 mWakefulness = WAKEFULNESS_NAPPING; 1118 mDirty |= DIRTY_WAKEFULNESS; 1119 changed = true; 1120 } 1121 } 1122 return changed; 1123 } 1124 1125 // Also used when exiting a dream to determine whether we should go back 1126 // to being fully awake or else go to sleep for good. 1127 private boolean isItBedTimeYetLocked() { 1128 return mBootCompleted && !mStayOn 1129 && (mWakeLockSummary 1130 & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) == 0 1131 && (mUserActivitySummary 1132 & (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) == 0; 1133 } 1134 1135 /** 1136 * Determines whether to post a message to the sandman to update the dream state. 1137 */ 1138 private void updateDreamLocked(int dirty) { 1139 if ((dirty & (DIRTY_WAKEFULNESS | DIRTY_SETTINGS 1140 | DIRTY_IS_POWERED | DIRTY_STAY_ON)) != 0) { 1141 scheduleSandmanLocked(); 1142 } 1143 } 1144 1145 private void scheduleSandmanLocked() { 1146 if (!mSandmanScheduled) { 1147 mSandmanScheduled = true; 1148 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1149 msg.setAsynchronous(true); 1150 mHandler.sendMessage(msg); 1151 } 1152 } 1153 1154 /** 1155 * Called when the device enters or exits a napping or dreaming state. 1156 * 1157 * We do this asynchronously because we must call out of the power manager to start 1158 * the dream and we don't want to hold our lock while doing so. There is a risk that 1159 * the device will wake or go to sleep in the meantime so we have to handle that case. 1160 */ 1161 private void handleSandman() { // runs on handler thread 1162 // Handle preconditions. 1163 boolean startDreaming = false; 1164 synchronized (mLock) { 1165 mSandmanScheduled = false; 1166 1167 if (DEBUG_SPEW) { 1168 Log.d(TAG, "handleSandman: canDream=" + canDreamLocked() 1169 + ", mWakefulness=" + wakefulnessToString(mWakefulness)); 1170 } 1171 1172 if (canDreamLocked() && mWakefulness == WAKEFULNESS_NAPPING) { 1173 startDreaming = true; 1174 } 1175 } 1176 1177 // Get the dream manager, if needed. 1178 if (startDreaming && mDreamManager == null) { 1179 mDreamManager = IDreamManager.Stub.asInterface( 1180 ServiceManager.checkService("dreams")); 1181 if (mDreamManager == null) { 1182 Slog.w(TAG, "Unable to find IDreamManager."); 1183 } 1184 } 1185 1186 // Start dreaming if needed. 1187 // We only control the dream on the handler thread, so we don't need to worry about 1188 // concurrent attempts to start or stop the dream. 1189 boolean isDreaming = false; 1190 if (mDreamManager != null) { 1191 try { 1192 isDreaming = mDreamManager.isDreaming(); 1193 if (startDreaming && !isDreaming) { 1194 Slog.i(TAG, "Entering dreamland."); 1195 mDreamManager.dream(); 1196 isDreaming = mDreamManager.isDreaming(); 1197 if (!isDreaming) { 1198 Slog.i(TAG, "Could not enter dreamland. Sleep will be dreamless."); 1199 } 1200 } 1201 } catch (RemoteException ex) { 1202 } 1203 } 1204 1205 // Update dream state. 1206 // We might need to stop the dream again if the preconditions changed. 1207 boolean continueDreaming = false; 1208 synchronized (mLock) { 1209 if (isDreaming && canDreamLocked()) { 1210 if (mWakefulness == WAKEFULNESS_NAPPING) { 1211 mWakefulness = WAKEFULNESS_DREAMING; 1212 mDirty |= DIRTY_WAKEFULNESS; 1213 updatePowerStateLocked(); 1214 continueDreaming = true; 1215 } else if (mWakefulness == WAKEFULNESS_DREAMING) { 1216 continueDreaming = true; 1217 } 1218 } 1219 if (!continueDreaming) { 1220 handleDreamFinishedLocked(); 1221 } 1222 1223 // Allow the sandman to detect when the dream has ended. 1224 // FIXME: The DreamManagerService should tell us explicitly. 1225 if (mWakefulness == WAKEFULNESS_DREAMING 1226 || mWakefulness == WAKEFULNESS_NAPPING) { 1227 if (!mSandmanScheduled) { 1228 mSandmanScheduled = true; 1229 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1230 msg.setAsynchronous(true); 1231 mHandler.sendMessageDelayed(msg, 1000); 1232 } 1233 } 1234 } 1235 1236 // Stop dreaming if needed. 1237 // It's possible that something else changed to make us need to start the dream again. 1238 // If so, then the power manager will have posted another message to the handler 1239 // to take care of it later. 1240 if (mDreamManager != null) { 1241 try { 1242 if (!continueDreaming && isDreaming) { 1243 Slog.i(TAG, "Leaving dreamland."); 1244 mDreamManager.awaken(); 1245 } 1246 } catch (RemoteException ex) { 1247 } 1248 } 1249 } 1250 1251 /** 1252 * Returns true if the device is allowed to dream in its current state, 1253 * assuming there has been no recent user activity and no wake locks are held. 1254 */ 1255 private boolean canDreamLocked() { 1256 return mIsPowered && mDreamsSupportedConfig 1257 && mDreamsEnabledSetting && mDreamsActivateOnSleepSetting; 1258 } 1259 1260 /** 1261 * Called when a dream is ending to figure out what to do next. 1262 */ 1263 private void handleDreamFinishedLocked() { 1264 if (mWakefulness == WAKEFULNESS_NAPPING 1265 || mWakefulness == WAKEFULNESS_DREAMING) { 1266 if (isItBedTimeYetLocked()) { 1267 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(), 1268 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1269 updatePowerStateLocked(); 1270 } else { 1271 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 1272 updatePowerStateLocked(); 1273 } 1274 } 1275 } 1276 1277 1278 /** 1279 * Updates the display power state asynchronously. 1280 * When the update is finished, mDisplayReady will be set to true. The display 1281 * controller posts a message to tell us when the actual display power state 1282 * has been updated so we come back here to double-check and finish up. 1283 * 1284 * This function recalculates the display power state each time. 1285 */ 1286 private void updateDisplayPowerStateLocked(int dirty) { 1287 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS 1288 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED 1289 | DIRTY_SETTINGS)) != 0) { 1290 int newScreenState = getDesiredScreenPowerState(); 1291 if (newScreenState != mDisplayPowerRequest.screenState) { 1292 if (newScreenState == DisplayPowerRequest.SCREEN_STATE_OFF 1293 && mDisplayPowerRequest.screenState 1294 != DisplayPowerRequest.SCREEN_STATE_OFF) { 1295 mLastScreenOffEventElapsedRealTime = SystemClock.elapsedRealtime(); 1296 } 1297 1298 mDisplayPowerRequest.screenState = newScreenState; 1299 nativeSetPowerState( 1300 newScreenState != DisplayPowerRequest.SCREEN_STATE_OFF, 1301 newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT); 1302 } 1303 1304 int screenBrightness = mScreenBrightnessSettingDefault; 1305 float screenAutoBrightnessAdjustment = 0.0f; 1306 boolean autoBrightness = (mScreenBrightnessModeSetting == 1307 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 1308 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) { 1309 screenBrightness = mScreenBrightnessOverrideFromWindowManager; 1310 autoBrightness = false; 1311 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) { 1312 screenBrightness = mTemporaryScreenBrightnessSettingOverride; 1313 } else if (isValidBrightness(mScreenBrightnessSetting)) { 1314 screenBrightness = mScreenBrightnessSetting; 1315 } 1316 if (autoBrightness) { 1317 screenBrightness = mScreenBrightnessSettingDefault; 1318 if (isValidAutoBrightnessAdjustment( 1319 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) { 1320 screenAutoBrightnessAdjustment = 1321 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride; 1322 } else if (isValidAutoBrightnessAdjustment( 1323 mScreenAutoBrightnessAdjustmentSetting)) { 1324 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting; 1325 } 1326 } 1327 screenBrightness = Math.max(Math.min(screenBrightness, 1328 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum); 1329 screenAutoBrightnessAdjustment = Math.max(Math.min( 1330 screenAutoBrightnessAdjustment, 1.0f), -1.0f); 1331 mDisplayPowerRequest.screenBrightness = screenBrightness; 1332 mDisplayPowerRequest.screenAutoBrightnessAdjustment = 1333 screenAutoBrightnessAdjustment; 1334 mDisplayPowerRequest.useAutoBrightness = autoBrightness; 1335 1336 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked(); 1337 1338 mDisplayReady = mDisplayPowerController.requestPowerState(mDisplayPowerRequest, 1339 mRequestWaitForNegativeProximity); 1340 mRequestWaitForNegativeProximity = false; 1341 1342 if (DEBUG_SPEW) { 1343 Slog.d(TAG, "updateScreenStateLocked: displayReady=" + mDisplayReady 1344 + ", newScreenState=" + newScreenState 1345 + ", mWakefulness=" + mWakefulness 1346 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary) 1347 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1348 + ", mBootCompleted=" + mBootCompleted); 1349 } 1350 } 1351 } 1352 1353 private static boolean isValidBrightness(int value) { 1354 return value >= 0 && value <= 255; 1355 } 1356 1357 private static boolean isValidAutoBrightnessAdjustment(float value) { 1358 return !Float.isNaN(value); 1359 } 1360 1361 private int getDesiredScreenPowerState() { 1362 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1363 return DisplayPowerRequest.SCREEN_STATE_OFF; 1364 } 1365 1366 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0 1367 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0 1368 || !mBootCompleted) { 1369 return DisplayPowerRequest.SCREEN_STATE_BRIGHT; 1370 } 1371 1372 return DisplayPowerRequest.SCREEN_STATE_DIM; 1373 } 1374 1375 private final DisplayPowerController.Callbacks mDisplayPowerControllerCallbacks = 1376 new DisplayPowerController.Callbacks() { 1377 @Override 1378 public void onStateChanged() { 1379 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED; 1380 updatePowerStateLocked(); 1381 } 1382 1383 @Override 1384 public void onProximityNegative() { 1385 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 1386 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1387 updatePowerStateLocked(); 1388 } 1389 }; 1390 1391 private boolean shouldUseProximitySensorLocked() { 1392 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0; 1393 } 1394 1395 /** 1396 * Updates the suspend blocker that keeps the CPU alive. 1397 * 1398 * This function must have no other side-effects. 1399 */ 1400 private void updateSuspendBlockerLocked() { 1401 boolean wantCpu = isCpuNeededLocked(); 1402 if (wantCpu != mHoldingWakeLockSuspendBlocker) { 1403 mHoldingWakeLockSuspendBlocker = wantCpu; 1404 if (wantCpu) { 1405 if (DEBUG) { 1406 Slog.d(TAG, "updateSuspendBlockerLocked: Acquiring suspend blocker."); 1407 } 1408 mWakeLockSuspendBlocker.acquire(); 1409 } else { 1410 if (DEBUG) { 1411 Slog.d(TAG, "updateSuspendBlockerLocked: Releasing suspend blocker."); 1412 } 1413 mWakeLockSuspendBlocker.release(); 1414 } 1415 } 1416 } 1417 1418 private boolean isCpuNeededLocked() { 1419 return !mBootCompleted 1420 || mWakeLockSummary != 0 1421 || mUserActivitySummary != 0 1422 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF 1423 || !mDisplayReady; 1424 } 1425 1426 @Override // Binder call 1427 public boolean isScreenOn() { 1428 final long ident = Binder.clearCallingIdentity(); 1429 try { 1430 return isScreenOnInternal(); 1431 } finally { 1432 Binder.restoreCallingIdentity(ident); 1433 } 1434 } 1435 1436 private boolean isScreenOnInternal() { 1437 synchronized (mLock) { 1438 return !mSystemReady 1439 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF; 1440 } 1441 } 1442 1443 private void handleBatteryStateChangedLocked() { 1444 mDirty |= DIRTY_BATTERY_STATE; 1445 updatePowerStateLocked(); 1446 } 1447 1448 private void handleBootCompletedLocked() { 1449 final long now = SystemClock.uptimeMillis(); 1450 mBootCompleted = true; 1451 mDirty |= DIRTY_BOOT_COMPLETED; 1452 userActivityNoUpdateLocked( 1453 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1454 updatePowerStateLocked(); 1455 } 1456 1457 private void handleDockStateChangedLocked(int dockState) { 1458 // TODO 1459 } 1460 1461 /** 1462 * Reboot the device immediately, passing 'reason' (may be null) 1463 * to the underlying __reboot system call. Should not return. 1464 */ 1465 @Override // Binder call 1466 public void reboot(String reason) { 1467 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1468 1469 final long ident = Binder.clearCallingIdentity(); 1470 try { 1471 rebootInternal(reason); 1472 } finally { 1473 Binder.restoreCallingIdentity(ident); 1474 } 1475 } 1476 1477 private void rebootInternal(final String reason) { 1478 if (mHandler == null || !mSystemReady) { 1479 throw new IllegalStateException("Too early to call reboot()"); 1480 } 1481 1482 Runnable runnable = new Runnable() { 1483 public void run() { 1484 synchronized (this) { 1485 ShutdownThread.reboot(mContext, reason, false); 1486 } 1487 } 1488 }; 1489 1490 // ShutdownThread must run on a looper capable of displaying the UI. 1491 Message msg = Message.obtain(mHandler, runnable); 1492 msg.setAsynchronous(true); 1493 mHandler.sendMessage(msg); 1494 1495 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 1496 synchronized (runnable) { 1497 while (true) { 1498 try { 1499 runnable.wait(); 1500 } catch (InterruptedException e) { 1501 } 1502 } 1503 } 1504 } 1505 1506 /** 1507 * Crash the runtime (causing a complete restart of the Android framework). 1508 * Requires REBOOT permission. Mostly for testing. Should not return. 1509 */ 1510 @Override // Binder call 1511 public void crash(String message) { 1512 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1513 1514 final long ident = Binder.clearCallingIdentity(); 1515 try { 1516 crashInternal(message); 1517 } finally { 1518 Binder.restoreCallingIdentity(ident); 1519 } 1520 } 1521 1522 private void crashInternal(final String message) { 1523 Thread t = new Thread("PowerManagerService.crash()") { 1524 public void run() { 1525 throw new RuntimeException(message); 1526 } 1527 }; 1528 try { 1529 t.start(); 1530 t.join(); 1531 } catch (InterruptedException e) { 1532 Log.wtf(TAG, e); 1533 } 1534 } 1535 1536 @Override // Binder call 1537 public void clearUserActivityTimeout(long now, long timeout) { 1538 // TODO Auto-generated method stub 1539 // Only used by phone app, delete this 1540 } 1541 1542 @Override // Binder call 1543 public void setPokeLock(int pokey, IBinder lock, String tag) { 1544 // TODO Auto-generated method stub 1545 // Only used by phone app, delete this 1546 } 1547 1548 /** 1549 * Set the setting that determines whether the device stays on when plugged in. 1550 * The argument is a bit string, with each bit specifying a power source that, 1551 * when the device is connected to that source, causes the device to stay on. 1552 * See {@link android.os.BatteryManager} for the list of power sources that 1553 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 1554 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 1555 * 1556 * Used by "adb shell svc power stayon ..." 1557 * 1558 * @param val an {@code int} containing the bits that specify which power sources 1559 * should cause the device to stay on. 1560 */ 1561 @Override // Binder call 1562 public void setStayOnSetting(int val) { 1563 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null); 1564 1565 final long ident = Binder.clearCallingIdentity(); 1566 try { 1567 setStayOnSettingInternal(val); 1568 } finally { 1569 Binder.restoreCallingIdentity(ident); 1570 } 1571 } 1572 1573 private void setStayOnSettingInternal(int val) { 1574 Settings.System.putInt(mContext.getContentResolver(), 1575 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val); 1576 } 1577 1578 /** 1579 * Used by device administration to set the maximum screen off timeout. 1580 * 1581 * This method must only be called by the device administration policy manager. 1582 */ 1583 @Override // Binder call 1584 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { 1585 final long ident = Binder.clearCallingIdentity(); 1586 try { 1587 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); 1588 } finally { 1589 Binder.restoreCallingIdentity(ident); 1590 } 1591 } 1592 1593 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) { 1594 synchronized (mLock) { 1595 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs; 1596 mDirty |= DIRTY_SETTINGS; 1597 updatePowerStateLocked(); 1598 } 1599 } 1600 1601 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() { 1602 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0 1603 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE; 1604 } 1605 1606 @Override // Binder call 1607 public void preventScreenOn(boolean prevent) { 1608 // TODO Auto-generated method stub 1609 // Only used by phone app, delete this 1610 } 1611 1612 /** 1613 * Used by the phone application to make the attention LED flash when ringing. 1614 */ 1615 @Override // Binder call 1616 public void setAttentionLight(boolean on, int color) { 1617 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1618 1619 final long ident = Binder.clearCallingIdentity(); 1620 try { 1621 setAttentionLightInternal(on, color); 1622 } finally { 1623 Binder.restoreCallingIdentity(ident); 1624 } 1625 } 1626 1627 private void setAttentionLightInternal(boolean on, int color) { 1628 LightsService.Light light; 1629 synchronized (mLock) { 1630 if (!mSystemReady) { 1631 return; 1632 } 1633 light = mAttentionLight; 1634 } 1635 1636 // Control light outside of lock. 1637 light.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 1638 } 1639 1640 /** 1641 * Used by the Watchdog. 1642 */ 1643 public long timeSinceScreenWasLastOn() { 1644 synchronized (mLock) { 1645 if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) { 1646 return 0; 1647 } 1648 return SystemClock.elapsedRealtime() - mLastScreenOffEventElapsedRealTime; 1649 } 1650 } 1651 1652 /** 1653 * Used by the window manager to override the screen brightness based on the 1654 * current foreground activity. 1655 * 1656 * This method must only be called by the window manager. 1657 * 1658 * @param brightness The overridden brightness, or -1 to disable the override. 1659 */ 1660 public void setScreenBrightnessOverrideFromWindowManager(int brightness) { 1661 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1662 1663 final long ident = Binder.clearCallingIdentity(); 1664 try { 1665 setScreenBrightnessOverrideFromWindowManagerInternal(brightness); 1666 } finally { 1667 Binder.restoreCallingIdentity(ident); 1668 } 1669 } 1670 1671 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) { 1672 synchronized (mLock) { 1673 if (mScreenBrightnessOverrideFromWindowManager != brightness) { 1674 mScreenBrightnessOverrideFromWindowManager = brightness; 1675 mDirty |= DIRTY_SETTINGS; 1676 updatePowerStateLocked(); 1677 } 1678 } 1679 } 1680 1681 /** 1682 * Used by the window manager to override the button brightness based on the 1683 * current foreground activity. 1684 * 1685 * This method must only be called by the window manager. 1686 * 1687 * @param brightness The overridden brightness, or -1 to disable the override. 1688 */ 1689 public void setButtonBrightnessOverrideFromWindowManager(int brightness) { 1690 // Do nothing. 1691 // Button lights are not currently supported in the new implementation. 1692 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1693 } 1694 1695 /** 1696 * Used by the settings application and brightness control widgets to 1697 * temporarily override the current screen brightness setting so that the 1698 * user can observe the effect of an intended settings change without applying 1699 * it immediately. 1700 * 1701 * The override will be canceled when the setting value is next updated. 1702 * 1703 * @param brightness The overridden brightness. 1704 * 1705 * @see Settings.System#SCREEN_BRIGHTNESS 1706 */ 1707 @Override // Binder call 1708 public void setTemporaryScreenBrightnessSettingOverride(int brightness) { 1709 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1710 1711 final long ident = Binder.clearCallingIdentity(); 1712 try { 1713 setTemporaryScreenBrightnessSettingOverrideInternal(brightness); 1714 } finally { 1715 Binder.restoreCallingIdentity(ident); 1716 } 1717 } 1718 1719 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) { 1720 synchronized (mLock) { 1721 if (mTemporaryScreenBrightnessSettingOverride != brightness) { 1722 mTemporaryScreenBrightnessSettingOverride = brightness; 1723 mDirty |= DIRTY_SETTINGS; 1724 updatePowerStateLocked(); 1725 } 1726 } 1727 } 1728 1729 /** 1730 * Used by the settings application and brightness control widgets to 1731 * temporarily override the current screen auto-brightness adjustment setting so that the 1732 * user can observe the effect of an intended settings change without applying 1733 * it immediately. 1734 * 1735 * The override will be canceled when the setting value is next updated. 1736 * 1737 * @param adj The overridden brightness, or Float.NaN to disable the override. 1738 * 1739 * @see Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ 1740 */ 1741 @Override // Binder call 1742 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) { 1743 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1744 1745 final long ident = Binder.clearCallingIdentity(); 1746 try { 1747 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj); 1748 } finally { 1749 Binder.restoreCallingIdentity(ident); 1750 } 1751 } 1752 1753 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) { 1754 synchronized (mLock) { 1755 // Note: This condition handles NaN because NaN is not equal to any other 1756 // value, including itself. 1757 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) { 1758 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj; 1759 mDirty |= DIRTY_SETTINGS; 1760 updatePowerStateLocked(); 1761 } 1762 } 1763 } 1764 1765 /** 1766 * Low-level function turn the device off immediately, without trying 1767 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown. 1768 */ 1769 public static void lowLevelShutdown() { 1770 nativeShutdown(); 1771 } 1772 1773 /** 1774 * Low-level function to reboot the device. 1775 * 1776 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 1777 * @throws IOException if reboot fails for some reason (eg, lack of 1778 * permission) 1779 */ 1780 public static void lowLevelReboot(String reason) throws IOException { 1781 nativeReboot(reason); 1782 } 1783 1784 @Override // Watchdog.Monitor implementation 1785 public void monitor() { 1786 // Grab and release lock for watchdog monitor to detect deadlocks. 1787 synchronized (mLock) { 1788 } 1789 } 1790 1791 @Override // Binder call 1792 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1793 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP) 1794 != PackageManager.PERMISSION_GRANTED) { 1795 pw.println("Permission Denial: can't dump PowerManager from from pid=" 1796 + Binder.getCallingPid() 1797 + ", uid=" + Binder.getCallingUid()); 1798 return; 1799 } 1800 1801 pw.println("POWER MANAGER (dumpsys power)\n"); 1802 1803 final DisplayPowerController dpc; 1804 synchronized (mLock) { 1805 pw.println("Power Manager State:"); 1806 pw.println(" mDirty=0x" + Integer.toHexString(mDirty)); 1807 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness)); 1808 pw.println(" mIsPowered=" + mIsPowered); 1809 pw.println(" mStayOn=" + mStayOn); 1810 pw.println(" mBootCompleted=" + mBootCompleted); 1811 pw.println(" mSystemReady=" + mSystemReady); 1812 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1813 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)); 1814 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity); 1815 pw.println(" mSandmanScheduled=" + mSandmanScheduled); 1816 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime)); 1817 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime)); 1818 pw.println(" mSendWakeUpFinishedNotificationWhenReady=" 1819 + mSendWakeUpFinishedNotificationWhenReady); 1820 pw.println(" mSendGoToSleepFinishedNotificationWhenReady=" 1821 + mSendGoToSleepFinishedNotificationWhenReady); 1822 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime)); 1823 pw.println(" mLastUserActivityTimeNoChangeLights=" 1824 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights)); 1825 pw.println(" mDisplayReady=" + mDisplayReady); 1826 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker); 1827 1828 pw.println(); 1829 pw.println("Settings and Configuration:"); 1830 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig); 1831 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting); 1832 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting); 1833 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting); 1834 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin=" 1835 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced=" 1836 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")"); 1837 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting); 1838 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting); 1839 pw.println(" mScreenAutoBrightnessAdjustmentSetting=" 1840 + mScreenAutoBrightnessAdjustmentSetting); 1841 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting); 1842 pw.println(" mScreenBrightnessOverrideFromWindowManager=" 1843 + mScreenBrightnessOverrideFromWindowManager); 1844 pw.println(" mTemporaryScreenBrightnessSettingOverride=" 1845 + mTemporaryScreenBrightnessSettingOverride); 1846 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=" 1847 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride); 1848 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum); 1849 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum); 1850 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault); 1851 1852 pw.println(); 1853 pw.println("Wake Locks: size=" + mWakeLocks.size()); 1854 for (WakeLock wl : mWakeLocks) { 1855 pw.println(" " + wl); 1856 } 1857 1858 pw.println(); 1859 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size()); 1860 for (SuspendBlocker sb : mSuspendBlockers) { 1861 pw.println(" " + sb); 1862 } 1863 1864 dpc = mDisplayPowerController; 1865 } 1866 1867 if (dpc != null) { 1868 dpc.dump(pw); 1869 } 1870 } 1871 1872 private SuspendBlocker createSuspendBlockerLocked(String name) { 1873 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name); 1874 mSuspendBlockers.add(suspendBlocker); 1875 return suspendBlocker; 1876 } 1877 1878 private static String wakefulnessToString(int wakefulness) { 1879 switch (wakefulness) { 1880 case WAKEFULNESS_ASLEEP: 1881 return "Asleep"; 1882 case WAKEFULNESS_AWAKE: 1883 return "Awake"; 1884 case WAKEFULNESS_DREAMING: 1885 return "Dreaming"; 1886 case WAKEFULNESS_NAPPING: 1887 return "Napping"; 1888 default: 1889 return Integer.toString(wakefulness); 1890 } 1891 } 1892 1893 private static WorkSource copyWorkSource(WorkSource workSource) { 1894 return workSource != null ? new WorkSource(workSource) : null; 1895 } 1896 1897 private final class BatteryReceiver extends BroadcastReceiver { 1898 @Override 1899 public void onReceive(Context context, Intent intent) { 1900 synchronized (mLock) { 1901 handleBatteryStateChangedLocked(); 1902 } 1903 } 1904 } 1905 1906 private final class BootCompletedReceiver extends BroadcastReceiver { 1907 @Override 1908 public void onReceive(Context context, Intent intent) { 1909 synchronized (mLock) { 1910 handleBootCompletedLocked(); 1911 } 1912 } 1913 } 1914 1915 private final class DockReceiver extends BroadcastReceiver { 1916 @Override 1917 public void onReceive(Context context, Intent intent) { 1918 synchronized (mLock) { 1919 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 1920 Intent.EXTRA_DOCK_STATE_UNDOCKED); 1921 handleDockStateChangedLocked(dockState); 1922 } 1923 } 1924 } 1925 1926 private final class SettingsObserver extends ContentObserver { 1927 public SettingsObserver(Handler handler) { 1928 super(handler); 1929 } 1930 1931 @Override 1932 public void onChange(boolean selfChange, Uri uri) { 1933 synchronized (mLock) { 1934 handleSettingsChangedLocked(); 1935 } 1936 } 1937 } 1938 1939 private final WindowManagerPolicy.ScreenOnListener mScreenOnListener = 1940 new WindowManagerPolicy.ScreenOnListener() { 1941 @Override 1942 public void onScreenOn() { 1943 } 1944 }; 1945 1946 /** 1947 * Handler for asynchronous operations performed by the power manager. 1948 */ 1949 private final class PowerManagerHandler extends Handler { 1950 public PowerManagerHandler(Looper looper) { 1951 super(looper); 1952 } 1953 1954 @Override 1955 public void handleMessage(Message msg) { 1956 switch (msg.what) { 1957 case MSG_USER_ACTIVITY_TIMEOUT: 1958 handleUserActivityTimeout(); 1959 break; 1960 case MSG_SANDMAN: 1961 handleSandman(); 1962 break; 1963 } 1964 } 1965 } 1966 1967 /** 1968 * Represents a wake lock that has been acquired by an application. 1969 */ 1970 private final class WakeLock implements IBinder.DeathRecipient { 1971 public final IBinder mLock; 1972 public int mFlags; 1973 public String mTag; 1974 public WorkSource mWorkSource; 1975 public int mOwnerUid; 1976 public int mOwnerPid; 1977 1978 public WakeLock(IBinder lock, int flags, String tag, WorkSource workSource, 1979 int ownerUid, int ownerPid) { 1980 mLock = lock; 1981 mFlags = flags; 1982 mTag = tag; 1983 mWorkSource = copyWorkSource(workSource); 1984 mOwnerUid = ownerUid; 1985 mOwnerPid = ownerPid; 1986 } 1987 1988 @Override 1989 public void binderDied() { 1990 PowerManagerService.this.handleWakeLockDeath(this); 1991 } 1992 1993 public boolean hasSameProperties(int flags, String tag, WorkSource workSource, 1994 int ownerUid, int ownerPid) { 1995 return mFlags == flags 1996 && mTag.equals(tag) 1997 && hasSameWorkSource(workSource) 1998 && mOwnerUid == ownerUid 1999 && mOwnerPid == ownerPid; 2000 } 2001 2002 public void updateProperties(int flags, String tag, WorkSource workSource, 2003 int ownerUid, int ownerPid) { 2004 mFlags = flags; 2005 mTag = tag; 2006 updateWorkSource(workSource); 2007 mOwnerUid = ownerUid; 2008 mOwnerPid = ownerPid; 2009 } 2010 2011 public boolean hasSameWorkSource(WorkSource workSource) { 2012 return Objects.equal(mWorkSource, workSource); 2013 } 2014 2015 public void updateWorkSource(WorkSource workSource) { 2016 mWorkSource = copyWorkSource(workSource); 2017 } 2018 2019 @Override 2020 public String toString() { 2021 return getLockLevelString() 2022 + " '" + mTag + "'" + getLockFlagsString() 2023 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")"; 2024 } 2025 2026 private String getLockLevelString() { 2027 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 2028 case PowerManager.FULL_WAKE_LOCK: 2029 return "FULL_WAKE_LOCK "; 2030 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 2031 return "SCREEN_BRIGHT_WAKE_LOCK "; 2032 case PowerManager.SCREEN_DIM_WAKE_LOCK: 2033 return "SCREEN_DIM_WAKE_LOCK "; 2034 case PowerManager.PARTIAL_WAKE_LOCK: 2035 return "PARTIAL_WAKE_LOCK "; 2036 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 2037 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 2038 default: 2039 return "??? "; 2040 } 2041 } 2042 2043 private String getLockFlagsString() { 2044 String result = ""; 2045 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 2046 result += " ACQUIRE_CAUSES_WAKEUP"; 2047 } 2048 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 2049 result += " ON_AFTER_RELEASE"; 2050 } 2051 return result; 2052 } 2053 } 2054 2055 private final class SuspendBlockerImpl implements SuspendBlocker { 2056 private final String mName; 2057 private int mReferenceCount; 2058 2059 public SuspendBlockerImpl(String name) { 2060 mName = name; 2061 } 2062 2063 @Override 2064 protected void finalize() throws Throwable { 2065 try { 2066 if (mReferenceCount != 0) { 2067 Log.wtf(TAG, "Suspend blocker \"" + mName 2068 + "\" was finalized without being released!"); 2069 mReferenceCount = 0; 2070 nativeReleaseSuspendBlocker(mName); 2071 } 2072 } finally { 2073 super.finalize(); 2074 } 2075 } 2076 2077 @Override 2078 public void acquire() { 2079 synchronized (this) { 2080 mReferenceCount += 1; 2081 if (mReferenceCount == 1) { 2082 nativeAcquireSuspendBlocker(mName); 2083 } 2084 } 2085 } 2086 2087 @Override 2088 public void release() { 2089 synchronized (this) { 2090 mReferenceCount -= 1; 2091 if (mReferenceCount == 0) { 2092 nativeReleaseSuspendBlocker(mName); 2093 } else if (mReferenceCount < 0) { 2094 Log.wtf(TAG, "Suspend blocker \"" + mName 2095 + "\" was released without being acquired!", new Throwable()); 2096 mReferenceCount = 0; 2097 } 2098 } 2099 } 2100 2101 @Override 2102 public String toString() { 2103 synchronized (this) { 2104 return mName + ": ref count=" + mReferenceCount; 2105 } 2106 } 2107 } 2108} 2109