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