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