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