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