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