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