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