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