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