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