PowerManagerService.java revision 72671fbb2036e13fccb0b8eeb98be606de1819dd
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            int callingUid) {
867        synchronized (mLock) {
868            int index = findWakeLockIndexLocked(lock);
869            if (index < 0) {
870                if (DEBUG_SPEW) {
871                    Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
872                            + " [not found], ws=" + ws);
873                }
874                throw new IllegalArgumentException("Wake lock not active: " + lock
875                        + " from uid " + callingUid);
876            }
877
878            WakeLock wakeLock = mWakeLocks.get(index);
879            if (DEBUG_SPEW) {
880                Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
881                        + " [" + wakeLock.mTag + "], ws=" + ws);
882            }
883
884            if (!wakeLock.hasSameWorkSource(ws)) {
885                notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
886                        wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
887                        ws, historyTag);
888                wakeLock.mHistoryTag = historyTag;
889                wakeLock.updateWorkSource(ws);
890            }
891        }
892    }
893
894    private int findWakeLockIndexLocked(IBinder lock) {
895        final int count = mWakeLocks.size();
896        for (int i = 0; i < count; i++) {
897            if (mWakeLocks.get(i).mLock == lock) {
898                return i;
899            }
900        }
901        return -1;
902    }
903
904    private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
905        if (mSystemReady) {
906            wakeLock.mNotifiedAcquired = true;
907            mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
908                    wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
909                    wakeLock.mHistoryTag);
910        }
911    }
912
913    private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
914            String packageName, int uid, int pid, WorkSource ws, String historyTag) {
915        if (mSystemReady && wakeLock.mNotifiedAcquired) {
916            mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
917                    wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
918                    wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
919        }
920    }
921
922    private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
923        if (mSystemReady && wakeLock.mNotifiedAcquired) {
924            wakeLock.mNotifiedAcquired = false;
925            mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
926                    wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
927                    wakeLock.mWorkSource, wakeLock.mHistoryTag);
928        }
929    }
930
931    @SuppressWarnings("deprecation")
932    private boolean isWakeLockLevelSupportedInternal(int level) {
933        synchronized (mLock) {
934            switch (level) {
935                case PowerManager.PARTIAL_WAKE_LOCK:
936                case PowerManager.SCREEN_DIM_WAKE_LOCK:
937                case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
938                case PowerManager.FULL_WAKE_LOCK:
939                case PowerManager.DOZE_WAKE_LOCK:
940                    return true;
941
942                case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
943                    return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
944
945                default:
946                    return false;
947            }
948        }
949    }
950
951    // Called from native code.
952    private void userActivityFromNative(long eventTime, int event, int flags) {
953        userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
954    }
955
956    private void userActivityInternal(long eventTime, int event, int flags, int uid) {
957        synchronized (mLock) {
958            if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
959                updatePowerStateLocked();
960            }
961        }
962    }
963
964    private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
965        if (DEBUG_SPEW) {
966            Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
967                    + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
968                    + ", uid=" + uid);
969        }
970
971        if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
972                || mWakefulness == WAKEFULNESS_ASLEEP || mWakefulness == WAKEFULNESS_DOZING
973                || !mBootCompleted || !mSystemReady) {
974            return false;
975        }
976
977        Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
978        try {
979            mNotifier.onUserActivity(event, uid);
980
981            if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
982                if (eventTime > mLastUserActivityTimeNoChangeLights
983                        && eventTime > mLastUserActivityTime) {
984                    mLastUserActivityTimeNoChangeLights = eventTime;
985                    mDirty |= DIRTY_USER_ACTIVITY;
986                    return true;
987                }
988            } else {
989                if (eventTime > mLastUserActivityTime) {
990                    mLastUserActivityTime = eventTime;
991                    mDirty |= DIRTY_USER_ACTIVITY;
992                    return true;
993                }
994            }
995        } finally {
996            Trace.traceEnd(Trace.TRACE_TAG_POWER);
997        }
998        return false;
999    }
1000
1001    private void wakeUpInternal(long eventTime, int uid) {
1002        synchronized (mLock) {
1003            if (wakeUpNoUpdateLocked(eventTime, uid)) {
1004                updatePowerStateLocked();
1005            }
1006        }
1007    }
1008
1009    private boolean wakeUpNoUpdateLocked(long eventTime, int uid) {
1010        if (DEBUG_SPEW) {
1011            Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
1012        }
1013
1014        if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
1015                || !mBootCompleted || !mSystemReady) {
1016            return false;
1017        }
1018
1019        Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1020        try {
1021            switch (mWakefulness) {
1022                case WAKEFULNESS_ASLEEP:
1023                    Slog.i(TAG, "Waking up from sleep (uid " + uid +")...");
1024                    break;
1025                case WAKEFULNESS_DREAMING:
1026                    Slog.i(TAG, "Waking up from dream (uid " + uid +")...");
1027                    break;
1028                case WAKEFULNESS_DOZING:
1029                    Slog.i(TAG, "Waking up from dozing (uid " + uid +")...");
1030                    break;
1031            }
1032
1033            mLastWakeTime = eventTime;
1034            mDirty |= DIRTY_WAKEFULNESS;
1035            mWakefulness = WAKEFULNESS_AWAKE;
1036            setInteractiveStateLocked(true, 0);
1037
1038            userActivityNoUpdateLocked(
1039                    eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
1040        } finally {
1041            Trace.traceEnd(Trace.TRACE_TAG_POWER);
1042        }
1043        return true;
1044    }
1045
1046    private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
1047        synchronized (mLock) {
1048            if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
1049                updatePowerStateLocked();
1050            }
1051        }
1052    }
1053
1054    // This method is called goToSleep for historical reasons but we actually start
1055    // dozing before really going to sleep.
1056    @SuppressWarnings("deprecation")
1057    private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
1058        if (DEBUG_SPEW) {
1059            Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
1060                    + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
1061        }
1062
1063        if (eventTime < mLastWakeTime
1064                || mWakefulness == WAKEFULNESS_ASLEEP
1065                || mWakefulness == WAKEFULNESS_DOZING
1066                || !mBootCompleted || !mSystemReady) {
1067            return false;
1068        }
1069
1070        Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1071        try {
1072            switch (reason) {
1073                case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
1074                    Slog.i(TAG, "Going to sleep due to device administration policy "
1075                            + "(uid " + uid +")...");
1076                    break;
1077                case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
1078                    Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")...");
1079                    break;
1080                case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH:
1081                    Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")...");
1082                    break;
1083                case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON:
1084                    Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")...");
1085                    break;
1086                case PowerManager.GO_TO_SLEEP_REASON_HDMI:
1087                    Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")...");
1088                    break;
1089                default:
1090                    Slog.i(TAG, "Going to sleep by application request (uid " + uid +")...");
1091                    reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION;
1092                    break;
1093            }
1094
1095            mLastSleepTime = eventTime;
1096            mDirty |= DIRTY_WAKEFULNESS;
1097            mWakefulness = WAKEFULNESS_DOZING;
1098            mSandmanSummoned = true;
1099            setInteractiveStateLocked(false, reason);
1100
1101            // Report the number of wake locks that will be cleared by going to sleep.
1102            int numWakeLocksCleared = 0;
1103            final int numWakeLocks = mWakeLocks.size();
1104            for (int i = 0; i < numWakeLocks; i++) {
1105                final WakeLock wakeLock = mWakeLocks.get(i);
1106                switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1107                    case PowerManager.FULL_WAKE_LOCK:
1108                    case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1109                    case PowerManager.SCREEN_DIM_WAKE_LOCK:
1110                        numWakeLocksCleared += 1;
1111                        break;
1112                }
1113            }
1114            EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
1115
1116            // Skip dozing if requested.
1117            if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1118                reallyGoToSleepNoUpdateLocked(eventTime, uid);
1119            }
1120        } finally {
1121            Trace.traceEnd(Trace.TRACE_TAG_POWER);
1122        }
1123        return true;
1124    }
1125
1126    private void napInternal(long eventTime, int uid) {
1127        synchronized (mLock) {
1128            if (napNoUpdateLocked(eventTime, uid)) {
1129                updatePowerStateLocked();
1130            }
1131        }
1132    }
1133
1134    private boolean napNoUpdateLocked(long eventTime, int uid) {
1135        if (DEBUG_SPEW) {
1136            Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
1137        }
1138
1139        if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1140                || !mBootCompleted || !mSystemReady) {
1141            return false;
1142        }
1143
1144        Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1145        try {
1146            Slog.i(TAG, "Nap time (uid " + uid +")...");
1147
1148            mDirty |= DIRTY_WAKEFULNESS;
1149            mWakefulness = WAKEFULNESS_DREAMING;
1150            mSandmanSummoned = true;
1151            setInteractiveStateLocked(true, 0);
1152        } finally {
1153            Trace.traceEnd(Trace.TRACE_TAG_POWER);
1154        }
1155        return true;
1156    }
1157
1158    // Done dozing, drop everything and go to sleep.
1159    private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
1160        if (DEBUG_SPEW) {
1161            Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1162                    + ", uid=" + uid);
1163        }
1164
1165        if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1166                || !mBootCompleted || !mSystemReady) {
1167            return false;
1168        }
1169
1170        Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1171        try {
1172            Slog.i(TAG, "Sleeping (uid " + uid +")...");
1173
1174            mDirty |= DIRTY_WAKEFULNESS;
1175            mWakefulness = WAKEFULNESS_ASLEEP;
1176            setInteractiveStateLocked(false, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1177        } finally {
1178            Trace.traceEnd(Trace.TRACE_TAG_POWER);
1179        }
1180        return true;
1181    }
1182
1183    private void setInteractiveStateLocked(boolean interactive, int reason) {
1184        if (mInteractive != interactive) {
1185            finishInteractiveStateChangeLocked();
1186
1187            mInteractive = interactive;
1188            mInteractiveChanging = true;
1189            mNotifier.onInteractiveStateChangeStarted(interactive, reason);
1190        }
1191    }
1192
1193    private void finishInteractiveStateChangeLocked() {
1194        if (mInteractiveChanging) {
1195            mNotifier.onInteractiveStateChangeFinished(mInteractive);
1196            mInteractiveChanging = false;
1197        }
1198    }
1199
1200    /**
1201     * Updates the global power state based on dirty bits recorded in mDirty.
1202     *
1203     * This is the main function that performs power state transitions.
1204     * We centralize them here so that we can recompute the power state completely
1205     * each time something important changes, and ensure that we do it the same
1206     * way each time.  The point is to gather all of the transition logic here.
1207     */
1208    private void updatePowerStateLocked() {
1209        if (!mSystemReady || mDirty == 0) {
1210            return;
1211        }
1212        if (!Thread.holdsLock(mLock)) {
1213            Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1214        }
1215
1216        Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1217        try {
1218            // Phase 0: Basic state updates.
1219            updateIsPoweredLocked(mDirty);
1220            updateStayOnLocked(mDirty);
1221
1222            // Phase 1: Update wakefulness.
1223            // Loop because the wake lock and user activity computations are influenced
1224            // by changes in wakefulness.
1225            final long now = SystemClock.uptimeMillis();
1226            int dirtyPhase2 = 0;
1227            for (;;) {
1228                int dirtyPhase1 = mDirty;
1229                dirtyPhase2 |= dirtyPhase1;
1230                mDirty = 0;
1231
1232                updateWakeLockSummaryLocked(dirtyPhase1);
1233                updateUserActivitySummaryLocked(now, dirtyPhase1);
1234                if (!updateWakefulnessLocked(dirtyPhase1)) {
1235                    break;
1236                }
1237            }
1238
1239            // Phase 2: Update dreams and display power state.
1240            updateDreamLocked(dirtyPhase2);
1241            updateDisplayPowerStateLocked(dirtyPhase2);
1242
1243            // Phase 3: Send notifications, if needed.
1244            if (mDisplayReady) {
1245                finishInteractiveStateChangeLocked();
1246            }
1247
1248            // Phase 4: Update suspend blocker.
1249            // Because we might release the last suspend blocker here, we need to make sure
1250            // we finished everything else first!
1251            updateSuspendBlockerLocked();
1252        } finally {
1253            Trace.traceEnd(Trace.TRACE_TAG_POWER);
1254        }
1255    }
1256
1257    /**
1258     * Updates the value of mIsPowered.
1259     * Sets DIRTY_IS_POWERED if a change occurred.
1260     */
1261    private void updateIsPoweredLocked(int dirty) {
1262        if ((dirty & DIRTY_BATTERY_STATE) != 0) {
1263            final boolean wasPowered = mIsPowered;
1264            final int oldPlugType = mPlugType;
1265            final boolean oldLevelLow = mBatteryLevelLow;
1266            mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1267            mPlugType = mBatteryManagerInternal.getPlugType();
1268            mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1269            mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
1270
1271            if (DEBUG_SPEW) {
1272                Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
1273                        + ", mIsPowered=" + mIsPowered
1274                        + ", oldPlugType=" + oldPlugType
1275                        + ", mPlugType=" + mPlugType
1276                        + ", mBatteryLevel=" + mBatteryLevel);
1277            }
1278
1279            if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
1280                mDirty |= DIRTY_IS_POWERED;
1281
1282                // Update wireless dock detection state.
1283                final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1284                        mIsPowered, mPlugType, mBatteryLevel);
1285
1286                // Treat plugging and unplugging the devices as a user activity.
1287                // Users find it disconcerting when they plug or unplug the device
1288                // and it shuts off right away.
1289                // Some devices also wake the device when plugged or unplugged because
1290                // they don't have a charging LED.
1291                final long now = SystemClock.uptimeMillis();
1292                if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1293                        dockedOnWirelessCharger)) {
1294                    wakeUpNoUpdateLocked(now, Process.SYSTEM_UID);
1295                }
1296                userActivityNoUpdateLocked(
1297                        now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1298
1299                // Tell the notifier whether wireless charging has started so that
1300                // it can provide feedback to the user.
1301                if (dockedOnWirelessCharger) {
1302                    mNotifier.onWirelessChargingStarted();
1303                }
1304            }
1305
1306            if (wasPowered != mIsPowered || oldLevelLow != mBatteryLevelLow) {
1307                if (oldLevelLow != mBatteryLevelLow && !mBatteryLevelLow) {
1308                    if (DEBUG_SPEW) {
1309                        Slog.d(TAG, "updateIsPoweredLocked: resetting low power snooze");
1310                    }
1311                    mAutoLowPowerModeSnoozing = false;
1312                }
1313                updateLowPowerModeLocked();
1314            }
1315        }
1316    }
1317
1318    private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1319            boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
1320        // Don't wake when powered unless configured to do so.
1321        if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1322            return false;
1323        }
1324
1325        // Don't wake when undocked from wireless charger.
1326        // See WirelessChargerDetector for justification.
1327        if (wasPowered && !mIsPowered
1328                && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1329            return false;
1330        }
1331
1332        // Don't wake when docked on wireless charger unless we are certain of it.
1333        // See WirelessChargerDetector for justification.
1334        if (!wasPowered && mIsPowered
1335                && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
1336                && !dockedOnWirelessCharger) {
1337            return false;
1338        }
1339
1340        // If already dreaming and becoming powered, then don't wake.
1341        if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
1342            return false;
1343        }
1344
1345        // Otherwise wake up!
1346        return true;
1347    }
1348
1349    /**
1350     * Updates the value of mStayOn.
1351     * Sets DIRTY_STAY_ON if a change occurred.
1352     */
1353    private void updateStayOnLocked(int dirty) {
1354        if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
1355            final boolean wasStayOn = mStayOn;
1356            if (mStayOnWhilePluggedInSetting != 0
1357                    && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1358                mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
1359            } else {
1360                mStayOn = false;
1361            }
1362
1363            if (mStayOn != wasStayOn) {
1364                mDirty |= DIRTY_STAY_ON;
1365            }
1366        }
1367    }
1368
1369    /**
1370     * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1371     * Note that most wake-locks are ignored when the system is asleep.
1372     *
1373     * This function must have no other side-effects.
1374     */
1375    @SuppressWarnings("deprecation")
1376    private void updateWakeLockSummaryLocked(int dirty) {
1377        if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1378            mWakeLockSummary = 0;
1379
1380            final int numWakeLocks = mWakeLocks.size();
1381            for (int i = 0; i < numWakeLocks; i++) {
1382                final WakeLock wakeLock = mWakeLocks.get(i);
1383                switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1384                    case PowerManager.PARTIAL_WAKE_LOCK:
1385                        mWakeLockSummary |= WAKE_LOCK_CPU;
1386                        break;
1387                    case PowerManager.FULL_WAKE_LOCK:
1388                        mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1389                        break;
1390                    case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1391                        mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT;
1392                        break;
1393                    case PowerManager.SCREEN_DIM_WAKE_LOCK:
1394                        mWakeLockSummary |= WAKE_LOCK_SCREEN_DIM;
1395                        break;
1396                    case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1397                        mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1398                        break;
1399                    case PowerManager.DOZE_WAKE_LOCK:
1400                        mWakeLockSummary |= WAKE_LOCK_DOZE;
1401                        break;
1402                }
1403            }
1404
1405            // Cancel wake locks that make no sense based on the current state.
1406            if (mWakefulness != WAKEFULNESS_DOZING) {
1407                mWakeLockSummary &= ~WAKE_LOCK_DOZE;
1408            }
1409            if (mWakefulness == WAKEFULNESS_ASLEEP
1410                    || (mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1411                mWakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1412                        | WAKE_LOCK_BUTTON_BRIGHT);
1413                if (mWakefulness == WAKEFULNESS_ASLEEP) {
1414                    mWakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1415                }
1416            }
1417
1418            // Infer implied wake locks where necessary based on the current state.
1419            if ((mWakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1420                if (mWakefulness == WAKEFULNESS_AWAKE) {
1421                    mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1422                } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1423                    mWakeLockSummary |= WAKE_LOCK_CPU;
1424                }
1425            }
1426
1427            if (DEBUG_SPEW) {
1428                Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
1429                        + wakefulnessToString(mWakefulness)
1430                        + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1431            }
1432        }
1433    }
1434
1435    /**
1436     * Updates the value of mUserActivitySummary to summarize the user requested
1437     * state of the system such as whether the screen should be bright or dim.
1438     * Note that user activity is ignored when the system is asleep.
1439     *
1440     * This function must have no other side-effects.
1441     */
1442    private void updateUserActivitySummaryLocked(long now, int dirty) {
1443        // Update the status of the user activity timeout timer.
1444        if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
1445                | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
1446            mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1447
1448            long nextTimeout = 0;
1449            if (mWakefulness == WAKEFULNESS_AWAKE
1450                    || mWakefulness == WAKEFULNESS_DREAMING
1451                    || mWakefulness == WAKEFULNESS_DOZING) {
1452                final int screenOffTimeout = getScreenOffTimeoutLocked();
1453                final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
1454
1455                mUserActivitySummary = 0;
1456                if (mLastUserActivityTime >= mLastWakeTime) {
1457                    nextTimeout = mLastUserActivityTime
1458                            + screenOffTimeout - screenDimDuration;
1459                    if (now < nextTimeout) {
1460                        mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT;
1461                    } else {
1462                        nextTimeout = mLastUserActivityTime + screenOffTimeout;
1463                        if (now < nextTimeout) {
1464                            mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM;
1465                        }
1466                    }
1467                }
1468                if (mUserActivitySummary == 0
1469                        && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
1470                    nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
1471                    if (now < nextTimeout) {
1472                        if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT) {
1473                            mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
1474                        } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
1475                            mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
1476                        }
1477                    }
1478                }
1479                if (mUserActivitySummary != 0) {
1480                    Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
1481                    msg.setAsynchronous(true);
1482                    mHandler.sendMessageAtTime(msg, nextTimeout);
1483                }
1484            } else {
1485                mUserActivitySummary = 0;
1486            }
1487
1488            if (DEBUG_SPEW) {
1489                Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
1490                        + wakefulnessToString(mWakefulness)
1491                        + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1492                        + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
1493            }
1494        }
1495    }
1496
1497    /**
1498     * Called when a user activity timeout has occurred.
1499     * Simply indicates that something about user activity has changed so that the new
1500     * state can be recomputed when the power state is updated.
1501     *
1502     * This function must have no other side-effects besides setting the dirty
1503     * bit and calling update power state.  Wakefulness transitions are handled elsewhere.
1504     */
1505    private void handleUserActivityTimeout() { // runs on handler thread
1506        synchronized (mLock) {
1507            if (DEBUG_SPEW) {
1508                Slog.d(TAG, "handleUserActivityTimeout");
1509            }
1510
1511            mDirty |= DIRTY_USER_ACTIVITY;
1512            updatePowerStateLocked();
1513        }
1514    }
1515
1516    private int getScreenOffTimeoutLocked() {
1517        int timeout = mScreenOffTimeoutSetting;
1518        if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1519            timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
1520        }
1521        if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
1522            timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
1523        }
1524        return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
1525    }
1526
1527    private int getScreenDimDurationLocked(int screenOffTimeout) {
1528        return Math.min(mMaximumScreenDimDurationConfig,
1529                (int)(screenOffTimeout * mMaximumScreenDimRatioConfig));
1530    }
1531
1532    /**
1533     * Updates the wakefulness of the device.
1534     *
1535     * This is the function that decides whether the device should start dreaming
1536     * based on the current wake locks and user activity state.  It may modify mDirty
1537     * if the wakefulness changes.
1538     *
1539     * Returns true if the wakefulness changed and we need to restart power state calculation.
1540     */
1541    private boolean updateWakefulnessLocked(int dirty) {
1542        boolean changed = false;
1543        if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
1544                | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
1545                | DIRTY_DOCK_STATE)) != 0) {
1546            if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
1547                if (DEBUG_SPEW) {
1548                    Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
1549                }
1550                final long time = SystemClock.uptimeMillis();
1551                if (shouldNapAtBedTimeLocked()) {
1552                    changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
1553                } else {
1554                    changed = goToSleepNoUpdateLocked(time,
1555                            PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
1556                }
1557            }
1558        }
1559        return changed;
1560    }
1561
1562    /**
1563     * Returns true if the device should automatically nap and start dreaming when the user
1564     * activity timeout has expired and it's bedtime.
1565     */
1566    private boolean shouldNapAtBedTimeLocked() {
1567        return mDreamsActivateOnSleepSetting
1568                || (mDreamsActivateOnDockSetting
1569                        && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
1570    }
1571
1572    /**
1573     * Returns true if the device should go to sleep now.
1574     * Also used when exiting a dream to determine whether we should go back
1575     * to being fully awake or else go to sleep for good.
1576     */
1577    private boolean isItBedTimeYetLocked() {
1578        return mBootCompleted && !isBeingKeptAwakeLocked();
1579    }
1580
1581    /**
1582     * Returns true if the device is being kept awake by a wake lock, user activity
1583     * or the stay on while powered setting.  We also keep the phone awake when
1584     * the proximity sensor returns a positive result so that the device does not
1585     * lock while in a phone call.  This function only controls whether the device
1586     * will go to sleep or dream which is independent of whether it will be allowed
1587     * to suspend.
1588     */
1589    private boolean isBeingKeptAwakeLocked() {
1590        return mStayOn
1591                || mProximityPositive
1592                || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1593                || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
1594                        | USER_ACTIVITY_SCREEN_DIM)) != 0;
1595    }
1596
1597    /**
1598     * Determines whether to post a message to the sandman to update the dream state.
1599     */
1600    private void updateDreamLocked(int dirty) {
1601        if ((dirty & (DIRTY_WAKEFULNESS
1602                | DIRTY_USER_ACTIVITY
1603                | DIRTY_WAKE_LOCKS
1604                | DIRTY_BOOT_COMPLETED
1605                | DIRTY_SETTINGS
1606                | DIRTY_IS_POWERED
1607                | DIRTY_STAY_ON
1608                | DIRTY_PROXIMITY_POSITIVE
1609                | DIRTY_BATTERY_STATE)) != 0) {
1610            scheduleSandmanLocked();
1611        }
1612    }
1613
1614    private void scheduleSandmanLocked() {
1615        if (!mSandmanScheduled) {
1616            mSandmanScheduled = true;
1617            Message msg = mHandler.obtainMessage(MSG_SANDMAN);
1618            msg.setAsynchronous(true);
1619            mHandler.sendMessage(msg);
1620        }
1621    }
1622
1623    /**
1624     * Called when the device enters or exits a dreaming or dozing state.
1625     *
1626     * We do this asynchronously because we must call out of the power manager to start
1627     * the dream and we don't want to hold our lock while doing so.  There is a risk that
1628     * the device will wake or go to sleep in the meantime so we have to handle that case.
1629     */
1630    private void handleSandman() { // runs on handler thread
1631        // Handle preconditions.
1632        final boolean startDreaming;
1633        final int wakefulness;
1634        synchronized (mLock) {
1635            mSandmanScheduled = false;
1636            wakefulness = mWakefulness;
1637            if (mSandmanSummoned) {
1638                startDreaming = ((wakefulness == WAKEFULNESS_DREAMING && canDreamLocked())
1639                        || wakefulness == WAKEFULNESS_DOZING);
1640                mSandmanSummoned = false;
1641            } else {
1642                startDreaming = false;
1643            }
1644        }
1645
1646        // Start dreaming if needed.
1647        // We only control the dream on the handler thread, so we don't need to worry about
1648        // concurrent attempts to start or stop the dream.
1649        final boolean isDreaming;
1650        if (mDreamManager != null) {
1651            // Restart the dream whenever the sandman is summoned.
1652            if (startDreaming) {
1653                mDreamManager.stopDream(false /*immediate*/);
1654                mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
1655            }
1656            isDreaming = mDreamManager.isDreaming();
1657        } else {
1658            isDreaming = false;
1659        }
1660
1661        // Update dream state.
1662        synchronized (mLock) {
1663            // Remember the initial battery level when the dream started.
1664            if (startDreaming && isDreaming) {
1665                mBatteryLevelWhenDreamStarted = mBatteryLevel;
1666                if (wakefulness == WAKEFULNESS_DOZING) {
1667                    Slog.i(TAG, "Dozing...");
1668                } else {
1669                    Slog.i(TAG, "Dreaming...");
1670                }
1671            }
1672
1673            // If preconditions changed, wait for the next iteration to determine
1674            // whether the dream should continue (or be restarted).
1675            if (mSandmanSummoned || mWakefulness != wakefulness) {
1676                return; // wait for next cycle
1677            }
1678
1679            // Determine whether the dream should continue.
1680            if (wakefulness == WAKEFULNESS_DREAMING) {
1681                if (isDreaming && canDreamLocked()) {
1682                    if (mDreamsBatteryLevelDrainCutoffConfig >= 0
1683                            && mBatteryLevel < mBatteryLevelWhenDreamStarted
1684                                    - mDreamsBatteryLevelDrainCutoffConfig
1685                            && !isBeingKeptAwakeLocked()) {
1686                        // If the user activity timeout expired and the battery appears
1687                        // to be draining faster than it is charging then stop dreaming
1688                        // and go to sleep.
1689                        Slog.i(TAG, "Stopping dream because the battery appears to "
1690                                + "be draining faster than it is charging.  "
1691                                + "Battery level when dream started: "
1692                                + mBatteryLevelWhenDreamStarted + "%.  "
1693                                + "Battery level now: " + mBatteryLevel + "%.");
1694                    } else {
1695                        return; // continue dreaming
1696                    }
1697                }
1698
1699                // Dream has ended or will be stopped.  Update the power state.
1700                if (isItBedTimeYetLocked()) {
1701                    goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
1702                            PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
1703                    updatePowerStateLocked();
1704                } else {
1705                    wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
1706                    updatePowerStateLocked();
1707                }
1708            } else if (wakefulness == WAKEFULNESS_DOZING) {
1709                if (isDreaming) {
1710                    return; // continue dozing
1711                }
1712
1713                // Doze has ended or will be stopped.  Update the power state.
1714                reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
1715                updatePowerStateLocked();
1716            }
1717        }
1718
1719        // Stop dream.
1720        if (isDreaming) {
1721            mDreamManager.stopDream(false /*immediate*/);
1722        }
1723    }
1724
1725    /**
1726     * Returns true if the device is allowed to dream in its current state.
1727     * This function is not called when dozing.
1728     */
1729    private boolean canDreamLocked() {
1730        if (mWakefulness != WAKEFULNESS_DREAMING
1731                || !mDreamsSupportedConfig
1732                || !mDreamsEnabledSetting
1733                || !mDisplayPowerRequest.isBrightOrDim()
1734                || !mBootCompleted) {
1735            return false;
1736        }
1737        if (!isBeingKeptAwakeLocked()) {
1738            if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
1739                return false;
1740            }
1741            if (!mIsPowered
1742                    && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
1743                    && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
1744                return false;
1745            }
1746            if (mIsPowered
1747                    && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
1748                    && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
1749                return false;
1750            }
1751        }
1752        return true;
1753    }
1754
1755    private void handleScreenOnBlockerReleased() {
1756        synchronized (mLock) {
1757            mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED;
1758            updatePowerStateLocked();
1759        }
1760    }
1761
1762    /**
1763     * Updates the display power state asynchronously.
1764     * When the update is finished, mDisplayReady will be set to true.  The display
1765     * controller posts a message to tell us when the actual display power state
1766     * has been updated so we come back here to double-check and finish up.
1767     *
1768     * This function recalculates the display power state each time.
1769     */
1770    private void updateDisplayPowerStateLocked(int dirty) {
1771        if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
1772                | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
1773                | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) {
1774            mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
1775
1776            int screenBrightness = mScreenBrightnessSettingDefault;
1777            float screenAutoBrightnessAdjustment = 0.0f;
1778            boolean autoBrightness = (mScreenBrightnessModeSetting ==
1779                    Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
1780            if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
1781                screenBrightness = mScreenBrightnessOverrideFromWindowManager;
1782                autoBrightness = false;
1783            } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
1784                screenBrightness = mTemporaryScreenBrightnessSettingOverride;
1785            } else if (isValidBrightness(mScreenBrightnessSetting)) {
1786                screenBrightness = mScreenBrightnessSetting;
1787            }
1788            if (autoBrightness) {
1789                screenBrightness = mScreenBrightnessSettingDefault;
1790                if (isValidAutoBrightnessAdjustment(
1791                        mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
1792                    screenAutoBrightnessAdjustment =
1793                            mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
1794                } else if (isValidAutoBrightnessAdjustment(
1795                        mScreenAutoBrightnessAdjustmentSetting)) {
1796                    screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
1797                }
1798            }
1799            screenBrightness = Math.max(Math.min(screenBrightness,
1800                    mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
1801            screenAutoBrightnessAdjustment = Math.max(Math.min(
1802                    screenAutoBrightnessAdjustment, 1.0f), -1.0f);
1803            mDisplayPowerRequest.screenBrightness = screenBrightness;
1804            mDisplayPowerRequest.screenAutoBrightnessAdjustment =
1805                    screenAutoBrightnessAdjustment;
1806            mDisplayPowerRequest.useAutoBrightness = autoBrightness;
1807
1808            mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
1809
1810            mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld();
1811
1812            mDisplayPowerRequest.lowPowerMode = mLowPowerModeEnabled;
1813
1814            if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
1815                mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
1816                mDisplayPowerRequest.dozeScreenBrightness =
1817                        mDozeScreenBrightnessOverrideFromDreamManager;
1818            } else {
1819                mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
1820                mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
1821            }
1822
1823            mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
1824                    mRequestWaitForNegativeProximity);
1825            mRequestWaitForNegativeProximity = false;
1826
1827            if (DEBUG_SPEW) {
1828                Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady
1829                        + ", policy=" + mDisplayPowerRequest.policy
1830                        + ", mWakefulness=" + mWakefulness
1831                        + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
1832                        + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1833                        + ", mBootCompleted=" + mBootCompleted);
1834            }
1835        }
1836    }
1837
1838    private static boolean isValidBrightness(int value) {
1839        return value >= 0 && value <= 255;
1840    }
1841
1842    private static boolean isValidAutoBrightnessAdjustment(float value) {
1843        // Handles NaN by always returning false.
1844        return value >= -1.0f && value <= 1.0f;
1845    }
1846
1847    private int getDesiredScreenPolicyLocked() {
1848        if (mWakefulness == WAKEFULNESS_ASLEEP) {
1849            return DisplayPowerRequest.POLICY_OFF;
1850        }
1851
1852        if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1853            return DisplayPowerRequest.POLICY_DOZE;
1854        }
1855
1856        if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
1857                || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
1858                || !mBootCompleted) {
1859            return DisplayPowerRequest.POLICY_BRIGHT;
1860        }
1861
1862        return DisplayPowerRequest.POLICY_DIM;
1863    }
1864
1865    private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
1866            new DisplayManagerInternal.DisplayPowerCallbacks() {
1867        private int mDisplayState = Display.STATE_UNKNOWN;
1868
1869        @Override
1870        public void onStateChanged() {
1871            synchronized (mLock) {
1872                mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
1873                updatePowerStateLocked();
1874            }
1875        }
1876
1877        @Override
1878        public void onProximityPositive() {
1879            synchronized (mLock) {
1880                mProximityPositive = true;
1881                mDirty |= DIRTY_PROXIMITY_POSITIVE;
1882                updatePowerStateLocked();
1883            }
1884        }
1885
1886        @Override
1887        public void onProximityNegative() {
1888            synchronized (mLock) {
1889                mProximityPositive = false;
1890                mDirty |= DIRTY_PROXIMITY_POSITIVE;
1891                userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1892                        PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1893                updatePowerStateLocked();
1894            }
1895        }
1896
1897        @Override
1898        public void onDisplayStateChange(int state) {
1899            // This method is only needed to support legacy display blanking behavior
1900            // where the display's power state is coupled to suspend or to the power HAL.
1901            // The order of operations matters here.
1902            synchronized (mLock) {
1903                if (mDisplayState != state) {
1904                    mDisplayState = state;
1905                    if (state == Display.STATE_OFF) {
1906                        if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
1907                            setHalInteractiveModeLocked(false);
1908                        }
1909                        if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1910                            setHalAutoSuspendModeLocked(true);
1911                        }
1912                    } else {
1913                        if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1914                            setHalAutoSuspendModeLocked(false);
1915                        }
1916                        if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
1917                            setHalInteractiveModeLocked(true);
1918                        }
1919                    }
1920                }
1921            }
1922        }
1923
1924        @Override
1925        public void acquireSuspendBlocker() {
1926            mDisplaySuspendBlocker.acquire();
1927        }
1928
1929        @Override
1930        public void releaseSuspendBlocker() {
1931            mDisplaySuspendBlocker.release();
1932        }
1933
1934        @Override
1935        public String toString() {
1936            synchronized (this) {
1937                return "state=" + Display.stateToString(mDisplayState);
1938            }
1939        }
1940    };
1941
1942    private boolean shouldUseProximitySensorLocked() {
1943        return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
1944    }
1945
1946    /**
1947     * Updates the suspend blocker that keeps the CPU alive.
1948     *
1949     * This function must have no other side-effects.
1950     */
1951    private void updateSuspendBlockerLocked() {
1952        final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
1953        final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
1954        final boolean autoSuspend = !needDisplaySuspendBlocker;
1955
1956        // Disable auto-suspend if needed.
1957        if (!autoSuspend) {
1958            if (mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1959                setHalAutoSuspendModeLocked(false);
1960            }
1961            if (mDecoupleHalInteractiveModeFromDisplayConfig) {
1962                setHalInteractiveModeLocked(true);
1963            }
1964        }
1965
1966        // First acquire suspend blockers if needed.
1967        if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
1968            mWakeLockSuspendBlocker.acquire();
1969            mHoldingWakeLockSuspendBlocker = true;
1970        }
1971        if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
1972            mDisplaySuspendBlocker.acquire();
1973            mHoldingDisplaySuspendBlocker = true;
1974        }
1975
1976        // Then release suspend blockers if needed.
1977        if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
1978            mWakeLockSuspendBlocker.release();
1979            mHoldingWakeLockSuspendBlocker = false;
1980        }
1981        if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
1982            mDisplaySuspendBlocker.release();
1983            mHoldingDisplaySuspendBlocker = false;
1984        }
1985
1986        // Enable auto-suspend if needed.
1987        if (autoSuspend) {
1988            if (mDecoupleHalInteractiveModeFromDisplayConfig) {
1989                setHalInteractiveModeLocked(false);
1990            }
1991            if (mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1992                setHalAutoSuspendModeLocked(true);
1993            }
1994        }
1995    }
1996
1997    /**
1998     * Return true if we must keep a suspend blocker active on behalf of the display.
1999     * We do so if the screen is on or is in transition between states.
2000     */
2001    private boolean needDisplaySuspendBlockerLocked() {
2002        if (!mDisplayReady) {
2003            return true;
2004        }
2005        if (mDisplayPowerRequest.isBrightOrDim()) {
2006            // If we asked for the screen to be on but it is off due to the proximity
2007            // sensor then we may suspend but only if the configuration allows it.
2008            // On some hardware it may not be safe to suspend because the proximity
2009            // sensor may not be correctly configured as a wake-up source.
2010            if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2011                    || !mSuspendWhenScreenOffDueToProximityConfig) {
2012                return true;
2013            }
2014        }
2015        // Let the system suspend if the screen is off or dozing.
2016        return false;
2017    }
2018
2019    private void setHalAutoSuspendModeLocked(boolean enable) {
2020        if (enable != mHalAutoSuspendModeEnabled) {
2021            if (DEBUG) {
2022                Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
2023            }
2024            mHalAutoSuspendModeEnabled = enable;
2025            Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2026            try {
2027                nativeSetAutoSuspend(enable);
2028            } finally {
2029                Trace.traceEnd(Trace.TRACE_TAG_POWER);
2030            }
2031        }
2032    }
2033
2034    private void setHalInteractiveModeLocked(boolean enable) {
2035        if (enable != mHalInteractiveModeEnabled) {
2036            if (DEBUG) {
2037                Slog.d(TAG, "Setting HAL interactive mode to " + enable);
2038            }
2039            mHalInteractiveModeEnabled = enable;
2040            Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2041            try {
2042                nativeSetInteractive(enable);
2043            } finally {
2044                Trace.traceEnd(Trace.TRACE_TAG_POWER);
2045            }
2046        }
2047    }
2048
2049    private boolean isInteractiveInternal() {
2050        synchronized (mLock) {
2051            return mInteractive;
2052        }
2053    }
2054
2055    private boolean isLowPowerModeInternal() {
2056        synchronized (mLock) {
2057            return mLowPowerModeEnabled;
2058        }
2059    }
2060
2061    private void handleBatteryStateChangedLocked() {
2062        mDirty |= DIRTY_BATTERY_STATE;
2063        updatePowerStateLocked();
2064    }
2065
2066    private void startWatchingForBootAnimationFinished() {
2067        mHandler.sendEmptyMessage(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED);
2068    }
2069
2070    private void checkIfBootAnimationFinished() {
2071        if (DEBUG) {
2072            Slog.d(TAG, "Check if boot animation finished...");
2073        }
2074
2075        if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) {
2076            mHandler.sendEmptyMessageDelayed(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED,
2077                    BOOT_ANIMATION_POLL_INTERVAL);
2078            return;
2079        }
2080
2081        synchronized (mLock) {
2082            if (!mBootCompleted) {
2083                Slog.i(TAG, "Boot animation finished.");
2084                handleBootCompletedLocked();
2085            }
2086        }
2087    }
2088
2089    private void handleBootCompletedLocked() {
2090        final long now = SystemClock.uptimeMillis();
2091        mBootCompleted = true;
2092        mDirty |= DIRTY_BOOT_COMPLETED;
2093        userActivityNoUpdateLocked(
2094                now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2095        updatePowerStateLocked();
2096    }
2097
2098    private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
2099            final String reason, boolean wait) {
2100        if (mHandler == null || !mSystemReady) {
2101            throw new IllegalStateException("Too early to call shutdown() or reboot()");
2102        }
2103
2104        Runnable runnable = new Runnable() {
2105            @Override
2106            public void run() {
2107                synchronized (this) {
2108                    if (shutdown) {
2109                        ShutdownThread.shutdown(mContext, confirm);
2110                    } else {
2111                        ShutdownThread.reboot(mContext, reason, confirm);
2112                    }
2113                }
2114            }
2115        };
2116
2117        // ShutdownThread must run on a looper capable of displaying the UI.
2118        Message msg = Message.obtain(mHandler, runnable);
2119        msg.setAsynchronous(true);
2120        mHandler.sendMessage(msg);
2121
2122        // PowerManager.reboot() is documented not to return so just wait for the inevitable.
2123        if (wait) {
2124            synchronized (runnable) {
2125                while (true) {
2126                    try {
2127                        runnable.wait();
2128                    } catch (InterruptedException e) {
2129                    }
2130                }
2131            }
2132        }
2133    }
2134
2135    private void crashInternal(final String message) {
2136        Thread t = new Thread("PowerManagerService.crash()") {
2137            @Override
2138            public void run() {
2139                throw new RuntimeException(message);
2140            }
2141        };
2142        try {
2143            t.start();
2144            t.join();
2145        } catch (InterruptedException e) {
2146            Log.wtf(TAG, e);
2147        }
2148    }
2149
2150    private void setStayOnSettingInternal(int val) {
2151        Settings.Global.putInt(mContext.getContentResolver(),
2152                Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
2153    }
2154
2155    private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
2156        synchronized (mLock) {
2157            mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2158            mDirty |= DIRTY_SETTINGS;
2159            updatePowerStateLocked();
2160        }
2161    }
2162
2163    private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
2164        return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
2165                && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
2166    }
2167
2168    private void setAttentionLightInternal(boolean on, int color) {
2169        Light light;
2170        synchronized (mLock) {
2171            if (!mSystemReady) {
2172                return;
2173            }
2174            light = mAttentionLight;
2175        }
2176
2177        // Control light outside of lock.
2178        light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
2179    }
2180
2181    private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
2182        synchronized (mLock) {
2183            if (mScreenBrightnessOverrideFromWindowManager != brightness) {
2184                mScreenBrightnessOverrideFromWindowManager = brightness;
2185                mDirty |= DIRTY_SETTINGS;
2186                updatePowerStateLocked();
2187            }
2188        }
2189    }
2190
2191    private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
2192        synchronized (mLock) {
2193            if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
2194                mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
2195                mDirty |= DIRTY_SETTINGS;
2196                updatePowerStateLocked();
2197            }
2198        }
2199    }
2200
2201    private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
2202        synchronized (mLock) {
2203            if (mTemporaryScreenBrightnessSettingOverride != brightness) {
2204                mTemporaryScreenBrightnessSettingOverride = brightness;
2205                mDirty |= DIRTY_SETTINGS;
2206                updatePowerStateLocked();
2207            }
2208        }
2209    }
2210
2211    private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
2212        synchronized (mLock) {
2213            // Note: This condition handles NaN because NaN is not equal to any other
2214            // value, including itself.
2215            if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
2216                mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
2217                mDirty |= DIRTY_SETTINGS;
2218                updatePowerStateLocked();
2219            }
2220        }
2221    }
2222
2223    private void setDozeOverrideFromDreamManagerInternal(
2224            int screenState, int screenBrightness) {
2225        synchronized (mLock) {
2226            if (mDozeScreenStateOverrideFromDreamManager != screenState
2227                    || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
2228                mDozeScreenStateOverrideFromDreamManager = screenState;
2229                mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
2230                mDirty |= DIRTY_SETTINGS;
2231                updatePowerStateLocked();
2232            }
2233        }
2234    }
2235
2236    private void powerHintInternal(int hintId, int data) {
2237        nativeSendPowerHint(hintId, data);
2238    }
2239
2240    /**
2241     * Low-level function turn the device off immediately, without trying
2242     * to be clean.  Most people should use {@link ShutdownThread} for a clean shutdown.
2243     */
2244    public static void lowLevelShutdown() {
2245        SystemProperties.set("sys.powerctl", "shutdown");
2246    }
2247
2248    /**
2249     * Low-level function to reboot the device. On success, this
2250     * function doesn't return. If more than 20 seconds passes from
2251     * the time a reboot is requested (120 seconds for reboot to
2252     * recovery), this method returns.
2253     *
2254     * @param reason code to pass to the kernel (e.g. "recovery"), or null.
2255     */
2256    public static void lowLevelReboot(String reason) {
2257        if (reason == null) {
2258            reason = "";
2259        }
2260        long duration;
2261        if (reason.equals(PowerManager.REBOOT_RECOVERY)) {
2262            // If we are rebooting to go into recovery, instead of
2263            // setting sys.powerctl directly we'll start the
2264            // pre-recovery service which will do some preparation for
2265            // recovery and then reboot for us.
2266            //
2267            // This preparation can take more than 20 seconds if
2268            // there's a very large update package, so lengthen the
2269            // timeout.
2270            SystemProperties.set("ctl.start", "pre-recovery");
2271            duration = 120 * 1000L;
2272        } else {
2273            SystemProperties.set("sys.powerctl", "reboot," + reason);
2274            duration = 20 * 1000L;
2275        }
2276        try {
2277            Thread.sleep(duration);
2278        } catch (InterruptedException e) {
2279            Thread.currentThread().interrupt();
2280        }
2281    }
2282
2283    @Override // Watchdog.Monitor implementation
2284    public void monitor() {
2285        // Grab and release lock for watchdog monitor to detect deadlocks.
2286        synchronized (mLock) {
2287        }
2288    }
2289
2290    private void dumpInternal(PrintWriter pw) {
2291        pw.println("POWER MANAGER (dumpsys power)\n");
2292
2293        final WirelessChargerDetector wcd;
2294        synchronized (mLock) {
2295            pw.println("Power Manager State:");
2296            pw.println("  mDirty=0x" + Integer.toHexString(mDirty));
2297            pw.println("  mWakefulness=" + wakefulnessToString(mWakefulness));
2298            pw.println("  mInteractive=" + mInteractive);
2299            pw.println("  mIsPowered=" + mIsPowered);
2300            pw.println("  mPlugType=" + mPlugType);
2301            pw.println("  mBatteryLevel=" + mBatteryLevel);
2302            pw.println("  mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
2303            pw.println("  mDockState=" + mDockState);
2304            pw.println("  mStayOn=" + mStayOn);
2305            pw.println("  mProximityPositive=" + mProximityPositive);
2306            pw.println("  mBootCompleted=" + mBootCompleted);
2307            pw.println("  mSystemReady=" + mSystemReady);
2308            pw.println("  mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
2309            pw.println("  mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
2310            pw.println("  mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
2311            pw.println("  mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
2312            pw.println("  mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
2313            pw.println("  mSandmanScheduled=" + mSandmanScheduled);
2314            pw.println("  mSandmanSummoned=" + mSandmanSummoned);
2315            pw.println("  mLowPowerModeEnabled=" + mLowPowerModeEnabled);
2316            pw.println("  mBatteryLevelLow=" + mBatteryLevelLow);
2317            pw.println("  mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
2318            pw.println("  mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
2319            pw.println("  mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
2320            pw.println("  mLastUserActivityTimeNoChangeLights="
2321                    + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
2322            pw.println("  mDisplayReady=" + mDisplayReady);
2323            pw.println("  mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
2324            pw.println("  mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
2325
2326            pw.println();
2327            pw.println("Settings and Configuration:");
2328            pw.println("  mDecoupleHalAutoSuspendModeFromDisplayConfig="
2329                    + mDecoupleHalAutoSuspendModeFromDisplayConfig);
2330            pw.println("  mDecoupleHalInteractiveModeFromDisplayConfig="
2331                    + mDecoupleHalInteractiveModeFromDisplayConfig);
2332            pw.println("  mWakeUpWhenPluggedOrUnpluggedConfig="
2333                    + mWakeUpWhenPluggedOrUnpluggedConfig);
2334            pw.println("  mSuspendWhenScreenOffDueToProximityConfig="
2335                    + mSuspendWhenScreenOffDueToProximityConfig);
2336            pw.println("  mDreamsSupportedConfig=" + mDreamsSupportedConfig);
2337            pw.println("  mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
2338            pw.println("  mDreamsActivatedOnSleepByDefaultConfig="
2339                    + mDreamsActivatedOnSleepByDefaultConfig);
2340            pw.println("  mDreamsActivatedOnDockByDefaultConfig="
2341                    + mDreamsActivatedOnDockByDefaultConfig);
2342            pw.println("  mDreamsEnabledOnBatteryConfig="
2343                    + mDreamsEnabledOnBatteryConfig);
2344            pw.println("  mDreamsBatteryLevelMinimumWhenPoweredConfig="
2345                    + mDreamsBatteryLevelMinimumWhenPoweredConfig);
2346            pw.println("  mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
2347                    + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
2348            pw.println("  mDreamsBatteryLevelDrainCutoffConfig="
2349                    + mDreamsBatteryLevelDrainCutoffConfig);
2350            pw.println("  mDreamsEnabledSetting=" + mDreamsEnabledSetting);
2351            pw.println("  mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
2352            pw.println("  mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
2353            pw.println("  mLowPowerModeSetting=" + mLowPowerModeSetting);
2354            pw.println("  mAutoLowPowerModeEnabled=" + mAutoLowPowerModeEnabled);
2355            pw.println("  mAutoLowPowerModeSnoozing=" + mAutoLowPowerModeSnoozing);
2356            pw.println("  mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
2357            pw.println("  mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
2358            pw.println("  mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
2359            pw.println("  mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
2360            pw.println("  mMaximumScreenOffTimeoutFromDeviceAdmin="
2361                    + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
2362                    + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
2363            pw.println("  mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
2364            pw.println("  mScreenBrightnessSetting=" + mScreenBrightnessSetting);
2365            pw.println("  mScreenAutoBrightnessAdjustmentSetting="
2366                    + mScreenAutoBrightnessAdjustmentSetting);
2367            pw.println("  mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
2368            pw.println("  mScreenBrightnessOverrideFromWindowManager="
2369                    + mScreenBrightnessOverrideFromWindowManager);
2370            pw.println("  mUserActivityTimeoutOverrideFromWindowManager="
2371                    + mUserActivityTimeoutOverrideFromWindowManager);
2372            pw.println("  mTemporaryScreenBrightnessSettingOverride="
2373                    + mTemporaryScreenBrightnessSettingOverride);
2374            pw.println("  mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
2375                    + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
2376            pw.println("  mDozeScreenStateOverrideFromDreamManager="
2377                    + mDozeScreenStateOverrideFromDreamManager);
2378            pw.println("  mDozeScreenBrightnessOverrideFromDreamManager="
2379                    + mDozeScreenBrightnessOverrideFromDreamManager);
2380            pw.println("  mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
2381            pw.println("  mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
2382            pw.println("  mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
2383
2384            final int screenOffTimeout = getScreenOffTimeoutLocked();
2385            final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
2386            pw.println();
2387            pw.println("Screen off timeout: " + screenOffTimeout + " ms");
2388            pw.println("Screen dim duration: " + screenDimDuration + " ms");
2389
2390            pw.println();
2391            pw.println("Wake Locks: size=" + mWakeLocks.size());
2392            for (WakeLock wl : mWakeLocks) {
2393                pw.println("  " + wl);
2394            }
2395
2396            pw.println();
2397            pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
2398            for (SuspendBlocker sb : mSuspendBlockers) {
2399                pw.println("  " + sb);
2400            }
2401
2402            pw.println();
2403            pw.println("Screen On Blocker: " + mScreenOnBlocker);
2404
2405            pw.println();
2406            pw.println("Display Power: " + mDisplayPowerCallbacks);
2407
2408            wcd = mWirelessChargerDetector;
2409        }
2410
2411        if (wcd != null) {
2412            wcd.dump(pw);
2413        }
2414    }
2415
2416    private SuspendBlocker createSuspendBlockerLocked(String name) {
2417        SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
2418        mSuspendBlockers.add(suspendBlocker);
2419        return suspendBlocker;
2420    }
2421
2422    private static String wakefulnessToString(int wakefulness) {
2423        switch (wakefulness) {
2424            case WAKEFULNESS_ASLEEP:
2425                return "Asleep";
2426            case WAKEFULNESS_AWAKE:
2427                return "Awake";
2428            case WAKEFULNESS_DREAMING:
2429                return "Dreaming";
2430            case WAKEFULNESS_DOZING:
2431                return "Dozing";
2432            default:
2433                return Integer.toString(wakefulness);
2434        }
2435    }
2436
2437    private static WorkSource copyWorkSource(WorkSource workSource) {
2438        return workSource != null ? new WorkSource(workSource) : null;
2439    }
2440
2441    private final class BatteryReceiver extends BroadcastReceiver {
2442        @Override
2443        public void onReceive(Context context, Intent intent) {
2444            synchronized (mLock) {
2445                handleBatteryStateChangedLocked();
2446            }
2447        }
2448    }
2449
2450    private final class DreamReceiver extends BroadcastReceiver {
2451        @Override
2452        public void onReceive(Context context, Intent intent) {
2453            synchronized (mLock) {
2454                scheduleSandmanLocked();
2455            }
2456        }
2457    }
2458
2459    private final class UserSwitchedReceiver extends BroadcastReceiver {
2460        @Override
2461        public void onReceive(Context context, Intent intent) {
2462            synchronized (mLock) {
2463                handleSettingsChangedLocked();
2464            }
2465        }
2466    }
2467
2468    private final class DockReceiver extends BroadcastReceiver {
2469        @Override
2470        public void onReceive(Context context, Intent intent) {
2471            synchronized (mLock) {
2472                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2473                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
2474                if (mDockState != dockState) {
2475                    mDockState = dockState;
2476                    mDirty |= DIRTY_DOCK_STATE;
2477                    updatePowerStateLocked();
2478                }
2479            }
2480        }
2481    }
2482
2483    private final class SettingsObserver extends ContentObserver {
2484        public SettingsObserver(Handler handler) {
2485            super(handler);
2486        }
2487
2488        @Override
2489        public void onChange(boolean selfChange, Uri uri) {
2490            synchronized (mLock) {
2491                handleSettingsChangedLocked();
2492            }
2493        }
2494    }
2495
2496    /**
2497     * Handler for asynchronous operations performed by the power manager.
2498     */
2499    private final class PowerManagerHandler extends Handler {
2500        public PowerManagerHandler(Looper looper) {
2501            super(looper, null, true /*async*/);
2502        }
2503
2504        @Override
2505        public void handleMessage(Message msg) {
2506            switch (msg.what) {
2507                case MSG_USER_ACTIVITY_TIMEOUT:
2508                    handleUserActivityTimeout();
2509                    break;
2510                case MSG_SANDMAN:
2511                    handleSandman();
2512                    break;
2513                case MSG_SCREEN_ON_BLOCKER_RELEASED:
2514                    handleScreenOnBlockerReleased();
2515                    break;
2516                case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED:
2517                    checkIfBootAnimationFinished();
2518                    break;
2519            }
2520        }
2521    }
2522
2523    /**
2524     * Represents a wake lock that has been acquired by an application.
2525     */
2526    private final class WakeLock implements IBinder.DeathRecipient {
2527        public final IBinder mLock;
2528        public int mFlags;
2529        public String mTag;
2530        public final String mPackageName;
2531        public WorkSource mWorkSource;
2532        public String mHistoryTag;
2533        public final int mOwnerUid;
2534        public final int mOwnerPid;
2535        public boolean mNotifiedAcquired;
2536
2537        public WakeLock(IBinder lock, int flags, String tag, String packageName,
2538                WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
2539            mLock = lock;
2540            mFlags = flags;
2541            mTag = tag;
2542            mPackageName = packageName;
2543            mWorkSource = copyWorkSource(workSource);
2544            mHistoryTag = historyTag;
2545            mOwnerUid = ownerUid;
2546            mOwnerPid = ownerPid;
2547        }
2548
2549        @Override
2550        public void binderDied() {
2551            PowerManagerService.this.handleWakeLockDeath(this);
2552        }
2553
2554        public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
2555                int ownerUid, int ownerPid) {
2556            return mFlags == flags
2557                    && mTag.equals(tag)
2558                    && hasSameWorkSource(workSource)
2559                    && mOwnerUid == ownerUid
2560                    && mOwnerPid == ownerPid;
2561        }
2562
2563        public void updateProperties(int flags, String tag, String packageName,
2564                WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
2565            if (!mPackageName.equals(packageName)) {
2566                throw new IllegalStateException("Existing wake lock package name changed: "
2567                        + mPackageName + " to " + packageName);
2568            }
2569            if (mOwnerUid != ownerUid) {
2570                throw new IllegalStateException("Existing wake lock uid changed: "
2571                        + mOwnerUid + " to " + ownerUid);
2572            }
2573            if (mOwnerPid != ownerPid) {
2574                throw new IllegalStateException("Existing wake lock pid changed: "
2575                        + mOwnerPid + " to " + ownerPid);
2576            }
2577            mFlags = flags;
2578            mTag = tag;
2579            updateWorkSource(workSource);
2580            mHistoryTag = historyTag;
2581        }
2582
2583        public boolean hasSameWorkSource(WorkSource workSource) {
2584            return Objects.equal(mWorkSource, workSource);
2585        }
2586
2587        public void updateWorkSource(WorkSource workSource) {
2588            mWorkSource = copyWorkSource(workSource);
2589        }
2590
2591        @Override
2592        public String toString() {
2593            return getLockLevelString()
2594                    + " '" + mTag + "'" + getLockFlagsString()
2595                    + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")";
2596        }
2597
2598        @SuppressWarnings("deprecation")
2599        private String getLockLevelString() {
2600            switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2601                case PowerManager.FULL_WAKE_LOCK:
2602                    return "FULL_WAKE_LOCK                ";
2603                case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2604                    return "SCREEN_BRIGHT_WAKE_LOCK       ";
2605                case PowerManager.SCREEN_DIM_WAKE_LOCK:
2606                    return "SCREEN_DIM_WAKE_LOCK          ";
2607                case PowerManager.PARTIAL_WAKE_LOCK:
2608                    return "PARTIAL_WAKE_LOCK             ";
2609                case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2610                    return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
2611                case PowerManager.DOZE_WAKE_LOCK:
2612                    return "DOZE_WAKE_LOCK                ";
2613                default:
2614                    return "???                           ";
2615            }
2616        }
2617
2618        private String getLockFlagsString() {
2619            String result = "";
2620            if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
2621                result += " ACQUIRE_CAUSES_WAKEUP";
2622            }
2623            if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
2624                result += " ON_AFTER_RELEASE";
2625            }
2626            return result;
2627        }
2628    }
2629
2630    private final class SuspendBlockerImpl implements SuspendBlocker {
2631        private final String mName;
2632        private final String mTraceName;
2633        private int mReferenceCount;
2634
2635        public SuspendBlockerImpl(String name) {
2636            mName = name;
2637            mTraceName = "SuspendBlocker (" + name + ")";
2638        }
2639
2640        @Override
2641        protected void finalize() throws Throwable {
2642            try {
2643                if (mReferenceCount != 0) {
2644                    Slog.wtf(TAG, "Suspend blocker \"" + mName
2645                            + "\" was finalized without being released!");
2646                    mReferenceCount = 0;
2647                    nativeReleaseSuspendBlocker(mName);
2648                    Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
2649                }
2650            } finally {
2651                super.finalize();
2652            }
2653        }
2654
2655        @Override
2656        public void acquire() {
2657            synchronized (this) {
2658                mReferenceCount += 1;
2659                if (mReferenceCount == 1) {
2660                    if (DEBUG_SPEW) {
2661                        Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
2662                    }
2663                    Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
2664                    nativeAcquireSuspendBlocker(mName);
2665                }
2666            }
2667        }
2668
2669        @Override
2670        public void release() {
2671            synchronized (this) {
2672                mReferenceCount -= 1;
2673                if (mReferenceCount == 0) {
2674                    if (DEBUG_SPEW) {
2675                        Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
2676                    }
2677                    nativeReleaseSuspendBlocker(mName);
2678                    Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
2679                } else if (mReferenceCount < 0) {
2680                    Slog.wtf(TAG, "Suspend blocker \"" + mName
2681                            + "\" was released without being acquired!", new Throwable());
2682                    mReferenceCount = 0;
2683                }
2684            }
2685        }
2686
2687        @Override
2688        public String toString() {
2689            synchronized (this) {
2690                return mName + ": ref count=" + mReferenceCount;
2691            }
2692        }
2693    }
2694
2695    private final class ScreenOnBlockerImpl implements ScreenOnBlocker {
2696        private static final String TRACE_NAME = "ScreenOnBlocker";
2697
2698        private int mNestCount;
2699
2700        public boolean isHeld() {
2701            synchronized (this) {
2702                return mNestCount != 0;
2703            }
2704        }
2705
2706        @Override
2707        public void acquire() {
2708            synchronized (this) {
2709                mNestCount += 1;
2710                if (DEBUG || true) {
2711                    Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount);
2712                }
2713                if (mNestCount == 1) {
2714                    Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_NAME, 0);
2715                }
2716            }
2717        }
2718
2719        @Override
2720        public void release() {
2721            synchronized (this) {
2722                mNestCount -= 1;
2723                if (mNestCount == 0) {
2724                    if (DEBUG || true) {
2725                        Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount);
2726                    }
2727                    mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED);
2728                    Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_NAME, 0);
2729                } else if (mNestCount < 0) {
2730                    Slog.wtf(TAG, "Screen on blocker was released without being acquired!",
2731                            new Throwable());
2732                    mNestCount = 0;
2733                }
2734            }
2735        }
2736
2737        @Override
2738        public String toString() {
2739            synchronized (this) {
2740                return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount;
2741            }
2742        }
2743    }
2744
2745    private final class BinderService extends IPowerManager.Stub {
2746        @Override // Binder call
2747        public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
2748                String packageName, int uid) {
2749            if (uid < 0) {
2750                uid = Binder.getCallingUid();
2751            }
2752            acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
2753        }
2754
2755        @Override // Binder call
2756        public void powerHint(int hintId, int data) {
2757            if (!mSystemReady) {
2758                // Service not ready yet, so who the heck cares about power hints, bah.
2759                return;
2760            }
2761            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2762            powerHintInternal(hintId, data);
2763        }
2764
2765        @Override // Binder call
2766        public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
2767                WorkSource ws, String historyTag) {
2768            if (lock == null) {
2769                throw new IllegalArgumentException("lock must not be null");
2770            }
2771            if (packageName == null) {
2772                throw new IllegalArgumentException("packageName must not be null");
2773            }
2774            PowerManager.validateWakeLockParameters(flags, tag);
2775
2776            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2777            if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
2778                mContext.enforceCallingOrSelfPermission(
2779                        android.Manifest.permission.DEVICE_POWER, null);
2780            }
2781            if (ws != null && ws.size() != 0) {
2782                mContext.enforceCallingOrSelfPermission(
2783                        android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2784            } else {
2785                ws = null;
2786            }
2787
2788            final int uid = Binder.getCallingUid();
2789            final int pid = Binder.getCallingPid();
2790            final long ident = Binder.clearCallingIdentity();
2791            try {
2792                acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
2793            } finally {
2794                Binder.restoreCallingIdentity(ident);
2795            }
2796        }
2797
2798        @Override // Binder call
2799        public void releaseWakeLock(IBinder lock, int flags) {
2800            if (lock == null) {
2801                throw new IllegalArgumentException("lock must not be null");
2802            }
2803
2804            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2805
2806            final long ident = Binder.clearCallingIdentity();
2807            try {
2808                releaseWakeLockInternal(lock, flags);
2809            } finally {
2810                Binder.restoreCallingIdentity(ident);
2811            }
2812        }
2813
2814        @Override // Binder call
2815        public void updateWakeLockUids(IBinder lock, int[] uids) {
2816            WorkSource ws = null;
2817
2818            if (uids != null) {
2819                ws = new WorkSource();
2820                // XXX should WorkSource have a way to set uids as an int[] instead of adding them
2821                // one at a time?
2822                for (int i = 0; i < uids.length; i++) {
2823                    ws.add(uids[i]);
2824                }
2825            }
2826            updateWakeLockWorkSource(lock, ws, null);
2827        }
2828
2829        @Override // Binder call
2830        public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
2831            if (lock == null) {
2832                throw new IllegalArgumentException("lock must not be null");
2833            }
2834
2835            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2836            if (ws != null && ws.size() != 0) {
2837                mContext.enforceCallingOrSelfPermission(
2838                        android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2839            } else {
2840                ws = null;
2841            }
2842
2843            final int callingUid = Binder.getCallingUid();
2844            final long ident = Binder.clearCallingIdentity();
2845            try {
2846                updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
2847            } finally {
2848                Binder.restoreCallingIdentity(ident);
2849            }
2850        }
2851
2852        @Override // Binder call
2853        public boolean isWakeLockLevelSupported(int level) {
2854            final long ident = Binder.clearCallingIdentity();
2855            try {
2856                return isWakeLockLevelSupportedInternal(level);
2857            } finally {
2858                Binder.restoreCallingIdentity(ident);
2859            }
2860        }
2861
2862        @Override // Binder call
2863        public void userActivity(long eventTime, int event, int flags) {
2864            final long now = SystemClock.uptimeMillis();
2865            if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2866                    != PackageManager.PERMISSION_GRANTED) {
2867                // Once upon a time applications could call userActivity().
2868                // Now we require the DEVICE_POWER permission.  Log a warning and ignore the
2869                // request instead of throwing a SecurityException so we don't break old apps.
2870                synchronized (mLock) {
2871                    if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
2872                        mLastWarningAboutUserActivityPermission = now;
2873                        Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
2874                                + "caller does not have DEVICE_POWER permission.  "
2875                                + "Please fix your app!  "
2876                                + " pid=" + Binder.getCallingPid()
2877                                + " uid=" + Binder.getCallingUid());
2878                    }
2879                }
2880                return;
2881            }
2882
2883            if (eventTime > SystemClock.uptimeMillis()) {
2884                throw new IllegalArgumentException("event time must not be in the future");
2885            }
2886
2887            final int uid = Binder.getCallingUid();
2888            final long ident = Binder.clearCallingIdentity();
2889            try {
2890                userActivityInternal(eventTime, event, flags, uid);
2891            } finally {
2892                Binder.restoreCallingIdentity(ident);
2893            }
2894        }
2895
2896        @Override // Binder call
2897        public void wakeUp(long eventTime) {
2898            if (eventTime > SystemClock.uptimeMillis()) {
2899                throw new IllegalArgumentException("event time must not be in the future");
2900            }
2901
2902            mContext.enforceCallingOrSelfPermission(
2903                    android.Manifest.permission.DEVICE_POWER, null);
2904
2905            final int uid = Binder.getCallingUid();
2906            final long ident = Binder.clearCallingIdentity();
2907            try {
2908                wakeUpInternal(eventTime, uid);
2909            } finally {
2910                Binder.restoreCallingIdentity(ident);
2911            }
2912        }
2913
2914        @Override // Binder call
2915        public void goToSleep(long eventTime, int reason, int flags) {
2916            if (eventTime > SystemClock.uptimeMillis()) {
2917                throw new IllegalArgumentException("event time must not be in the future");
2918            }
2919
2920            mContext.enforceCallingOrSelfPermission(
2921                    android.Manifest.permission.DEVICE_POWER, null);
2922
2923            final int uid = Binder.getCallingUid();
2924            final long ident = Binder.clearCallingIdentity();
2925            try {
2926                goToSleepInternal(eventTime, reason, flags, uid);
2927            } finally {
2928                Binder.restoreCallingIdentity(ident);
2929            }
2930        }
2931
2932        @Override // Binder call
2933        public void nap(long eventTime) {
2934            if (eventTime > SystemClock.uptimeMillis()) {
2935                throw new IllegalArgumentException("event time must not be in the future");
2936            }
2937
2938            mContext.enforceCallingOrSelfPermission(
2939                    android.Manifest.permission.DEVICE_POWER, null);
2940
2941            final int uid = Binder.getCallingUid();
2942            final long ident = Binder.clearCallingIdentity();
2943            try {
2944                napInternal(eventTime, uid);
2945            } finally {
2946                Binder.restoreCallingIdentity(ident);
2947            }
2948        }
2949
2950        @Override // Binder call
2951        public boolean isInteractive() {
2952            final long ident = Binder.clearCallingIdentity();
2953            try {
2954                return isInteractiveInternal();
2955            } finally {
2956                Binder.restoreCallingIdentity(ident);
2957            }
2958        }
2959
2960        @Override // Binder call
2961        public boolean isPowerSaveMode() {
2962            final long ident = Binder.clearCallingIdentity();
2963            try {
2964                return isLowPowerModeInternal();
2965            } finally {
2966                Binder.restoreCallingIdentity(ident);
2967            }
2968        }
2969
2970        /**
2971         * Reboots the device.
2972         *
2973         * @param confirm If true, shows a reboot confirmation dialog.
2974         * @param reason The reason for the reboot, or null if none.
2975         * @param wait If true, this call waits for the reboot to complete and does not return.
2976         */
2977        @Override // Binder call
2978        public void reboot(boolean confirm, String reason, boolean wait) {
2979            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2980            if (PowerManager.REBOOT_RECOVERY.equals(reason)) {
2981                mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
2982            }
2983
2984            final long ident = Binder.clearCallingIdentity();
2985            try {
2986                shutdownOrRebootInternal(false, confirm, reason, wait);
2987            } finally {
2988                Binder.restoreCallingIdentity(ident);
2989            }
2990        }
2991
2992        /**
2993         * Shuts down the device.
2994         *
2995         * @param confirm If true, shows a shutdown confirmation dialog.
2996         * @param wait If true, this call waits for the shutdown to complete and does not return.
2997         */
2998        @Override // Binder call
2999        public void shutdown(boolean confirm, boolean wait) {
3000            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3001
3002            final long ident = Binder.clearCallingIdentity();
3003            try {
3004                shutdownOrRebootInternal(true, confirm, null, wait);
3005            } finally {
3006                Binder.restoreCallingIdentity(ident);
3007            }
3008        }
3009
3010        /**
3011         * Crash the runtime (causing a complete restart of the Android framework).
3012         * Requires REBOOT permission.  Mostly for testing.  Should not return.
3013         */
3014        @Override // Binder call
3015        public void crash(String message) {
3016            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3017
3018            final long ident = Binder.clearCallingIdentity();
3019            try {
3020                crashInternal(message);
3021            } finally {
3022                Binder.restoreCallingIdentity(ident);
3023            }
3024        }
3025
3026        /**
3027         * Set the setting that determines whether the device stays on when plugged in.
3028         * The argument is a bit string, with each bit specifying a power source that,
3029         * when the device is connected to that source, causes the device to stay on.
3030         * See {@link android.os.BatteryManager} for the list of power sources that
3031         * can be specified. Current values include
3032         * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
3033         * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
3034         *
3035         * Used by "adb shell svc power stayon ..."
3036         *
3037         * @param val an {@code int} containing the bits that specify which power sources
3038         * should cause the device to stay on.
3039         */
3040        @Override // Binder call
3041        public void setStayOnSetting(int val) {
3042            mContext.enforceCallingOrSelfPermission(
3043                    android.Manifest.permission.WRITE_SETTINGS, null);
3044
3045            final long ident = Binder.clearCallingIdentity();
3046            try {
3047                setStayOnSettingInternal(val);
3048            } finally {
3049                Binder.restoreCallingIdentity(ident);
3050            }
3051        }
3052
3053        /**
3054         * Used by device administration to set the maximum screen off timeout.
3055         *
3056         * This method must only be called by the device administration policy manager.
3057         */
3058        @Override // Binder call
3059        public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
3060            final long ident = Binder.clearCallingIdentity();
3061            try {
3062                setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
3063            } finally {
3064                Binder.restoreCallingIdentity(ident);
3065            }
3066        }
3067
3068        /**
3069         * Used by the settings application and brightness control widgets to
3070         * temporarily override the current screen brightness setting so that the
3071         * user can observe the effect of an intended settings change without applying
3072         * it immediately.
3073         *
3074         * The override will be canceled when the setting value is next updated.
3075         *
3076         * @param brightness The overridden brightness.
3077         *
3078         * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
3079         */
3080        @Override // Binder call
3081        public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
3082            mContext.enforceCallingOrSelfPermission(
3083                    android.Manifest.permission.DEVICE_POWER, null);
3084
3085            final long ident = Binder.clearCallingIdentity();
3086            try {
3087                setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
3088            } finally {
3089                Binder.restoreCallingIdentity(ident);
3090            }
3091        }
3092
3093        /**
3094         * Used by the settings application and brightness control widgets to
3095         * temporarily override the current screen auto-brightness adjustment setting so that the
3096         * user can observe the effect of an intended settings change without applying
3097         * it immediately.
3098         *
3099         * The override will be canceled when the setting value is next updated.
3100         *
3101         * @param adj The overridden brightness, or Float.NaN to disable the override.
3102         *
3103         * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
3104         */
3105        @Override // Binder call
3106        public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
3107            mContext.enforceCallingOrSelfPermission(
3108                    android.Manifest.permission.DEVICE_POWER, null);
3109
3110            final long ident = Binder.clearCallingIdentity();
3111            try {
3112                setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
3113            } finally {
3114                Binder.restoreCallingIdentity(ident);
3115            }
3116        }
3117
3118        /**
3119         * Used by the phone application to make the attention LED flash when ringing.
3120         */
3121        @Override // Binder call
3122        public void setAttentionLight(boolean on, int color) {
3123            mContext.enforceCallingOrSelfPermission(
3124                    android.Manifest.permission.DEVICE_POWER, null);
3125
3126            final long ident = Binder.clearCallingIdentity();
3127            try {
3128                setAttentionLightInternal(on, color);
3129            } finally {
3130                Binder.restoreCallingIdentity(ident);
3131            }
3132        }
3133
3134        @Override // Binder call
3135        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3136            if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
3137                    != PackageManager.PERMISSION_GRANTED) {
3138                pw.println("Permission Denial: can't dump PowerManager from from pid="
3139                        + Binder.getCallingPid()
3140                        + ", uid=" + Binder.getCallingUid());
3141                return;
3142            }
3143
3144            final long ident = Binder.clearCallingIdentity();
3145            try {
3146                dumpInternal(pw);
3147            } finally {
3148                Binder.restoreCallingIdentity(ident);
3149            }
3150        }
3151    }
3152
3153    private final class LocalService extends PowerManagerInternal {
3154        @Override
3155        public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
3156            if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
3157                    || screenBrightness > PowerManager.BRIGHTNESS_ON) {
3158                screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
3159            }
3160            setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
3161        }
3162
3163        @Override
3164        public void setButtonBrightnessOverrideFromWindowManager(int screenBrightness) {
3165            // Do nothing.
3166            // Button lights are not currently supported in the new implementation.
3167        }
3168
3169        @Override
3170        public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
3171            switch (screenState) {
3172                case Display.STATE_UNKNOWN:
3173                case Display.STATE_OFF:
3174                case Display.STATE_DOZE:
3175                case Display.STATE_DOZE_SUSPEND:
3176                case Display.STATE_ON:
3177                    break;
3178                default:
3179                    screenState = Display.STATE_UNKNOWN;
3180                    break;
3181            }
3182            if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
3183                    || screenBrightness > PowerManager.BRIGHTNESS_ON) {
3184                screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
3185            }
3186            setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
3187        }
3188
3189        @Override
3190        public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
3191            setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
3192        }
3193
3194        @Override
3195        public boolean getLowPowerModeEnabled() {
3196            synchronized (mLock) {
3197                return mLowPowerModeEnabled;
3198            }
3199        }
3200
3201        @Override
3202        public void registerLowPowerModeObserver(LowPowerModeListener listener) {
3203            synchronized (mLock) {
3204                mLowPowerModeListeners.add(listener);
3205            }
3206        }
3207    }
3208}
3209