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