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