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