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