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