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