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