Home | History | Annotate | Download | only in power
      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 com.android.internal.app.IAppOpsService;
     20 import com.android.internal.app.IBatteryStats;
     21 import com.android.server.BatteryService;
     22 import com.android.server.EventLogTags;
     23 import com.android.server.LightsService;
     24 import com.android.server.TwilightService;
     25 import com.android.server.Watchdog;
     26 import com.android.server.am.ActivityManagerService;
     27 import com.android.server.display.DisplayManagerService;
     28 import com.android.server.dreams.DreamManagerService;
     29 
     30 import android.Manifest;
     31 import android.content.BroadcastReceiver;
     32 import android.content.ContentResolver;
     33 import android.content.Context;
     34 import android.content.Intent;
     35 import android.content.IntentFilter;
     36 import android.content.pm.PackageManager;
     37 import android.content.res.Resources;
     38 import android.database.ContentObserver;
     39 import android.hardware.SensorManager;
     40 import android.hardware.SystemSensorManager;
     41 import android.net.Uri;
     42 import android.os.BatteryManager;
     43 import android.os.Binder;
     44 import android.os.Handler;
     45 import android.os.HandlerThread;
     46 import android.os.IBinder;
     47 import android.os.IPowerManager;
     48 import android.os.Looper;
     49 import android.os.Message;
     50 import android.os.PowerManager;
     51 import android.os.Process;
     52 import android.os.RemoteException;
     53 import android.os.SystemClock;
     54 import android.os.SystemProperties;
     55 import android.os.SystemService;
     56 import android.os.UserHandle;
     57 import android.os.WorkSource;
     58 import android.provider.Settings;
     59 import android.util.EventLog;
     60 import android.util.Log;
     61 import android.util.Slog;
     62 import android.util.TimeUtils;
     63 import android.view.WindowManagerPolicy;
     64 
     65 import java.io.FileDescriptor;
     66 import java.io.PrintWriter;
     67 import java.util.ArrayList;
     68 
     69 import libcore.util.Objects;
     70 
     71 /**
     72  * The power manager service is responsible for coordinating power management
     73  * functions on the device.
     74  */
     75 public final class PowerManagerService extends IPowerManager.Stub
     76         implements Watchdog.Monitor {
     77     private static final String TAG = "PowerManagerService";
     78 
     79     private static final boolean DEBUG = false;
     80     private static final boolean DEBUG_SPEW = DEBUG && true;
     81 
     82     // Message: Sent when a user activity timeout occurs to update the power state.
     83     private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
     84     // Message: Sent when the device enters or exits a napping or dreaming state.
     85     private static final int MSG_SANDMAN = 2;
     86     // Message: Sent when the screen on blocker is released.
     87     private static final int MSG_SCREEN_ON_BLOCKER_RELEASED = 3;
     88     // Message: Sent to poll whether the boot animation has terminated.
     89     private static final int MSG_CHECK_IF_BOOT_ANIMATION_FINISHED = 4;
     90 
     91     // Dirty bit: mWakeLocks changed
     92     private static final int DIRTY_WAKE_LOCKS = 1 << 0;
     93     // Dirty bit: mWakefulness changed
     94     private static final int DIRTY_WAKEFULNESS = 1 << 1;
     95     // Dirty bit: user activity was poked or may have timed out
     96     private static final int DIRTY_USER_ACTIVITY = 1 << 2;
     97     // Dirty bit: actual display power state was updated asynchronously
     98     private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
     99     // Dirty bit: mBootCompleted changed
    100     private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
    101     // Dirty bit: settings changed
    102     private static final int DIRTY_SETTINGS = 1 << 5;
    103     // Dirty bit: mIsPowered changed
    104     private static final int DIRTY_IS_POWERED = 1 << 6;
    105     // Dirty bit: mStayOn changed
    106     private static final int DIRTY_STAY_ON = 1 << 7;
    107     // Dirty bit: battery state changed
    108     private static final int DIRTY_BATTERY_STATE = 1 << 8;
    109     // Dirty bit: proximity state changed
    110     private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
    111     // Dirty bit: screen on blocker state became held or unheld
    112     private static final int DIRTY_SCREEN_ON_BLOCKER_RELEASED = 1 << 10;
    113     // Dirty bit: dock state changed
    114     private static final int DIRTY_DOCK_STATE = 1 << 11;
    115 
    116     // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp().
    117     // The screen should be off or in the process of being turned off by the display controller.
    118     private static final int WAKEFULNESS_ASLEEP = 0;
    119     // Wakefulness: The device is fully awake.  It can be put to sleep by a call to goToSleep().
    120     // When the user activity timeout expires, the device may start napping or go to sleep.
    121     private static final int WAKEFULNESS_AWAKE = 1;
    122     // Wakefulness: The device is napping.  It is deciding whether to dream or go to sleep
    123     // but hasn't gotten around to it yet.  It can be awoken by a call to wakeUp(), which
    124     // ends the nap. User activity may brighten the screen but does not end the nap.
    125     private static final int WAKEFULNESS_NAPPING = 2;
    126     // Wakefulness: The device is dreaming.  It can be awoken by a call to wakeUp(),
    127     // which ends the dream.  The device goes to sleep when goToSleep() is called, when
    128     // the dream ends or when unplugged.
    129     // User activity may brighten the screen but does not end the dream.
    130     private static final int WAKEFULNESS_DREAMING = 3;
    131 
    132     // Summarizes the state of all active wakelocks.
    133     private static final int WAKE_LOCK_CPU = 1 << 0;
    134     private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
    135     private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
    136     private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
    137     private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
    138     private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
    139 
    140     // Summarizes the user activity state.
    141     private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
    142     private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
    143 
    144     // Default and minimum screen off timeout in milliseconds.
    145     private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
    146     private static final int MINIMUM_SCREEN_OFF_TIMEOUT = 10 * 1000;
    147 
    148     // The screen dim duration, in milliseconds.
    149     // This is subtracted from the end of the screen off timeout so the
    150     // minimum screen off timeout should be longer than this.
    151     private static final int SCREEN_DIM_DURATION = 7 * 1000;
    152 
    153     // The maximum screen dim time expressed as a ratio relative to the screen
    154     // off timeout.  If the screen off timeout is very short then we want the
    155     // dim timeout to also be quite short so that most of the time is spent on.
    156     // Otherwise the user won't get much screen on time before dimming occurs.
    157     private static final float MAXIMUM_SCREEN_DIM_RATIO = 0.2f;
    158 
    159     // The name of the boot animation service in init.rc.
    160     private static final String BOOT_ANIMATION_SERVICE = "bootanim";
    161 
    162     // Poll interval in milliseconds for watching boot animation finished.
    163     private static final int BOOT_ANIMATION_POLL_INTERVAL = 200;
    164 
    165     // If the battery level drops by this percentage and the user activity timeout
    166     // has expired, then assume the device is receiving insufficient current to charge
    167     // effectively and terminate the dream.
    168     private static final int DREAM_BATTERY_LEVEL_DRAIN_CUTOFF = 5;
    169 
    170     private Context mContext;
    171     private LightsService mLightsService;
    172     private BatteryService mBatteryService;
    173     private DisplayManagerService mDisplayManagerService;
    174     private IBatteryStats mBatteryStats;
    175     private IAppOpsService mAppOps;
    176     private HandlerThread mHandlerThread;
    177     private PowerManagerHandler mHandler;
    178     private WindowManagerPolicy mPolicy;
    179     private Notifier mNotifier;
    180     private DisplayPowerController mDisplayPowerController;
    181     private WirelessChargerDetector mWirelessChargerDetector;
    182     private SettingsObserver mSettingsObserver;
    183     private DreamManagerService mDreamManager;
    184     private LightsService.Light mAttentionLight;
    185 
    186     private final Object mLock = new Object();
    187 
    188     // A bitfield that indicates what parts of the power state have
    189     // changed and need to be recalculated.
    190     private int mDirty;
    191 
    192     // Indicates whether the device is awake or asleep or somewhere in between.
    193     // This is distinct from the screen power state, which is managed separately.
    194     private int mWakefulness;
    195 
    196     // True if MSG_SANDMAN has been scheduled.
    197     private boolean mSandmanScheduled;
    198 
    199     // Table of all suspend blockers.
    200     // There should only be a few of these.
    201     private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
    202 
    203     // Table of all wake locks acquired by applications.
    204     private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
    205 
    206     // A bitfield that summarizes the state of all active wakelocks.
    207     private int mWakeLockSummary;
    208 
    209     // If true, instructs the display controller to wait for the proximity sensor to
    210     // go negative before turning the screen on.
    211     private boolean mRequestWaitForNegativeProximity;
    212 
    213     // Timestamp of the last time the device was awoken or put to sleep.
    214     private long mLastWakeTime;
    215     private long mLastSleepTime;
    216 
    217     // True if we need to send a wake up or go to sleep finished notification
    218     // when the display is ready.
    219     private boolean mSendWakeUpFinishedNotificationWhenReady;
    220     private boolean mSendGoToSleepFinishedNotificationWhenReady;
    221 
    222     // Timestamp of the last call to user activity.
    223     private long mLastUserActivityTime;
    224     private long mLastUserActivityTimeNoChangeLights;
    225 
    226     // A bitfield that summarizes the effect of the user activity timer.
    227     // A zero value indicates that the user activity timer has expired.
    228     private int mUserActivitySummary;
    229 
    230     // The desired display power state.  The actual state may lag behind the
    231     // requested because it is updated asynchronously by the display power controller.
    232     private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
    233 
    234     // The time the screen was last turned off, in elapsedRealtime() timebase.
    235     private long mLastScreenOffEventElapsedRealTime;
    236 
    237     // True if the display power state has been fully applied, which means the display
    238     // is actually on or actually off or whatever was requested.
    239     private boolean mDisplayReady;
    240 
    241     // The suspend blocker used to keep the CPU alive when an application has acquired
    242     // a wake lock.
    243     private final SuspendBlocker mWakeLockSuspendBlocker;
    244 
    245     // True if the wake lock suspend blocker has been acquired.
    246     private boolean mHoldingWakeLockSuspendBlocker;
    247 
    248     // The suspend blocker used to keep the CPU alive when the display is on, the
    249     // display is getting ready or there is user activity (in which case the display
    250     // must be on).
    251     private final SuspendBlocker mDisplaySuspendBlocker;
    252 
    253     // True if the display suspend blocker has been acquired.
    254     private boolean mHoldingDisplaySuspendBlocker;
    255 
    256     // The screen on blocker used to keep the screen from turning on while the lock
    257     // screen is coming up.
    258     private final ScreenOnBlockerImpl mScreenOnBlocker;
    259 
    260     // The display blanker used to turn the screen on or off.
    261     private final DisplayBlankerImpl mDisplayBlanker;
    262 
    263     // True if systemReady() has been called.
    264     private boolean mSystemReady;
    265 
    266     // True if boot completed occurred.  We keep the screen on until this happens.
    267     private boolean mBootCompleted;
    268 
    269     // True if the device is plugged into a power source.
    270     private boolean mIsPowered;
    271 
    272     // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
    273     private int mPlugType;
    274 
    275     // The current battery level percentage.
    276     private int mBatteryLevel;
    277 
    278     // The battery level percentage at the time the dream started.
    279     // This is used to terminate a dream and go to sleep if the battery is
    280     // draining faster than it is charging and the user activity timeout has expired.
    281     private int mBatteryLevelWhenDreamStarted;
    282 
    283     // The current dock state.
    284     private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
    285 
    286     // True if the device should wake up when plugged or unplugged.
    287     private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
    288 
    289     // True if the device should suspend when the screen is off due to proximity.
    290     private boolean mSuspendWhenScreenOffDueToProximityConfig;
    291 
    292     // True if dreams are supported on this device.
    293     private boolean mDreamsSupportedConfig;
    294 
    295     // Default value for dreams enabled
    296     private boolean mDreamsEnabledByDefaultConfig;
    297 
    298     // Default value for dreams activate-on-sleep
    299     private boolean mDreamsActivatedOnSleepByDefaultConfig;
    300 
    301     // Default value for dreams activate-on-dock
    302     private boolean mDreamsActivatedOnDockByDefaultConfig;
    303 
    304     // True if dreams are enabled by the user.
    305     private boolean mDreamsEnabledSetting;
    306 
    307     // True if dreams should be activated on sleep.
    308     private boolean mDreamsActivateOnSleepSetting;
    309 
    310     // True if dreams should be activated on dock.
    311     private boolean mDreamsActivateOnDockSetting;
    312 
    313     // The screen off timeout setting value in milliseconds.
    314     private int mScreenOffTimeoutSetting;
    315 
    316     // The maximum allowable screen off timeout according to the device
    317     // administration policy.  Overrides other settings.
    318     private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE;
    319 
    320     // The stay on while plugged in setting.
    321     // A bitfield of battery conditions under which to make the screen stay on.
    322     private int mStayOnWhilePluggedInSetting;
    323 
    324     // True if the device should stay on.
    325     private boolean mStayOn;
    326 
    327     // True if the proximity sensor reads a positive result.
    328     private boolean mProximityPositive;
    329 
    330     // Screen brightness setting limits.
    331     private int mScreenBrightnessSettingMinimum;
    332     private int mScreenBrightnessSettingMaximum;
    333     private int mScreenBrightnessSettingDefault;
    334 
    335     // The screen brightness setting, from 0 to 255.
    336     // Use -1 if no value has been set.
    337     private int mScreenBrightnessSetting;
    338 
    339     // The screen auto-brightness adjustment setting, from -1 to 1.
    340     // Use 0 if there is no adjustment.
    341     private float mScreenAutoBrightnessAdjustmentSetting;
    342 
    343     // The screen brightness mode.
    344     // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
    345     private int mScreenBrightnessModeSetting;
    346 
    347     // The screen brightness setting override from the window manager
    348     // to allow the current foreground activity to override the brightness.
    349     // Use -1 to disable.
    350     private int mScreenBrightnessOverrideFromWindowManager = -1;
    351 
    352     // The user activity timeout override from the window manager
    353     // to allow the current foreground activity to override the user activity timeout.
    354     // Use -1 to disable.
    355     private long mUserActivityTimeoutOverrideFromWindowManager = -1;
    356 
    357     // The screen brightness setting override from the settings application
    358     // to temporarily adjust the brightness until next updated,
    359     // Use -1 to disable.
    360     private int mTemporaryScreenBrightnessSettingOverride = -1;
    361 
    362     // The screen brightness adjustment setting override from the settings
    363     // application to temporarily adjust the auto-brightness adjustment factor
    364     // until next updated, in the range -1..1.
    365     // Use NaN to disable.
    366     private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
    367 
    368     // Time when we last logged a warning about calling userActivity() without permission.
    369     private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
    370 
    371     private native void nativeInit();
    372 
    373     private static native void nativeSetPowerState(boolean screenOn, boolean screenBright);
    374     private static native void nativeAcquireSuspendBlocker(String name);
    375     private static native void nativeReleaseSuspendBlocker(String name);
    376     private static native void nativeSetInteractive(boolean enable);
    377     private static native void nativeSetAutoSuspend(boolean enable);
    378 
    379     public PowerManagerService() {
    380         synchronized (mLock) {
    381             mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
    382             mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
    383             mDisplaySuspendBlocker.acquire();
    384             mHoldingDisplaySuspendBlocker = true;
    385 
    386             mScreenOnBlocker = new ScreenOnBlockerImpl();
    387             mDisplayBlanker = new DisplayBlankerImpl();
    388             mWakefulness = WAKEFULNESS_AWAKE;
    389         }
    390 
    391         nativeInit();
    392         nativeSetPowerState(true, true);
    393     }
    394 
    395     /**
    396      * Initialize the power manager.
    397      * Must be called before any other functions within the power manager are called.
    398      */
    399     public void init(Context context, LightsService ls,
    400             ActivityManagerService am, BatteryService bs, IBatteryStats bss,
    401             IAppOpsService appOps, DisplayManagerService dm) {
    402         mContext = context;
    403         mLightsService = ls;
    404         mBatteryService = bs;
    405         mBatteryStats = bss;
    406         mAppOps = appOps;
    407         mDisplayManagerService = dm;
    408         mHandlerThread = new HandlerThread(TAG);
    409         mHandlerThread.start();
    410         mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
    411 
    412         Watchdog.getInstance().addMonitor(this);
    413         Watchdog.getInstance().addThread(mHandler, mHandlerThread.getName());
    414 
    415         // Forcibly turn the screen on at boot so that it is in a known power state.
    416         // We do this in init() rather than in the constructor because setting the
    417         // screen state requires a call into surface flinger which then needs to call back
    418         // into the activity manager to check permissions.  Unfortunately the
    419         // activity manager is not running when the constructor is called, so we
    420         // have to defer setting the screen state until this point.
    421         mDisplayBlanker.unblankAllDisplays();
    422     }
    423 
    424     public void setPolicy(WindowManagerPolicy policy) {
    425         synchronized (mLock) {
    426             mPolicy = policy;
    427         }
    428     }
    429 
    430     public void systemReady(TwilightService twilight, DreamManagerService dreamManager) {
    431         synchronized (mLock) {
    432             mSystemReady = true;
    433             mDreamManager = dreamManager;
    434 
    435             PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
    436             mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
    437             mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
    438             mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
    439 
    440             SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
    441 
    442             // The notifier runs on the system server's main looper so as not to interfere
    443             // with the animations and other critical functions of the power manager.
    444             mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
    445                     mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
    446                     mScreenOnBlocker, mPolicy);
    447 
    448             // The display power controller runs on the power manager service's
    449             // own handler thread to ensure timely operation.
    450             mDisplayPowerController = new DisplayPowerController(mHandler.getLooper(),
    451                     mContext, mNotifier, mLightsService, twilight, sensorManager,
    452                     mDisplayManagerService, mDisplaySuspendBlocker, mDisplayBlanker,
    453                     mDisplayPowerControllerCallbacks, mHandler);
    454 
    455             mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
    456                     createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
    457                     mHandler);
    458             mSettingsObserver = new SettingsObserver(mHandler);
    459             mAttentionLight = mLightsService.getLight(LightsService.LIGHT_ID_ATTENTION);
    460 
    461             // Register for broadcasts from other components of the system.
    462             IntentFilter filter = new IntentFilter();
    463             filter.addAction(Intent.ACTION_BATTERY_CHANGED);
    464             mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
    465 
    466             filter = new IntentFilter();
    467             filter.addAction(Intent.ACTION_BOOT_COMPLETED);
    468             mContext.registerReceiver(new BootCompletedReceiver(), filter, null, mHandler);
    469 
    470             filter = new IntentFilter();
    471             filter.addAction(Intent.ACTION_DREAMING_STARTED);
    472             filter.addAction(Intent.ACTION_DREAMING_STOPPED);
    473             mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
    474 
    475             filter = new IntentFilter();
    476             filter.addAction(Intent.ACTION_USER_SWITCHED);
    477             mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
    478 
    479             filter = new IntentFilter();
    480             filter.addAction(Intent.ACTION_DOCK_EVENT);
    481             mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
    482 
    483             // Register for settings changes.
    484             final ContentResolver resolver = mContext.getContentResolver();
    485             resolver.registerContentObserver(Settings.Secure.getUriFor(
    486                     Settings.Secure.SCREENSAVER_ENABLED),
    487                     false, mSettingsObserver, UserHandle.USER_ALL);
    488             resolver.registerContentObserver(Settings.Secure.getUriFor(
    489                     Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
    490                     false, mSettingsObserver, UserHandle.USER_ALL);
    491             resolver.registerContentObserver(Settings.Secure.getUriFor(
    492                     Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
    493                     false, mSettingsObserver, UserHandle.USER_ALL);
    494             resolver.registerContentObserver(Settings.System.getUriFor(
    495                     Settings.System.SCREEN_OFF_TIMEOUT),
    496                     false, mSettingsObserver, UserHandle.USER_ALL);
    497             resolver.registerContentObserver(Settings.Global.getUriFor(
    498                     Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
    499                     false, mSettingsObserver, UserHandle.USER_ALL);
    500             resolver.registerContentObserver(Settings.System.getUriFor(
    501                     Settings.System.SCREEN_BRIGHTNESS),
    502                     false, mSettingsObserver, UserHandle.USER_ALL);
    503             resolver.registerContentObserver(Settings.System.getUriFor(
    504                     Settings.System.SCREEN_BRIGHTNESS_MODE),
    505                     false, mSettingsObserver, UserHandle.USER_ALL);
    506 
    507             // Go.
    508             readConfigurationLocked();
    509             updateSettingsLocked();
    510             mDirty |= DIRTY_BATTERY_STATE;
    511             updatePowerStateLocked();
    512         }
    513     }
    514 
    515     private void readConfigurationLocked() {
    516         final Resources resources = mContext.getResources();
    517 
    518         mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
    519                 com.android.internal.R.bool.config_unplugTurnsOnScreen);
    520         mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
    521                 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
    522         mDreamsSupportedConfig = resources.getBoolean(
    523                 com.android.internal.R.bool.config_dreamsSupported);
    524         mDreamsEnabledByDefaultConfig = resources.getBoolean(
    525                 com.android.internal.R.bool.config_dreamsEnabledByDefault);
    526         mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
    527                 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
    528         mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
    529                 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
    530     }
    531 
    532     private void updateSettingsLocked() {
    533         final ContentResolver resolver = mContext.getContentResolver();
    534 
    535         mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
    536                 Settings.Secure.SCREENSAVER_ENABLED,
    537                 mDreamsEnabledByDefaultConfig ? 1 : 0,
    538                 UserHandle.USER_CURRENT) != 0);
    539         mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
    540                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
    541                 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
    542                 UserHandle.USER_CURRENT) != 0);
    543         mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
    544                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
    545                 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
    546                 UserHandle.USER_CURRENT) != 0);
    547         mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
    548                 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
    549                 UserHandle.USER_CURRENT);
    550         mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
    551                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
    552 
    553         final int oldScreenBrightnessSetting = mScreenBrightnessSetting;
    554         mScreenBrightnessSetting = Settings.System.getIntForUser(resolver,
    555                 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault,
    556                 UserHandle.USER_CURRENT);
    557         if (oldScreenBrightnessSetting != mScreenBrightnessSetting) {
    558             mTemporaryScreenBrightnessSettingOverride = -1;
    559         }
    560 
    561         final float oldScreenAutoBrightnessAdjustmentSetting =
    562                 mScreenAutoBrightnessAdjustmentSetting;
    563         mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver,
    564                 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f,
    565                 UserHandle.USER_CURRENT);
    566         if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) {
    567             mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
    568         }
    569 
    570         mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
    571                 Settings.System.SCREEN_BRIGHTNESS_MODE,
    572                 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
    573 
    574         mDirty |= DIRTY_SETTINGS;
    575     }
    576 
    577     private void handleSettingsChangedLocked() {
    578         updateSettingsLocked();
    579         updatePowerStateLocked();
    580     }
    581 
    582     @Override // Binder call
    583     public void acquireWakeLockWithUid(IBinder lock, int flags, String tag, String packageName,
    584             int uid) {
    585         acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid));
    586     }
    587 
    588     @Override // Binder call
    589     public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
    590             WorkSource ws) {
    591         if (lock == null) {
    592             throw new IllegalArgumentException("lock must not be null");
    593         }
    594         if (packageName == null) {
    595             throw new IllegalArgumentException("packageName must not be null");
    596         }
    597         PowerManager.validateWakeLockParameters(flags, tag);
    598 
    599         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
    600         if (ws != null && ws.size() != 0) {
    601             mContext.enforceCallingOrSelfPermission(
    602                     android.Manifest.permission.UPDATE_DEVICE_STATS, null);
    603         } else {
    604             ws = null;
    605         }
    606 
    607         final int uid = Binder.getCallingUid();
    608         final int pid = Binder.getCallingPid();
    609         final long ident = Binder.clearCallingIdentity();
    610         try {
    611             acquireWakeLockInternal(lock, flags, tag, packageName, ws, uid, pid);
    612         } finally {
    613             Binder.restoreCallingIdentity(ident);
    614         }
    615     }
    616 
    617     private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
    618             WorkSource ws, int uid, int pid) {
    619         synchronized (mLock) {
    620             if (DEBUG_SPEW) {
    621                 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
    622                         + ", flags=0x" + Integer.toHexString(flags)
    623                         + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
    624             }
    625 
    626             WakeLock wakeLock;
    627             int index = findWakeLockIndexLocked(lock);
    628             if (index >= 0) {
    629                 wakeLock = mWakeLocks.get(index);
    630                 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
    631                     // Update existing wake lock.  This shouldn't happen but is harmless.
    632                     notifyWakeLockReleasedLocked(wakeLock);
    633                     wakeLock.updateProperties(flags, tag, packageName, ws, uid, pid);
    634                     notifyWakeLockAcquiredLocked(wakeLock);
    635                 }
    636             } else {
    637                 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, uid, pid);
    638                 try {
    639                     lock.linkToDeath(wakeLock, 0);
    640                 } catch (RemoteException ex) {
    641                     throw new IllegalArgumentException("Wake lock is already dead.");
    642                 }
    643                 notifyWakeLockAcquiredLocked(wakeLock);
    644                 mWakeLocks.add(wakeLock);
    645             }
    646 
    647             applyWakeLockFlagsOnAcquireLocked(wakeLock);
    648             mDirty |= DIRTY_WAKE_LOCKS;
    649             updatePowerStateLocked();
    650         }
    651     }
    652 
    653     @SuppressWarnings("deprecation")
    654     private static boolean isScreenLock(final WakeLock wakeLock) {
    655         switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
    656             case PowerManager.FULL_WAKE_LOCK:
    657             case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
    658             case PowerManager.SCREEN_DIM_WAKE_LOCK:
    659                 return true;
    660         }
    661         return false;
    662     }
    663 
    664     private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) {
    665         if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
    666                 && isScreenLock(wakeLock)) {
    667             wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
    668         }
    669     }
    670 
    671     @Override // Binder call
    672     public void releaseWakeLock(IBinder lock, int flags) {
    673         if (lock == null) {
    674             throw new IllegalArgumentException("lock must not be null");
    675         }
    676 
    677         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
    678 
    679         final long ident = Binder.clearCallingIdentity();
    680         try {
    681             releaseWakeLockInternal(lock, flags);
    682         } finally {
    683             Binder.restoreCallingIdentity(ident);
    684         }
    685     }
    686 
    687     private void releaseWakeLockInternal(IBinder lock, int flags) {
    688         synchronized (mLock) {
    689             int index = findWakeLockIndexLocked(lock);
    690             if (index < 0) {
    691                 if (DEBUG_SPEW) {
    692                     Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
    693                             + " [not found], flags=0x" + Integer.toHexString(flags));
    694                 }
    695                 return;
    696             }
    697 
    698             WakeLock wakeLock = mWakeLocks.get(index);
    699             if (DEBUG_SPEW) {
    700                 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
    701                         + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
    702             }
    703 
    704             mWakeLocks.remove(index);
    705             notifyWakeLockReleasedLocked(wakeLock);
    706             wakeLock.mLock.unlinkToDeath(wakeLock, 0);
    707 
    708             if ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0) {
    709                 mRequestWaitForNegativeProximity = true;
    710             }
    711 
    712             applyWakeLockFlagsOnReleaseLocked(wakeLock);
    713             mDirty |= DIRTY_WAKE_LOCKS;
    714             updatePowerStateLocked();
    715         }
    716     }
    717 
    718     private void handleWakeLockDeath(WakeLock wakeLock) {
    719         synchronized (mLock) {
    720             if (DEBUG_SPEW) {
    721                 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
    722                         + " [" + wakeLock.mTag + "]");
    723             }
    724 
    725             int index = mWakeLocks.indexOf(wakeLock);
    726             if (index < 0) {
    727                 return;
    728             }
    729 
    730             mWakeLocks.remove(index);
    731             notifyWakeLockReleasedLocked(wakeLock);
    732 
    733             applyWakeLockFlagsOnReleaseLocked(wakeLock);
    734             mDirty |= DIRTY_WAKE_LOCKS;
    735             updatePowerStateLocked();
    736         }
    737     }
    738 
    739     private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
    740         if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
    741                 && isScreenLock(wakeLock)) {
    742             userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
    743                     PowerManager.USER_ACTIVITY_EVENT_OTHER,
    744                     PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
    745                     wakeLock.mOwnerUid);
    746         }
    747     }
    748 
    749     @Override // Binder call
    750     public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
    751         if (lock == null) {
    752             throw new IllegalArgumentException("lock must not be null");
    753         }
    754 
    755         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
    756         if (ws != null && ws.size() != 0) {
    757             mContext.enforceCallingOrSelfPermission(
    758                     android.Manifest.permission.UPDATE_DEVICE_STATS, null);
    759         } else {
    760             ws = null;
    761         }
    762 
    763         final long ident = Binder.clearCallingIdentity();
    764         try {
    765             updateWakeLockWorkSourceInternal(lock, ws);
    766         } finally {
    767             Binder.restoreCallingIdentity(ident);
    768         }
    769     }
    770 
    771     private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws) {
    772         synchronized (mLock) {
    773             int index = findWakeLockIndexLocked(lock);
    774             if (index < 0) {
    775                 if (DEBUG_SPEW) {
    776                     Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
    777                             + " [not found], ws=" + ws);
    778                 }
    779                 throw new IllegalArgumentException("Wake lock not active");
    780             }
    781 
    782             WakeLock wakeLock = mWakeLocks.get(index);
    783             if (DEBUG_SPEW) {
    784                 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
    785                         + " [" + wakeLock.mTag + "], ws=" + ws);
    786             }
    787 
    788             if (!wakeLock.hasSameWorkSource(ws)) {
    789                 notifyWakeLockReleasedLocked(wakeLock);
    790                 wakeLock.updateWorkSource(ws);
    791                 notifyWakeLockAcquiredLocked(wakeLock);
    792             }
    793         }
    794     }
    795 
    796     private int findWakeLockIndexLocked(IBinder lock) {
    797         final int count = mWakeLocks.size();
    798         for (int i = 0; i < count; i++) {
    799             if (mWakeLocks.get(i).mLock == lock) {
    800                 return i;
    801             }
    802         }
    803         return -1;
    804     }
    805 
    806     private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
    807         if (mSystemReady) {
    808             wakeLock.mNotifiedAcquired = true;
    809             mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
    810                     wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource);
    811         }
    812     }
    813 
    814     private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
    815         if (mSystemReady && wakeLock.mNotifiedAcquired) {
    816             wakeLock.mNotifiedAcquired = false;
    817             mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
    818                     wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource);
    819         }
    820     }
    821 
    822     @Override // Binder call
    823     public boolean isWakeLockLevelSupported(int level) {
    824         final long ident = Binder.clearCallingIdentity();
    825         try {
    826             return isWakeLockLevelSupportedInternal(level);
    827         } finally {
    828             Binder.restoreCallingIdentity(ident);
    829         }
    830     }
    831 
    832     @SuppressWarnings("deprecation")
    833     private boolean isWakeLockLevelSupportedInternal(int level) {
    834         synchronized (mLock) {
    835             switch (level) {
    836                 case PowerManager.PARTIAL_WAKE_LOCK:
    837                 case PowerManager.SCREEN_DIM_WAKE_LOCK:
    838                 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
    839                 case PowerManager.FULL_WAKE_LOCK:
    840                     return true;
    841 
    842                 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
    843                     return mSystemReady && mDisplayPowerController.isProximitySensorAvailable();
    844 
    845                 default:
    846                     return false;
    847             }
    848         }
    849     }
    850 
    851     @Override // Binder call
    852     public void userActivity(long eventTime, int event, int flags) {
    853         final long now = SystemClock.uptimeMillis();
    854         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
    855                 != PackageManager.PERMISSION_GRANTED) {
    856             // Once upon a time applications could call userActivity().
    857             // Now we require the DEVICE_POWER permission.  Log a warning and ignore the
    858             // request instead of throwing a SecurityException so we don't break old apps.
    859             synchronized (mLock) {
    860                 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
    861                     mLastWarningAboutUserActivityPermission = now;
    862                     Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
    863                             + "caller does not have DEVICE_POWER permission.  "
    864                             + "Please fix your app!  "
    865                             + " pid=" + Binder.getCallingPid()
    866                             + " uid=" + Binder.getCallingUid());
    867                 }
    868             }
    869             return;
    870         }
    871 
    872         if (eventTime > SystemClock.uptimeMillis()) {
    873             throw new IllegalArgumentException("event time must not be in the future");
    874         }
    875 
    876         final int uid = Binder.getCallingUid();
    877         final long ident = Binder.clearCallingIdentity();
    878         try {
    879             userActivityInternal(eventTime, event, flags, uid);
    880         } finally {
    881             Binder.restoreCallingIdentity(ident);
    882         }
    883     }
    884 
    885     // Called from native code.
    886     private void userActivityFromNative(long eventTime, int event, int flags) {
    887         userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
    888     }
    889 
    890     private void userActivityInternal(long eventTime, int event, int flags, int uid) {
    891         synchronized (mLock) {
    892             if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
    893                 updatePowerStateLocked();
    894             }
    895         }
    896     }
    897 
    898     private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
    899         if (DEBUG_SPEW) {
    900             Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
    901                     + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
    902                     + ", uid=" + uid);
    903         }
    904 
    905         if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
    906                 || mWakefulness == WAKEFULNESS_ASLEEP || !mBootCompleted || !mSystemReady) {
    907             return false;
    908         }
    909 
    910         mNotifier.onUserActivity(event, uid);
    911 
    912         if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
    913             if (eventTime > mLastUserActivityTimeNoChangeLights
    914                     && eventTime > mLastUserActivityTime) {
    915                 mLastUserActivityTimeNoChangeLights = eventTime;
    916                 mDirty |= DIRTY_USER_ACTIVITY;
    917                 return true;
    918             }
    919         } else {
    920             if (eventTime > mLastUserActivityTime) {
    921                 mLastUserActivityTime = eventTime;
    922                 mDirty |= DIRTY_USER_ACTIVITY;
    923                 return true;
    924             }
    925         }
    926         return false;
    927     }
    928 
    929     @Override // Binder call
    930     public void wakeUp(long eventTime) {
    931         if (eventTime > SystemClock.uptimeMillis()) {
    932             throw new IllegalArgumentException("event time must not be in the future");
    933         }
    934 
    935         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
    936 
    937         final long ident = Binder.clearCallingIdentity();
    938         try {
    939             wakeUpInternal(eventTime);
    940         } finally {
    941             Binder.restoreCallingIdentity(ident);
    942         }
    943     }
    944 
    945     // Called from native code.
    946     private void wakeUpFromNative(long eventTime) {
    947         wakeUpInternal(eventTime);
    948     }
    949 
    950     private void wakeUpInternal(long eventTime) {
    951         synchronized (mLock) {
    952             if (wakeUpNoUpdateLocked(eventTime)) {
    953                 updatePowerStateLocked();
    954             }
    955         }
    956     }
    957 
    958     private boolean wakeUpNoUpdateLocked(long eventTime) {
    959         if (DEBUG_SPEW) {
    960             Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime);
    961         }
    962 
    963         if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
    964                 || !mBootCompleted || !mSystemReady) {
    965             return false;
    966         }
    967 
    968         switch (mWakefulness) {
    969             case WAKEFULNESS_ASLEEP:
    970                 Slog.i(TAG, "Waking up from sleep...");
    971                 sendPendingNotificationsLocked();
    972                 mNotifier.onWakeUpStarted();
    973                 mSendWakeUpFinishedNotificationWhenReady = true;
    974                 break;
    975             case WAKEFULNESS_DREAMING:
    976                 Slog.i(TAG, "Waking up from dream...");
    977                 break;
    978             case WAKEFULNESS_NAPPING:
    979                 Slog.i(TAG, "Waking up from nap...");
    980                 break;
    981         }
    982 
    983         mLastWakeTime = eventTime;
    984         mWakefulness = WAKEFULNESS_AWAKE;
    985         mDirty |= DIRTY_WAKEFULNESS;
    986 
    987         userActivityNoUpdateLocked(
    988                 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
    989         return true;
    990     }
    991 
    992     @Override // Binder call
    993     public void goToSleep(long eventTime, int reason) {
    994         if (eventTime > SystemClock.uptimeMillis()) {
    995             throw new IllegalArgumentException("event time must not be in the future");
    996         }
    997 
    998         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
    999 
   1000         final long ident = Binder.clearCallingIdentity();
   1001         try {
   1002             goToSleepInternal(eventTime, reason);
   1003         } finally {
   1004             Binder.restoreCallingIdentity(ident);
   1005         }
   1006     }
   1007 
   1008     // Called from native code.
   1009     private void goToSleepFromNative(long eventTime, int reason) {
   1010         goToSleepInternal(eventTime, reason);
   1011     }
   1012 
   1013     private void goToSleepInternal(long eventTime, int reason) {
   1014         synchronized (mLock) {
   1015             if (goToSleepNoUpdateLocked(eventTime, reason)) {
   1016                 updatePowerStateLocked();
   1017             }
   1018         }
   1019     }
   1020 
   1021     @SuppressWarnings("deprecation")
   1022     private boolean goToSleepNoUpdateLocked(long eventTime, int reason) {
   1023         if (DEBUG_SPEW) {
   1024             Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime + ", reason=" + reason);
   1025         }
   1026 
   1027         if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
   1028                 || !mBootCompleted || !mSystemReady) {
   1029             return false;
   1030         }
   1031 
   1032         switch (reason) {
   1033             case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
   1034                 Slog.i(TAG, "Going to sleep due to device administration policy...");
   1035                 break;
   1036             case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
   1037                 Slog.i(TAG, "Going to sleep due to screen timeout...");
   1038                 break;
   1039             default:
   1040                 Slog.i(TAG, "Going to sleep by user request...");
   1041                 reason = PowerManager.GO_TO_SLEEP_REASON_USER;
   1042                 break;
   1043         }
   1044 
   1045         sendPendingNotificationsLocked();
   1046         mNotifier.onGoToSleepStarted(reason);
   1047         mSendGoToSleepFinishedNotificationWhenReady = true;
   1048 
   1049         mLastSleepTime = eventTime;
   1050         mDirty |= DIRTY_WAKEFULNESS;
   1051         mWakefulness = WAKEFULNESS_ASLEEP;
   1052 
   1053         // Report the number of wake locks that will be cleared by going to sleep.
   1054         int numWakeLocksCleared = 0;
   1055         final int numWakeLocks = mWakeLocks.size();
   1056         for (int i = 0; i < numWakeLocks; i++) {
   1057             final WakeLock wakeLock = mWakeLocks.get(i);
   1058             switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
   1059                 case PowerManager.FULL_WAKE_LOCK:
   1060                 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
   1061                 case PowerManager.SCREEN_DIM_WAKE_LOCK:
   1062                     numWakeLocksCleared += 1;
   1063                     break;
   1064             }
   1065         }
   1066         EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
   1067         return true;
   1068     }
   1069 
   1070     @Override // Binder call
   1071     public void nap(long eventTime) {
   1072         if (eventTime > SystemClock.uptimeMillis()) {
   1073             throw new IllegalArgumentException("event time must not be in the future");
   1074         }
   1075 
   1076         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   1077 
   1078         final long ident = Binder.clearCallingIdentity();
   1079         try {
   1080             napInternal(eventTime);
   1081         } finally {
   1082             Binder.restoreCallingIdentity(ident);
   1083         }
   1084     }
   1085 
   1086     private void napInternal(long eventTime) {
   1087         synchronized (mLock) {
   1088             if (napNoUpdateLocked(eventTime)) {
   1089                 updatePowerStateLocked();
   1090             }
   1091         }
   1092     }
   1093 
   1094     private boolean napNoUpdateLocked(long eventTime) {
   1095         if (DEBUG_SPEW) {
   1096             Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime);
   1097         }
   1098 
   1099         if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
   1100                 || !mBootCompleted || !mSystemReady) {
   1101             return false;
   1102         }
   1103 
   1104         Slog.i(TAG, "Nap time...");
   1105 
   1106         mDirty |= DIRTY_WAKEFULNESS;
   1107         mWakefulness = WAKEFULNESS_NAPPING;
   1108         return true;
   1109     }
   1110 
   1111     /**
   1112      * Updates the global power state based on dirty bits recorded in mDirty.
   1113      *
   1114      * This is the main function that performs power state transitions.
   1115      * We centralize them here so that we can recompute the power state completely
   1116      * each time something important changes, and ensure that we do it the same
   1117      * way each time.  The point is to gather all of the transition logic here.
   1118      */
   1119     private void updatePowerStateLocked() {
   1120         if (!mSystemReady || mDirty == 0) {
   1121             return;
   1122         }
   1123 
   1124         // Phase 0: Basic state updates.
   1125         updateIsPoweredLocked(mDirty);
   1126         updateStayOnLocked(mDirty);
   1127 
   1128         // Phase 1: Update wakefulness.
   1129         // Loop because the wake lock and user activity computations are influenced
   1130         // by changes in wakefulness.
   1131         final long now = SystemClock.uptimeMillis();
   1132         int dirtyPhase2 = 0;
   1133         for (;;) {
   1134             int dirtyPhase1 = mDirty;
   1135             dirtyPhase2 |= dirtyPhase1;
   1136             mDirty = 0;
   1137 
   1138             updateWakeLockSummaryLocked(dirtyPhase1);
   1139             updateUserActivitySummaryLocked(now, dirtyPhase1);
   1140             if (!updateWakefulnessLocked(dirtyPhase1)) {
   1141                 break;
   1142             }
   1143         }
   1144 
   1145         // Phase 2: Update dreams and display power state.
   1146         updateDreamLocked(dirtyPhase2);
   1147         updateDisplayPowerStateLocked(dirtyPhase2);
   1148 
   1149         // Phase 3: Send notifications, if needed.
   1150         if (mDisplayReady) {
   1151             sendPendingNotificationsLocked();
   1152         }
   1153 
   1154         // Phase 4: Update suspend blocker.
   1155         // Because we might release the last suspend blocker here, we need to make sure
   1156         // we finished everything else first!
   1157         updateSuspendBlockerLocked();
   1158     }
   1159 
   1160     private void sendPendingNotificationsLocked() {
   1161         if (mSendWakeUpFinishedNotificationWhenReady) {
   1162             mSendWakeUpFinishedNotificationWhenReady = false;
   1163             mNotifier.onWakeUpFinished();
   1164         }
   1165         if (mSendGoToSleepFinishedNotificationWhenReady) {
   1166             mSendGoToSleepFinishedNotificationWhenReady = false;
   1167             mNotifier.onGoToSleepFinished();
   1168         }
   1169     }
   1170 
   1171     /**
   1172      * Updates the value of mIsPowered.
   1173      * Sets DIRTY_IS_POWERED if a change occurred.
   1174      */
   1175     private void updateIsPoweredLocked(int dirty) {
   1176         if ((dirty & DIRTY_BATTERY_STATE) != 0) {
   1177             final boolean wasPowered = mIsPowered;
   1178             final int oldPlugType = mPlugType;
   1179             mIsPowered = mBatteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
   1180             mPlugType = mBatteryService.getPlugType();
   1181             mBatteryLevel = mBatteryService.getBatteryLevel();
   1182 
   1183             if (DEBUG) {
   1184                 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
   1185                         + ", mIsPowered=" + mIsPowered
   1186                         + ", oldPlugType=" + oldPlugType
   1187                         + ", mPlugType=" + mPlugType
   1188                         + ", mBatteryLevel=" + mBatteryLevel);
   1189             }
   1190 
   1191             if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
   1192                 mDirty |= DIRTY_IS_POWERED;
   1193 
   1194                 // Update wireless dock detection state.
   1195                 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
   1196                         mIsPowered, mPlugType, mBatteryLevel);
   1197 
   1198                 // Treat plugging and unplugging the devices as a user activity.
   1199                 // Users find it disconcerting when they plug or unplug the device
   1200                 // and it shuts off right away.
   1201                 // Some devices also wake the device when plugged or unplugged because
   1202                 // they don't have a charging LED.
   1203                 final long now = SystemClock.uptimeMillis();
   1204                 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
   1205                         dockedOnWirelessCharger)) {
   1206                     wakeUpNoUpdateLocked(now);
   1207                 }
   1208                 userActivityNoUpdateLocked(
   1209                         now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
   1210 
   1211                 // Tell the notifier whether wireless charging has started so that
   1212                 // it can provide feedback to the user.
   1213                 if (dockedOnWirelessCharger) {
   1214                     mNotifier.onWirelessChargingStarted();
   1215                 }
   1216             }
   1217         }
   1218     }
   1219 
   1220     private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
   1221             boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
   1222         // Don't wake when powered unless configured to do so.
   1223         if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
   1224             return false;
   1225         }
   1226 
   1227         // Don't wake when undocked from wireless charger.
   1228         // See WirelessChargerDetector for justification.
   1229         if (wasPowered && !mIsPowered
   1230                 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
   1231             return false;
   1232         }
   1233 
   1234         // Don't wake when docked on wireless charger unless we are certain of it.
   1235         // See WirelessChargerDetector for justification.
   1236         if (!wasPowered && mIsPowered
   1237                 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
   1238                 && !dockedOnWirelessCharger) {
   1239             return false;
   1240         }
   1241 
   1242         // If already dreaming and becoming powered, then don't wake.
   1243         if (mIsPowered && (mWakefulness == WAKEFULNESS_NAPPING
   1244                 || mWakefulness == WAKEFULNESS_DREAMING)) {
   1245             return false;
   1246         }
   1247 
   1248         // Otherwise wake up!
   1249         return true;
   1250     }
   1251 
   1252     /**
   1253      * Updates the value of mStayOn.
   1254      * Sets DIRTY_STAY_ON if a change occurred.
   1255      */
   1256     private void updateStayOnLocked(int dirty) {
   1257         if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
   1258             final boolean wasStayOn = mStayOn;
   1259             if (mStayOnWhilePluggedInSetting != 0
   1260                     && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
   1261                 mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting);
   1262             } else {
   1263                 mStayOn = false;
   1264             }
   1265 
   1266             if (mStayOn != wasStayOn) {
   1267                 mDirty |= DIRTY_STAY_ON;
   1268             }
   1269         }
   1270     }
   1271 
   1272     /**
   1273      * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
   1274      * Note that most wake-locks are ignored when the system is asleep.
   1275      *
   1276      * This function must have no other side-effects.
   1277      */
   1278     @SuppressWarnings("deprecation")
   1279     private void updateWakeLockSummaryLocked(int dirty) {
   1280         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
   1281             mWakeLockSummary = 0;
   1282 
   1283             final int numWakeLocks = mWakeLocks.size();
   1284             for (int i = 0; i < numWakeLocks; i++) {
   1285                 final WakeLock wakeLock = mWakeLocks.get(i);
   1286                 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
   1287                     case PowerManager.PARTIAL_WAKE_LOCK:
   1288                         mWakeLockSummary |= WAKE_LOCK_CPU;
   1289                         break;
   1290                     case PowerManager.FULL_WAKE_LOCK:
   1291                         if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1292                             mWakeLockSummary |= WAKE_LOCK_CPU
   1293                                     | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
   1294                             if (mWakefulness == WAKEFULNESS_AWAKE) {
   1295                                 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
   1296                             }
   1297                         }
   1298                         break;
   1299                     case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
   1300                         if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1301                             mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT;
   1302                             if (mWakefulness == WAKEFULNESS_AWAKE) {
   1303                                 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
   1304                             }
   1305                         }
   1306                         break;
   1307                     case PowerManager.SCREEN_DIM_WAKE_LOCK:
   1308                         if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1309                             mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM;
   1310                             if (mWakefulness == WAKEFULNESS_AWAKE) {
   1311                                 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
   1312                             }
   1313                         }
   1314                         break;
   1315                     case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
   1316                         if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1317                             mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
   1318                         }
   1319                         break;
   1320                 }
   1321             }
   1322 
   1323             if (DEBUG_SPEW) {
   1324                 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
   1325                         + wakefulnessToString(mWakefulness)
   1326                         + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
   1327             }
   1328         }
   1329     }
   1330 
   1331     /**
   1332      * Updates the value of mUserActivitySummary to summarize the user requested
   1333      * state of the system such as whether the screen should be bright or dim.
   1334      * Note that user activity is ignored when the system is asleep.
   1335      *
   1336      * This function must have no other side-effects.
   1337      */
   1338     private void updateUserActivitySummaryLocked(long now, int dirty) {
   1339         // Update the status of the user activity timeout timer.
   1340         if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
   1341             mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
   1342 
   1343             long nextTimeout = 0;
   1344             if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1345                 final int screenOffTimeout = getScreenOffTimeoutLocked();
   1346                 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
   1347 
   1348                 mUserActivitySummary = 0;
   1349                 if (mLastUserActivityTime >= mLastWakeTime) {
   1350                     nextTimeout = mLastUserActivityTime
   1351                             + screenOffTimeout - screenDimDuration;
   1352                     if (now < nextTimeout) {
   1353                         mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT;
   1354                     } else {
   1355                         nextTimeout = mLastUserActivityTime + screenOffTimeout;
   1356                         if (now < nextTimeout) {
   1357                             mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM;
   1358                         }
   1359                     }
   1360                 }
   1361                 if (mUserActivitySummary == 0
   1362                         && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
   1363                     nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
   1364                     if (now < nextTimeout
   1365                             && mDisplayPowerRequest.screenState
   1366                                     != DisplayPowerRequest.SCREEN_STATE_OFF) {
   1367                         mUserActivitySummary = mDisplayPowerRequest.screenState
   1368                                 == DisplayPowerRequest.SCREEN_STATE_BRIGHT ?
   1369                                 USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM;
   1370                     }
   1371                 }
   1372                 if (mUserActivitySummary != 0) {
   1373                     Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
   1374                     msg.setAsynchronous(true);
   1375                     mHandler.sendMessageAtTime(msg, nextTimeout);
   1376                 }
   1377             } else {
   1378                 mUserActivitySummary = 0;
   1379             }
   1380 
   1381             if (DEBUG_SPEW) {
   1382                 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
   1383                         + wakefulnessToString(mWakefulness)
   1384                         + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
   1385                         + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
   1386             }
   1387         }
   1388     }
   1389 
   1390     /**
   1391      * Called when a user activity timeout has occurred.
   1392      * Simply indicates that something about user activity has changed so that the new
   1393      * state can be recomputed when the power state is updated.
   1394      *
   1395      * This function must have no other side-effects besides setting the dirty
   1396      * bit and calling update power state.  Wakefulness transitions are handled elsewhere.
   1397      */
   1398     private void handleUserActivityTimeout() { // runs on handler thread
   1399         synchronized (mLock) {
   1400             if (DEBUG_SPEW) {
   1401                 Slog.d(TAG, "handleUserActivityTimeout");
   1402             }
   1403 
   1404             mDirty |= DIRTY_USER_ACTIVITY;
   1405             updatePowerStateLocked();
   1406         }
   1407     }
   1408 
   1409     private int getScreenOffTimeoutLocked() {
   1410         int timeout = mScreenOffTimeoutSetting;
   1411         if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
   1412             timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
   1413         }
   1414         if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
   1415             timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
   1416         }
   1417         return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT);
   1418     }
   1419 
   1420     private int getScreenDimDurationLocked(int screenOffTimeout) {
   1421         return Math.min(SCREEN_DIM_DURATION,
   1422                 (int)(screenOffTimeout * MAXIMUM_SCREEN_DIM_RATIO));
   1423     }
   1424 
   1425     /**
   1426      * Updates the wakefulness of the device.
   1427      *
   1428      * This is the function that decides whether the device should start napping
   1429      * based on the current wake locks and user activity state.  It may modify mDirty
   1430      * if the wakefulness changes.
   1431      *
   1432      * Returns true if the wakefulness changed and we need to restart power state calculation.
   1433      */
   1434     private boolean updateWakefulnessLocked(int dirty) {
   1435         boolean changed = false;
   1436         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
   1437                 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
   1438                 | DIRTY_DOCK_STATE)) != 0) {
   1439             if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
   1440                 if (DEBUG_SPEW) {
   1441                     Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
   1442                 }
   1443                 final long time = SystemClock.uptimeMillis();
   1444                 if (shouldNapAtBedTimeLocked()) {
   1445                     changed = napNoUpdateLocked(time);
   1446                 } else {
   1447                     changed = goToSleepNoUpdateLocked(time,
   1448                             PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
   1449                 }
   1450             }
   1451         }
   1452         return changed;
   1453     }
   1454 
   1455     /**
   1456      * Returns true if the device should automatically nap and start dreaming when the user
   1457      * activity timeout has expired and it's bedtime.
   1458      */
   1459     private boolean shouldNapAtBedTimeLocked() {
   1460         return mDreamsActivateOnSleepSetting
   1461                 || (mDreamsActivateOnDockSetting
   1462                         && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
   1463     }
   1464 
   1465     /**
   1466      * Returns true if the device should go to sleep now.
   1467      * Also used when exiting a dream to determine whether we should go back
   1468      * to being fully awake or else go to sleep for good.
   1469      */
   1470     private boolean isItBedTimeYetLocked() {
   1471         return mBootCompleted && !isBeingKeptAwakeLocked();
   1472     }
   1473 
   1474     /**
   1475      * Returns true if the device is being kept awake by a wake lock, user activity
   1476      * or the stay on while powered setting.  We also keep the phone awake when
   1477      * the proximity sensor returns a positive result so that the device does not
   1478      * lock while in a phone call.  This function only controls whether the device
   1479      * will go to sleep or dream which is independent of whether it will be allowed
   1480      * to suspend.
   1481      */
   1482     private boolean isBeingKeptAwakeLocked() {
   1483         return mStayOn
   1484                 || mProximityPositive
   1485                 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
   1486                 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
   1487                         | USER_ACTIVITY_SCREEN_DIM)) != 0;
   1488     }
   1489 
   1490     /**
   1491      * Determines whether to post a message to the sandman to update the dream state.
   1492      */
   1493     private void updateDreamLocked(int dirty) {
   1494         if ((dirty & (DIRTY_WAKEFULNESS
   1495                 | DIRTY_USER_ACTIVITY
   1496                 | DIRTY_WAKE_LOCKS
   1497                 | DIRTY_BOOT_COMPLETED
   1498                 | DIRTY_SETTINGS
   1499                 | DIRTY_IS_POWERED
   1500                 | DIRTY_STAY_ON
   1501                 | DIRTY_PROXIMITY_POSITIVE
   1502                 | DIRTY_BATTERY_STATE)) != 0) {
   1503             scheduleSandmanLocked();
   1504         }
   1505     }
   1506 
   1507     private void scheduleSandmanLocked() {
   1508         if (!mSandmanScheduled) {
   1509             mSandmanScheduled = true;
   1510             Message msg = mHandler.obtainMessage(MSG_SANDMAN);
   1511             msg.setAsynchronous(true);
   1512             mHandler.sendMessage(msg);
   1513         }
   1514     }
   1515 
   1516     /**
   1517      * Called when the device enters or exits a napping or dreaming state.
   1518      *
   1519      * We do this asynchronously because we must call out of the power manager to start
   1520      * the dream and we don't want to hold our lock while doing so.  There is a risk that
   1521      * the device will wake or go to sleep in the meantime so we have to handle that case.
   1522      */
   1523     private void handleSandman() { // runs on handler thread
   1524         // Handle preconditions.
   1525         boolean startDreaming = false;
   1526         synchronized (mLock) {
   1527             mSandmanScheduled = false;
   1528             boolean canDream = canDreamLocked();
   1529             if (DEBUG_SPEW) {
   1530                 Slog.d(TAG, "handleSandman: canDream=" + canDream
   1531                         + ", mWakefulness=" + wakefulnessToString(mWakefulness));
   1532             }
   1533 
   1534             if (canDream && mWakefulness == WAKEFULNESS_NAPPING) {
   1535                 startDreaming = true;
   1536             }
   1537         }
   1538 
   1539         // Start dreaming if needed.
   1540         // We only control the dream on the handler thread, so we don't need to worry about
   1541         // concurrent attempts to start or stop the dream.
   1542         boolean isDreaming = false;
   1543         if (mDreamManager != null) {
   1544             if (startDreaming) {
   1545                 mDreamManager.startDream();
   1546             }
   1547             isDreaming = mDreamManager.isDreaming();
   1548         }
   1549 
   1550         // Update dream state.
   1551         // We might need to stop the dream again if the preconditions changed.
   1552         boolean continueDreaming = false;
   1553         synchronized (mLock) {
   1554             if (isDreaming && canDreamLocked()) {
   1555                 if (mWakefulness == WAKEFULNESS_NAPPING) {
   1556                     mWakefulness = WAKEFULNESS_DREAMING;
   1557                     mDirty |= DIRTY_WAKEFULNESS;
   1558                     mBatteryLevelWhenDreamStarted = mBatteryLevel;
   1559                     updatePowerStateLocked();
   1560                     continueDreaming = true;
   1561                 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
   1562                     if (!isBeingKeptAwakeLocked()
   1563                             && mBatteryLevel < mBatteryLevelWhenDreamStarted
   1564                                     - DREAM_BATTERY_LEVEL_DRAIN_CUTOFF) {
   1565                         // If the user activity timeout expired and the battery appears
   1566                         // to be draining faster than it is charging then stop dreaming
   1567                         // and go to sleep.
   1568                         Slog.i(TAG, "Stopping dream because the battery appears to "
   1569                                 + "be draining faster than it is charging.  "
   1570                                 + "Battery level when dream started: "
   1571                                 + mBatteryLevelWhenDreamStarted + "%.  "
   1572                                 + "Battery level now: " + mBatteryLevel + "%.");
   1573                     } else {
   1574                         continueDreaming = true;
   1575                     }
   1576                 }
   1577             }
   1578             if (!continueDreaming) {
   1579                 handleDreamFinishedLocked();
   1580             }
   1581         }
   1582 
   1583         // Stop dreaming if needed.
   1584         // It's possible that something else changed to make us need to start the dream again.
   1585         // If so, then the power manager will have posted another message to the handler
   1586         // to take care of it later.
   1587         if (mDreamManager != null) {
   1588             if (!continueDreaming) {
   1589                 mDreamManager.stopDream();
   1590             }
   1591         }
   1592     }
   1593 
   1594     /**
   1595      * Returns true if the device is allowed to dream in its current state
   1596      * assuming that it is currently napping or dreaming.
   1597      */
   1598     private boolean canDreamLocked() {
   1599         return mDreamsSupportedConfig
   1600                 && mDreamsEnabledSetting
   1601                 && mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF
   1602                 && mBootCompleted
   1603                 && (mIsPowered || isBeingKeptAwakeLocked());
   1604     }
   1605 
   1606     /**
   1607      * Called when a dream is ending to figure out what to do next.
   1608      */
   1609     private void handleDreamFinishedLocked() {
   1610         if (mWakefulness == WAKEFULNESS_NAPPING
   1611                 || mWakefulness == WAKEFULNESS_DREAMING) {
   1612             if (isItBedTimeYetLocked()) {
   1613                 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
   1614                         PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
   1615                 updatePowerStateLocked();
   1616             } else {
   1617                 wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
   1618                 updatePowerStateLocked();
   1619             }
   1620         }
   1621     }
   1622 
   1623     private void handleScreenOnBlockerReleased() {
   1624         synchronized (mLock) {
   1625             mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED;
   1626             updatePowerStateLocked();
   1627         }
   1628     }
   1629 
   1630     /**
   1631      * Updates the display power state asynchronously.
   1632      * When the update is finished, mDisplayReady will be set to true.  The display
   1633      * controller posts a message to tell us when the actual display power state
   1634      * has been updated so we come back here to double-check and finish up.
   1635      *
   1636      * This function recalculates the display power state each time.
   1637      */
   1638     private void updateDisplayPowerStateLocked(int dirty) {
   1639         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
   1640                 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
   1641                 | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) {
   1642             int newScreenState = getDesiredScreenPowerStateLocked();
   1643             if (newScreenState != mDisplayPowerRequest.screenState) {
   1644                 if (newScreenState == DisplayPowerRequest.SCREEN_STATE_OFF
   1645                         && mDisplayPowerRequest.screenState
   1646                                 != DisplayPowerRequest.SCREEN_STATE_OFF) {
   1647                     mLastScreenOffEventElapsedRealTime = SystemClock.elapsedRealtime();
   1648                 }
   1649 
   1650                 mDisplayPowerRequest.screenState = newScreenState;
   1651                 nativeSetPowerState(
   1652                         newScreenState != DisplayPowerRequest.SCREEN_STATE_OFF,
   1653                         newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT);
   1654             }
   1655 
   1656             int screenBrightness = mScreenBrightnessSettingDefault;
   1657             float screenAutoBrightnessAdjustment = 0.0f;
   1658             boolean autoBrightness = (mScreenBrightnessModeSetting ==
   1659                     Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
   1660             if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
   1661                 screenBrightness = mScreenBrightnessOverrideFromWindowManager;
   1662                 autoBrightness = false;
   1663             } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
   1664                 screenBrightness = mTemporaryScreenBrightnessSettingOverride;
   1665             } else if (isValidBrightness(mScreenBrightnessSetting)) {
   1666                 screenBrightness = mScreenBrightnessSetting;
   1667             }
   1668             if (autoBrightness) {
   1669                 screenBrightness = mScreenBrightnessSettingDefault;
   1670                 if (isValidAutoBrightnessAdjustment(
   1671                         mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
   1672                     screenAutoBrightnessAdjustment =
   1673                             mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
   1674                 } else if (isValidAutoBrightnessAdjustment(
   1675                         mScreenAutoBrightnessAdjustmentSetting)) {
   1676                     screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
   1677                 }
   1678             }
   1679             screenBrightness = Math.max(Math.min(screenBrightness,
   1680                     mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
   1681             screenAutoBrightnessAdjustment = Math.max(Math.min(
   1682                     screenAutoBrightnessAdjustment, 1.0f), -1.0f);
   1683             mDisplayPowerRequest.screenBrightness = screenBrightness;
   1684             mDisplayPowerRequest.screenAutoBrightnessAdjustment =
   1685                     screenAutoBrightnessAdjustment;
   1686             mDisplayPowerRequest.useAutoBrightness = autoBrightness;
   1687 
   1688             mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
   1689 
   1690             mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld();
   1691 
   1692             mDisplayReady = mDisplayPowerController.requestPowerState(mDisplayPowerRequest,
   1693                     mRequestWaitForNegativeProximity);
   1694             mRequestWaitForNegativeProximity = false;
   1695 
   1696             if (DEBUG_SPEW) {
   1697                 Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady
   1698                         + ", newScreenState=" + newScreenState
   1699                         + ", mWakefulness=" + mWakefulness
   1700                         + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
   1701                         + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
   1702                         + ", mBootCompleted=" + mBootCompleted);
   1703             }
   1704         }
   1705     }
   1706 
   1707     private static boolean isValidBrightness(int value) {
   1708         return value >= 0 && value <= 255;
   1709     }
   1710 
   1711     private static boolean isValidAutoBrightnessAdjustment(float value) {
   1712         // Handles NaN by always returning false.
   1713         return value >= -1.0f && value <= 1.0f;
   1714     }
   1715 
   1716     private int getDesiredScreenPowerStateLocked() {
   1717         if (mWakefulness == WAKEFULNESS_ASLEEP) {
   1718             return DisplayPowerRequest.SCREEN_STATE_OFF;
   1719         }
   1720 
   1721         if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
   1722                 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
   1723                 || !mBootCompleted) {
   1724             return DisplayPowerRequest.SCREEN_STATE_BRIGHT;
   1725         }
   1726 
   1727         return DisplayPowerRequest.SCREEN_STATE_DIM;
   1728     }
   1729 
   1730     private final DisplayPowerController.Callbacks mDisplayPowerControllerCallbacks =
   1731             new DisplayPowerController.Callbacks() {
   1732         @Override
   1733         public void onStateChanged() {
   1734             synchronized (mLock) {
   1735                 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
   1736                 updatePowerStateLocked();
   1737             }
   1738         }
   1739 
   1740         @Override
   1741         public void onProximityPositive() {
   1742             synchronized (mLock) {
   1743                 mProximityPositive = true;
   1744                 mDirty |= DIRTY_PROXIMITY_POSITIVE;
   1745                 updatePowerStateLocked();
   1746             }
   1747         }
   1748 
   1749         @Override
   1750         public void onProximityNegative() {
   1751             synchronized (mLock) {
   1752                 mProximityPositive = false;
   1753                 mDirty |= DIRTY_PROXIMITY_POSITIVE;
   1754                 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
   1755                         PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
   1756                 updatePowerStateLocked();
   1757             }
   1758         }
   1759     };
   1760 
   1761     private boolean shouldUseProximitySensorLocked() {
   1762         return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
   1763     }
   1764 
   1765     /**
   1766      * Updates the suspend blocker that keeps the CPU alive.
   1767      *
   1768      * This function must have no other side-effects.
   1769      */
   1770     private void updateSuspendBlockerLocked() {
   1771         final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
   1772         final boolean needDisplaySuspendBlocker = needDisplaySuspendBlocker();
   1773 
   1774         // First acquire suspend blockers if needed.
   1775         if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
   1776             mWakeLockSuspendBlocker.acquire();
   1777             mHoldingWakeLockSuspendBlocker = true;
   1778         }
   1779         if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
   1780             mDisplaySuspendBlocker.acquire();
   1781             mHoldingDisplaySuspendBlocker = true;
   1782         }
   1783 
   1784         // Then release suspend blockers if needed.
   1785         if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
   1786             mWakeLockSuspendBlocker.release();
   1787             mHoldingWakeLockSuspendBlocker = false;
   1788         }
   1789         if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
   1790             mDisplaySuspendBlocker.release();
   1791             mHoldingDisplaySuspendBlocker = false;
   1792         }
   1793     }
   1794 
   1795     /**
   1796      * Return true if we must keep a suspend blocker active on behalf of the display.
   1797      * We do so if the screen is on or is in transition between states.
   1798      */
   1799     private boolean needDisplaySuspendBlocker() {
   1800         if (!mDisplayReady) {
   1801             return true;
   1802         }
   1803         if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) {
   1804             // If we asked for the screen to be on but it is off due to the proximity
   1805             // sensor then we may suspend but only if the configuration allows it.
   1806             // On some hardware it may not be safe to suspend because the proximity
   1807             // sensor may not be correctly configured as a wake-up source.
   1808             if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
   1809                     || !mSuspendWhenScreenOffDueToProximityConfig) {
   1810                 return true;
   1811             }
   1812         }
   1813         return false;
   1814     }
   1815 
   1816     @Override // Binder call
   1817     public boolean isScreenOn() {
   1818         final long ident = Binder.clearCallingIdentity();
   1819         try {
   1820             return isScreenOnInternal();
   1821         } finally {
   1822             Binder.restoreCallingIdentity(ident);
   1823         }
   1824     }
   1825 
   1826     private boolean isScreenOnInternal() {
   1827         synchronized (mLock) {
   1828             return !mSystemReady
   1829                     || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF;
   1830         }
   1831     }
   1832 
   1833     private void handleBatteryStateChangedLocked() {
   1834         mDirty |= DIRTY_BATTERY_STATE;
   1835         updatePowerStateLocked();
   1836     }
   1837 
   1838     private void startWatchingForBootAnimationFinished() {
   1839         mHandler.sendEmptyMessage(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED);
   1840     }
   1841 
   1842     private void checkIfBootAnimationFinished() {
   1843         if (DEBUG) {
   1844             Slog.d(TAG, "Check if boot animation finished...");
   1845         }
   1846 
   1847         if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) {
   1848             mHandler.sendEmptyMessageDelayed(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED,
   1849                     BOOT_ANIMATION_POLL_INTERVAL);
   1850             return;
   1851         }
   1852 
   1853         synchronized (mLock) {
   1854             if (!mBootCompleted) {
   1855                 Slog.i(TAG, "Boot animation finished.");
   1856                 handleBootCompletedLocked();
   1857             }
   1858         }
   1859     }
   1860 
   1861     private void handleBootCompletedLocked() {
   1862         final long now = SystemClock.uptimeMillis();
   1863         mBootCompleted = true;
   1864         mDirty |= DIRTY_BOOT_COMPLETED;
   1865         userActivityNoUpdateLocked(
   1866                 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
   1867         updatePowerStateLocked();
   1868     }
   1869 
   1870     /**
   1871      * Reboots the device.
   1872      *
   1873      * @param confirm If true, shows a reboot confirmation dialog.
   1874      * @param reason The reason for the reboot, or null if none.
   1875      * @param wait If true, this call waits for the reboot to complete and does not return.
   1876      */
   1877     @Override // Binder call
   1878     public void reboot(boolean confirm, String reason, boolean wait) {
   1879         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
   1880 
   1881         final long ident = Binder.clearCallingIdentity();
   1882         try {
   1883             shutdownOrRebootInternal(false, confirm, reason, wait);
   1884         } finally {
   1885             Binder.restoreCallingIdentity(ident);
   1886         }
   1887     }
   1888 
   1889     /**
   1890      * Shuts down the device.
   1891      *
   1892      * @param confirm If true, shows a shutdown confirmation dialog.
   1893      * @param wait If true, this call waits for the shutdown to complete and does not return.
   1894      */
   1895     @Override // Binder call
   1896     public void shutdown(boolean confirm, boolean wait) {
   1897         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
   1898 
   1899         final long ident = Binder.clearCallingIdentity();
   1900         try {
   1901             shutdownOrRebootInternal(true, confirm, null, wait);
   1902         } finally {
   1903             Binder.restoreCallingIdentity(ident);
   1904         }
   1905     }
   1906 
   1907     private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
   1908             final String reason, boolean wait) {
   1909         if (mHandler == null || !mSystemReady) {
   1910             throw new IllegalStateException("Too early to call shutdown() or reboot()");
   1911         }
   1912 
   1913         Runnable runnable = new Runnable() {
   1914             @Override
   1915             public void run() {
   1916                 synchronized (this) {
   1917                     if (shutdown) {
   1918                         ShutdownThread.shutdown(mContext, confirm);
   1919                     } else {
   1920                         ShutdownThread.reboot(mContext, reason, confirm);
   1921                     }
   1922                 }
   1923             }
   1924         };
   1925 
   1926         // ShutdownThread must run on a looper capable of displaying the UI.
   1927         Message msg = Message.obtain(mHandler, runnable);
   1928         msg.setAsynchronous(true);
   1929         mHandler.sendMessage(msg);
   1930 
   1931         // PowerManager.reboot() is documented not to return so just wait for the inevitable.
   1932         if (wait) {
   1933             synchronized (runnable) {
   1934                 while (true) {
   1935                     try {
   1936                         runnable.wait();
   1937                     } catch (InterruptedException e) {
   1938                     }
   1939                 }
   1940             }
   1941         }
   1942     }
   1943 
   1944     /**
   1945      * Crash the runtime (causing a complete restart of the Android framework).
   1946      * Requires REBOOT permission.  Mostly for testing.  Should not return.
   1947      */
   1948     @Override // Binder call
   1949     public void crash(String message) {
   1950         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
   1951 
   1952         final long ident = Binder.clearCallingIdentity();
   1953         try {
   1954             crashInternal(message);
   1955         } finally {
   1956             Binder.restoreCallingIdentity(ident);
   1957         }
   1958     }
   1959 
   1960     private void crashInternal(final String message) {
   1961         Thread t = new Thread("PowerManagerService.crash()") {
   1962             @Override
   1963             public void run() {
   1964                 throw new RuntimeException(message);
   1965             }
   1966         };
   1967         try {
   1968             t.start();
   1969             t.join();
   1970         } catch (InterruptedException e) {
   1971             Log.wtf(TAG, e);
   1972         }
   1973     }
   1974 
   1975     /**
   1976      * Set the setting that determines whether the device stays on when plugged in.
   1977      * The argument is a bit string, with each bit specifying a power source that,
   1978      * when the device is connected to that source, causes the device to stay on.
   1979      * See {@link android.os.BatteryManager} for the list of power sources that
   1980      * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
   1981      * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
   1982      *
   1983      * Used by "adb shell svc power stayon ..."
   1984      *
   1985      * @param val an {@code int} containing the bits that specify which power sources
   1986      * should cause the device to stay on.
   1987      */
   1988     @Override // Binder call
   1989     public void setStayOnSetting(int val) {
   1990         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
   1991 
   1992         final long ident = Binder.clearCallingIdentity();
   1993         try {
   1994             setStayOnSettingInternal(val);
   1995         } finally {
   1996             Binder.restoreCallingIdentity(ident);
   1997         }
   1998     }
   1999 
   2000     private void setStayOnSettingInternal(int val) {
   2001         Settings.Global.putInt(mContext.getContentResolver(),
   2002                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
   2003     }
   2004 
   2005     /**
   2006      * Used by device administration to set the maximum screen off timeout.
   2007      *
   2008      * This method must only be called by the device administration policy manager.
   2009      */
   2010     @Override // Binder call
   2011     public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
   2012         final long ident = Binder.clearCallingIdentity();
   2013         try {
   2014             setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
   2015         } finally {
   2016             Binder.restoreCallingIdentity(ident);
   2017         }
   2018     }
   2019 
   2020     private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
   2021         synchronized (mLock) {
   2022             mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
   2023             mDirty |= DIRTY_SETTINGS;
   2024             updatePowerStateLocked();
   2025         }
   2026     }
   2027 
   2028     private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
   2029         return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
   2030                 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
   2031     }
   2032 
   2033     /**
   2034      * Used by the phone application to make the attention LED flash when ringing.
   2035      */
   2036     @Override // Binder call
   2037     public void setAttentionLight(boolean on, int color) {
   2038         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2039 
   2040         final long ident = Binder.clearCallingIdentity();
   2041         try {
   2042             setAttentionLightInternal(on, color);
   2043         } finally {
   2044             Binder.restoreCallingIdentity(ident);
   2045         }
   2046     }
   2047 
   2048     private void setAttentionLightInternal(boolean on, int color) {
   2049         LightsService.Light light;
   2050         synchronized (mLock) {
   2051             if (!mSystemReady) {
   2052                 return;
   2053             }
   2054             light = mAttentionLight;
   2055         }
   2056 
   2057         // Control light outside of lock.
   2058         light.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
   2059     }
   2060 
   2061     /**
   2062      * Used by the Watchdog.
   2063      */
   2064     public long timeSinceScreenWasLastOn() {
   2065         synchronized (mLock) {
   2066             if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) {
   2067                 return 0;
   2068             }
   2069             return SystemClock.elapsedRealtime() - mLastScreenOffEventElapsedRealTime;
   2070         }
   2071     }
   2072 
   2073     /**
   2074      * Used by the window manager to override the screen brightness based on the
   2075      * current foreground activity.
   2076      *
   2077      * This method must only be called by the window manager.
   2078      *
   2079      * @param brightness The overridden brightness, or -1 to disable the override.
   2080      */
   2081     public void setScreenBrightnessOverrideFromWindowManager(int brightness) {
   2082         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2083 
   2084         final long ident = Binder.clearCallingIdentity();
   2085         try {
   2086             setScreenBrightnessOverrideFromWindowManagerInternal(brightness);
   2087         } finally {
   2088             Binder.restoreCallingIdentity(ident);
   2089         }
   2090     }
   2091 
   2092     private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
   2093         synchronized (mLock) {
   2094             if (mScreenBrightnessOverrideFromWindowManager != brightness) {
   2095                 mScreenBrightnessOverrideFromWindowManager = brightness;
   2096                 mDirty |= DIRTY_SETTINGS;
   2097                 updatePowerStateLocked();
   2098             }
   2099         }
   2100     }
   2101 
   2102     /**
   2103      * Used by the window manager to override the button brightness based on the
   2104      * current foreground activity.
   2105      *
   2106      * This method must only be called by the window manager.
   2107      *
   2108      * @param brightness The overridden brightness, or -1 to disable the override.
   2109      */
   2110     public void setButtonBrightnessOverrideFromWindowManager(int brightness) {
   2111         // Do nothing.
   2112         // Button lights are not currently supported in the new implementation.
   2113         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2114     }
   2115 
   2116     /**
   2117      * Used by the window manager to override the user activity timeout based on the
   2118      * current foreground activity.  It can only be used to make the timeout shorter
   2119      * than usual, not longer.
   2120      *
   2121      * This method must only be called by the window manager.
   2122      *
   2123      * @param timeoutMillis The overridden timeout, or -1 to disable the override.
   2124      */
   2125     public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
   2126         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2127 
   2128         final long ident = Binder.clearCallingIdentity();
   2129         try {
   2130             setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
   2131         } finally {
   2132             Binder.restoreCallingIdentity(ident);
   2133         }
   2134     }
   2135 
   2136     private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
   2137         synchronized (mLock) {
   2138             if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
   2139                 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
   2140                 mDirty |= DIRTY_SETTINGS;
   2141                 updatePowerStateLocked();
   2142             }
   2143         }
   2144     }
   2145 
   2146     /**
   2147      * Used by the settings application and brightness control widgets to
   2148      * temporarily override the current screen brightness setting so that the
   2149      * user can observe the effect of an intended settings change without applying
   2150      * it immediately.
   2151      *
   2152      * The override will be canceled when the setting value is next updated.
   2153      *
   2154      * @param brightness The overridden brightness.
   2155      *
   2156      * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
   2157      */
   2158     @Override // Binder call
   2159     public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
   2160         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2161 
   2162         final long ident = Binder.clearCallingIdentity();
   2163         try {
   2164             setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
   2165         } finally {
   2166             Binder.restoreCallingIdentity(ident);
   2167         }
   2168     }
   2169 
   2170     private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
   2171         synchronized (mLock) {
   2172             if (mTemporaryScreenBrightnessSettingOverride != brightness) {
   2173                 mTemporaryScreenBrightnessSettingOverride = brightness;
   2174                 mDirty |= DIRTY_SETTINGS;
   2175                 updatePowerStateLocked();
   2176             }
   2177         }
   2178     }
   2179 
   2180     /**
   2181      * Used by the settings application and brightness control widgets to
   2182      * temporarily override the current screen auto-brightness adjustment setting so that the
   2183      * user can observe the effect of an intended settings change without applying
   2184      * it immediately.
   2185      *
   2186      * The override will be canceled when the setting value is next updated.
   2187      *
   2188      * @param adj The overridden brightness, or Float.NaN to disable the override.
   2189      *
   2190      * @see Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
   2191      */
   2192     @Override // Binder call
   2193     public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
   2194         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2195 
   2196         final long ident = Binder.clearCallingIdentity();
   2197         try {
   2198             setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
   2199         } finally {
   2200             Binder.restoreCallingIdentity(ident);
   2201         }
   2202     }
   2203 
   2204     private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
   2205         synchronized (mLock) {
   2206             // Note: This condition handles NaN because NaN is not equal to any other
   2207             // value, including itself.
   2208             if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
   2209                 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
   2210                 mDirty |= DIRTY_SETTINGS;
   2211                 updatePowerStateLocked();
   2212             }
   2213         }
   2214     }
   2215 
   2216     /**
   2217      * Low-level function turn the device off immediately, without trying
   2218      * to be clean.  Most people should use {@link ShutdownThread} for a clean shutdown.
   2219      */
   2220     public static void lowLevelShutdown() {
   2221         SystemProperties.set("sys.powerctl", "shutdown");
   2222     }
   2223 
   2224     /**
   2225      * Low-level function to reboot the device. On success, this function
   2226      * doesn't return. If more than 5 seconds passes from the time,
   2227      * a reboot is requested, this method returns.
   2228      *
   2229      * @param reason code to pass to the kernel (e.g. "recovery"), or null.
   2230      */
   2231     public static void lowLevelReboot(String reason) {
   2232         if (reason == null) {
   2233             reason = "";
   2234         }
   2235         SystemProperties.set("sys.powerctl", "reboot," + reason);
   2236         try {
   2237             Thread.sleep(20000);
   2238         } catch (InterruptedException e) {
   2239             Thread.currentThread().interrupt();
   2240         }
   2241     }
   2242 
   2243     @Override // Watchdog.Monitor implementation
   2244     public void monitor() {
   2245         // Grab and release lock for watchdog monitor to detect deadlocks.
   2246         synchronized (mLock) {
   2247         }
   2248     }
   2249 
   2250     @Override // Binder call
   2251     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2252         if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
   2253                 != PackageManager.PERMISSION_GRANTED) {
   2254             pw.println("Permission Denial: can't dump PowerManager from from pid="
   2255                     + Binder.getCallingPid()
   2256                     + ", uid=" + Binder.getCallingUid());
   2257             return;
   2258         }
   2259 
   2260         pw.println("POWER MANAGER (dumpsys power)\n");
   2261 
   2262         final DisplayPowerController dpc;
   2263         final WirelessChargerDetector wcd;
   2264         synchronized (mLock) {
   2265             pw.println("Power Manager State:");
   2266             pw.println("  mDirty=0x" + Integer.toHexString(mDirty));
   2267             pw.println("  mWakefulness=" + wakefulnessToString(mWakefulness));
   2268             pw.println("  mIsPowered=" + mIsPowered);
   2269             pw.println("  mPlugType=" + mPlugType);
   2270             pw.println("  mBatteryLevel=" + mBatteryLevel);
   2271             pw.println("  mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
   2272             pw.println("  mDockState=" + mDockState);
   2273             pw.println("  mStayOn=" + mStayOn);
   2274             pw.println("  mProximityPositive=" + mProximityPositive);
   2275             pw.println("  mBootCompleted=" + mBootCompleted);
   2276             pw.println("  mSystemReady=" + mSystemReady);
   2277             pw.println("  mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
   2278             pw.println("  mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
   2279             pw.println("  mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
   2280             pw.println("  mSandmanScheduled=" + mSandmanScheduled);
   2281             pw.println("  mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
   2282             pw.println("  mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
   2283             pw.println("  mSendWakeUpFinishedNotificationWhenReady="
   2284                     + mSendWakeUpFinishedNotificationWhenReady);
   2285             pw.println("  mSendGoToSleepFinishedNotificationWhenReady="
   2286                     + mSendGoToSleepFinishedNotificationWhenReady);
   2287             pw.println("  mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
   2288             pw.println("  mLastUserActivityTimeNoChangeLights="
   2289                     + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
   2290             pw.println("  mDisplayReady=" + mDisplayReady);
   2291             pw.println("  mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
   2292             pw.println("  mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
   2293 
   2294             pw.println();
   2295             pw.println("Settings and Configuration:");
   2296             pw.println("  mWakeUpWhenPluggedOrUnpluggedConfig="
   2297                     + mWakeUpWhenPluggedOrUnpluggedConfig);
   2298             pw.println("  mSuspendWhenScreenOffDueToProximityConfig="
   2299                     + mSuspendWhenScreenOffDueToProximityConfig);
   2300             pw.println("  mDreamsSupportedConfig=" + mDreamsSupportedConfig);
   2301             pw.println("  mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
   2302             pw.println("  mDreamsActivatedOnSleepByDefaultConfig="
   2303                     + mDreamsActivatedOnSleepByDefaultConfig);
   2304             pw.println("  mDreamsActivatedOnDockByDefaultConfig="
   2305                     + mDreamsActivatedOnDockByDefaultConfig);
   2306             pw.println("  mDreamsEnabledSetting=" + mDreamsEnabledSetting);
   2307             pw.println("  mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
   2308             pw.println("  mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
   2309             pw.println("  mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
   2310             pw.println("  mMaximumScreenOffTimeoutFromDeviceAdmin="
   2311                     + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
   2312                     + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
   2313             pw.println("  mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
   2314             pw.println("  mScreenBrightnessSetting=" + mScreenBrightnessSetting);
   2315             pw.println("  mScreenAutoBrightnessAdjustmentSetting="
   2316                     + mScreenAutoBrightnessAdjustmentSetting);
   2317             pw.println("  mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
   2318             pw.println("  mScreenBrightnessOverrideFromWindowManager="
   2319                     + mScreenBrightnessOverrideFromWindowManager);
   2320             pw.println("  mUserActivityTimeoutOverrideFromWindowManager="
   2321                     + mUserActivityTimeoutOverrideFromWindowManager);
   2322             pw.println("  mTemporaryScreenBrightnessSettingOverride="
   2323                     + mTemporaryScreenBrightnessSettingOverride);
   2324             pw.println("  mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
   2325                     + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
   2326             pw.println("  mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
   2327             pw.println("  mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
   2328             pw.println("  mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
   2329 
   2330             final int screenOffTimeout = getScreenOffTimeoutLocked();
   2331             final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
   2332             pw.println();
   2333             pw.println("Screen off timeout: " + screenOffTimeout + " ms");
   2334             pw.println("Screen dim duration: " + screenDimDuration + " ms");
   2335 
   2336             pw.println();
   2337             pw.println("Wake Locks: size=" + mWakeLocks.size());
   2338             for (WakeLock wl : mWakeLocks) {
   2339                 pw.println("  " + wl);
   2340             }
   2341 
   2342             pw.println();
   2343             pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
   2344             for (SuspendBlocker sb : mSuspendBlockers) {
   2345                 pw.println("  " + sb);
   2346             }
   2347 
   2348             pw.println();
   2349             pw.println("Screen On Blocker: " + mScreenOnBlocker);
   2350 
   2351             pw.println();
   2352             pw.println("Display Blanker: " + mDisplayBlanker);
   2353 
   2354             dpc = mDisplayPowerController;
   2355             wcd = mWirelessChargerDetector;
   2356         }
   2357 
   2358         if (dpc != null) {
   2359             dpc.dump(pw);
   2360         }
   2361 
   2362         if (wcd != null) {
   2363             wcd.dump(pw);
   2364         }
   2365     }
   2366 
   2367     private SuspendBlocker createSuspendBlockerLocked(String name) {
   2368         SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
   2369         mSuspendBlockers.add(suspendBlocker);
   2370         return suspendBlocker;
   2371     }
   2372 
   2373     private static String wakefulnessToString(int wakefulness) {
   2374         switch (wakefulness) {
   2375             case WAKEFULNESS_ASLEEP:
   2376                 return "Asleep";
   2377             case WAKEFULNESS_AWAKE:
   2378                 return "Awake";
   2379             case WAKEFULNESS_DREAMING:
   2380                 return "Dreaming";
   2381             case WAKEFULNESS_NAPPING:
   2382                 return "Napping";
   2383             default:
   2384                 return Integer.toString(wakefulness);
   2385         }
   2386     }
   2387 
   2388     private static WorkSource copyWorkSource(WorkSource workSource) {
   2389         return workSource != null ? new WorkSource(workSource) : null;
   2390     }
   2391 
   2392     private final class BatteryReceiver extends BroadcastReceiver {
   2393         @Override
   2394         public void onReceive(Context context, Intent intent) {
   2395             synchronized (mLock) {
   2396                 handleBatteryStateChangedLocked();
   2397             }
   2398         }
   2399     }
   2400 
   2401     private final class BootCompletedReceiver extends BroadcastReceiver {
   2402         @Override
   2403         public void onReceive(Context context, Intent intent) {
   2404             // This is our early signal that the system thinks it has finished booting.
   2405             // However, the boot animation may still be running for a few more seconds
   2406             // since it is ultimately in charge of when it terminates.
   2407             // Defer transitioning into the boot completed state until the animation exits.
   2408             // We do this so that the screen does not start to dim prematurely before
   2409             // the user has actually had a chance to interact with the device.
   2410             startWatchingForBootAnimationFinished();
   2411         }
   2412     }
   2413 
   2414     private final class DreamReceiver extends BroadcastReceiver {
   2415         @Override
   2416         public void onReceive(Context context, Intent intent) {
   2417             synchronized (mLock) {
   2418                 scheduleSandmanLocked();
   2419             }
   2420         }
   2421     }
   2422 
   2423     private final class UserSwitchedReceiver extends BroadcastReceiver {
   2424         @Override
   2425         public void onReceive(Context context, Intent intent) {
   2426             synchronized (mLock) {
   2427                 handleSettingsChangedLocked();
   2428             }
   2429         }
   2430     }
   2431 
   2432     private final class DockReceiver extends BroadcastReceiver {
   2433         @Override
   2434         public void onReceive(Context context, Intent intent) {
   2435             synchronized (mLock) {
   2436                 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
   2437                         Intent.EXTRA_DOCK_STATE_UNDOCKED);
   2438                 if (mDockState != dockState) {
   2439                     mDockState = dockState;
   2440                     mDirty |= DIRTY_DOCK_STATE;
   2441                     updatePowerStateLocked();
   2442                 }
   2443             }
   2444         }
   2445     }
   2446 
   2447     private final class SettingsObserver extends ContentObserver {
   2448         public SettingsObserver(Handler handler) {
   2449             super(handler);
   2450         }
   2451 
   2452         @Override
   2453         public void onChange(boolean selfChange, Uri uri) {
   2454             synchronized (mLock) {
   2455                 handleSettingsChangedLocked();
   2456             }
   2457         }
   2458     }
   2459 
   2460     /**
   2461      * Handler for asynchronous operations performed by the power manager.
   2462      */
   2463     private final class PowerManagerHandler extends Handler {
   2464         public PowerManagerHandler(Looper looper) {
   2465             super(looper, null, true /*async*/);
   2466         }
   2467 
   2468         @Override
   2469         public void handleMessage(Message msg) {
   2470             switch (msg.what) {
   2471                 case MSG_USER_ACTIVITY_TIMEOUT:
   2472                     handleUserActivityTimeout();
   2473                     break;
   2474                 case MSG_SANDMAN:
   2475                     handleSandman();
   2476                     break;
   2477                 case MSG_SCREEN_ON_BLOCKER_RELEASED:
   2478                     handleScreenOnBlockerReleased();
   2479                     break;
   2480                 case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED:
   2481                     checkIfBootAnimationFinished();
   2482                     break;
   2483             }
   2484         }
   2485     }
   2486 
   2487     /**
   2488      * Represents a wake lock that has been acquired by an application.
   2489      */
   2490     private final class WakeLock implements IBinder.DeathRecipient {
   2491         public final IBinder mLock;
   2492         public int mFlags;
   2493         public String mTag;
   2494         public final String mPackageName;
   2495         public WorkSource mWorkSource;
   2496         public final int mOwnerUid;
   2497         public final int mOwnerPid;
   2498         public boolean mNotifiedAcquired;
   2499 
   2500         public WakeLock(IBinder lock, int flags, String tag, String packageName,
   2501                 WorkSource workSource, int ownerUid, int ownerPid) {
   2502             mLock = lock;
   2503             mFlags = flags;
   2504             mTag = tag;
   2505             mPackageName = packageName;
   2506             mWorkSource = copyWorkSource(workSource);
   2507             mOwnerUid = ownerUid;
   2508             mOwnerPid = ownerPid;
   2509         }
   2510 
   2511         @Override
   2512         public void binderDied() {
   2513             PowerManagerService.this.handleWakeLockDeath(this);
   2514         }
   2515 
   2516         public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
   2517                 int ownerUid, int ownerPid) {
   2518             return mFlags == flags
   2519                     && mTag.equals(tag)
   2520                     && hasSameWorkSource(workSource)
   2521                     && mOwnerUid == ownerUid
   2522                     && mOwnerPid == ownerPid;
   2523         }
   2524 
   2525         public void updateProperties(int flags, String tag, String packageName,
   2526                 WorkSource workSource, int ownerUid, int ownerPid) {
   2527             if (!mPackageName.equals(packageName)) {
   2528                 throw new IllegalStateException("Existing wake lock package name changed: "
   2529                         + mPackageName + " to " + packageName);
   2530             }
   2531             if (mOwnerUid != ownerUid) {
   2532                 throw new IllegalStateException("Existing wake lock uid changed: "
   2533                         + mOwnerUid + " to " + ownerUid);
   2534             }
   2535             if (mOwnerPid != ownerPid) {
   2536                 throw new IllegalStateException("Existing wake lock pid changed: "
   2537                         + mOwnerPid + " to " + ownerPid);
   2538             }
   2539             mFlags = flags;
   2540             mTag = tag;
   2541             updateWorkSource(workSource);
   2542         }
   2543 
   2544         public boolean hasSameWorkSource(WorkSource workSource) {
   2545             return Objects.equal(mWorkSource, workSource);
   2546         }
   2547 
   2548         public void updateWorkSource(WorkSource workSource) {
   2549             mWorkSource = copyWorkSource(workSource);
   2550         }
   2551 
   2552         @Override
   2553         public String toString() {
   2554             return getLockLevelString()
   2555                     + " '" + mTag + "'" + getLockFlagsString()
   2556                     + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")";
   2557         }
   2558 
   2559         private String getLockLevelString() {
   2560             switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
   2561                 case PowerManager.FULL_WAKE_LOCK:
   2562                     return "FULL_WAKE_LOCK                ";
   2563                 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
   2564                     return "SCREEN_BRIGHT_WAKE_LOCK       ";
   2565                 case PowerManager.SCREEN_DIM_WAKE_LOCK:
   2566                     return "SCREEN_DIM_WAKE_LOCK          ";
   2567                 case PowerManager.PARTIAL_WAKE_LOCK:
   2568                     return "PARTIAL_WAKE_LOCK             ";
   2569                 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
   2570                     return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
   2571                 default:
   2572                     return "???                           ";
   2573             }
   2574         }
   2575 
   2576         private String getLockFlagsString() {
   2577             String result = "";
   2578             if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
   2579                 result += " ACQUIRE_CAUSES_WAKEUP";
   2580             }
   2581             if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
   2582                 result += " ON_AFTER_RELEASE";
   2583             }
   2584             return result;
   2585         }
   2586     }
   2587 
   2588     private final class SuspendBlockerImpl implements SuspendBlocker {
   2589         private final String mName;
   2590         private int mReferenceCount;
   2591 
   2592         public SuspendBlockerImpl(String name) {
   2593             mName = name;
   2594         }
   2595 
   2596         @Override
   2597         protected void finalize() throws Throwable {
   2598             try {
   2599                 if (mReferenceCount != 0) {
   2600                     Log.wtf(TAG, "Suspend blocker \"" + mName
   2601                             + "\" was finalized without being released!");
   2602                     mReferenceCount = 0;
   2603                     nativeReleaseSuspendBlocker(mName);
   2604                 }
   2605             } finally {
   2606                 super.finalize();
   2607             }
   2608         }
   2609 
   2610         @Override
   2611         public void acquire() {
   2612             synchronized (this) {
   2613                 mReferenceCount += 1;
   2614                 if (mReferenceCount == 1) {
   2615                     if (DEBUG_SPEW) {
   2616                         Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
   2617                     }
   2618                     nativeAcquireSuspendBlocker(mName);
   2619                 }
   2620             }
   2621         }
   2622 
   2623         @Override
   2624         public void release() {
   2625             synchronized (this) {
   2626                 mReferenceCount -= 1;
   2627                 if (mReferenceCount == 0) {
   2628                     if (DEBUG_SPEW) {
   2629                         Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
   2630                     }
   2631                     nativeReleaseSuspendBlocker(mName);
   2632                 } else if (mReferenceCount < 0) {
   2633                     Log.wtf(TAG, "Suspend blocker \"" + mName
   2634                             + "\" was released without being acquired!", new Throwable());
   2635                     mReferenceCount = 0;
   2636                 }
   2637             }
   2638         }
   2639 
   2640         @Override
   2641         public String toString() {
   2642             synchronized (this) {
   2643                 return mName + ": ref count=" + mReferenceCount;
   2644             }
   2645         }
   2646     }
   2647 
   2648     private final class ScreenOnBlockerImpl implements ScreenOnBlocker {
   2649         private int mNestCount;
   2650 
   2651         public boolean isHeld() {
   2652             synchronized (this) {
   2653                 return mNestCount != 0;
   2654             }
   2655         }
   2656 
   2657         @Override
   2658         public void acquire() {
   2659             synchronized (this) {
   2660                 mNestCount += 1;
   2661                 if (DEBUG) {
   2662                     Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount);
   2663                 }
   2664             }
   2665         }
   2666 
   2667         @Override
   2668         public void release() {
   2669             synchronized (this) {
   2670                 mNestCount -= 1;
   2671                 if (mNestCount < 0) {
   2672                     Log.wtf(TAG, "Screen on blocker was released without being acquired!",
   2673                             new Throwable());
   2674                     mNestCount = 0;
   2675                 }
   2676                 if (mNestCount == 0) {
   2677                     mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED);
   2678                 }
   2679                 if (DEBUG) {
   2680                     Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount);
   2681                 }
   2682             }
   2683         }
   2684 
   2685         @Override
   2686         public String toString() {
   2687             synchronized (this) {
   2688                 return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount;
   2689             }
   2690         }
   2691     }
   2692 
   2693     private final class DisplayBlankerImpl implements DisplayBlanker {
   2694         private boolean mBlanked;
   2695 
   2696         @Override
   2697         public void blankAllDisplays() {
   2698             synchronized (this) {
   2699                 mBlanked = true;
   2700                 mDisplayManagerService.blankAllDisplaysFromPowerManager();
   2701                 nativeSetInteractive(false);
   2702                 nativeSetAutoSuspend(true);
   2703             }
   2704         }
   2705 
   2706         @Override
   2707         public void unblankAllDisplays() {
   2708             synchronized (this) {
   2709                 nativeSetAutoSuspend(false);
   2710                 nativeSetInteractive(true);
   2711                 mDisplayManagerService.unblankAllDisplaysFromPowerManager();
   2712                 mBlanked = false;
   2713             }
   2714         }
   2715 
   2716         @Override
   2717         public String toString() {
   2718             synchronized (this) {
   2719                 return "blanked=" + mBlanked;
   2720             }
   2721         }
   2722     }
   2723 }
   2724