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