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