blob: 1bb85c4426e12a7c977d8f29abd58ea94ba3099c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Jeff Brown4f8ecd82012-06-18 18:29:13 -070017package com.android.server.power;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
Beverlyae79ab92017-12-11 09:20:02 -050019import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
20import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
21import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
22import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
23
Tony Mantlerb8009fd2016-03-14 15:55:35 -070024import android.annotation.IntDef;
Pavel Grafov28939982017-10-03 15:11:52 +010025import android.annotation.UserIdInt;
Jason Monkafae4bd2015-12-15 14:20:06 -050026import android.app.ActivityManager;
Pavel Grafov28939982017-10-03 15:11:52 +010027import android.app.SynchronousUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070034import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080035import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080036import android.hardware.SensorManager;
37import android.hardware.SystemSensorManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080038import android.hardware.display.DisplayManagerInternal;
Jeff Brown131206b2014-04-08 17:27:14 -070039import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Ruchi Kandoi0d434042016-10-03 09:12:02 -070040import android.hardware.power.V1_0.PowerHint;
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -070041import android.metrics.LogMaker;
Jeff Brown96307042012-07-27 15:51:34 -070042import android.net.Uri;
Amith Yamasani8b619832010-09-22 16:11:59 -070043import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070044import android.os.BatteryManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Binder;
46import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.IBinder;
48import android.os.IPowerManager;
Jeff Brown96307042012-07-27 15:51:34 -070049import android.os.Looper;
Jim Miller92e66dd2012-02-21 18:57:12 -080050import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -070052import android.os.PowerManager.ServiceType;
Jeff Brown6f357d32014-01-15 20:40:55 -080053import android.os.PowerManagerInternal;
jackqdyulei92681e82017-02-28 11:26:28 -080054import android.os.PowerSaveState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Process;
56import android.os.RemoteException;
Jocelyn Dangf2c38c12017-03-31 14:03:37 -070057import android.os.ResultReceiver;
58import android.os.ShellCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070060import android.os.SystemProperties;
Jeff Brown3edf5272014-08-14 19:25:14 -070061import android.os.Trace;
Jeff Brownd4935962012-09-25 13:27:20 -070062import android.os.UserHandle;
Christine Franks732c0432017-06-23 18:12:46 -070063import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070064import android.os.WorkSource;
Narayan Kamath2f916ed2017-12-29 13:02:15 +000065import android.os.WorkSource.WorkChain;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.provider.Settings;
Daichi Hirono82ab9802016-03-02 13:23:29 +090067import android.provider.Settings.SettingNotFoundException;
Jeff Brown567f7ca2014-01-30 23:38:03 -080068import android.service.dreams.DreamManagerInternal;
Ruben Brunkc7be3be2016-04-01 17:07:51 -070069import android.service.vr.IVrManager;
70import android.service.vr.IVrStateCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.util.EventLog;
Dianne Hackborn0ef403e2017-01-24 18:22:15 -080072import android.util.KeyValueListParser;
Michael Wrightd8460232018-01-16 18:04:59 +000073import android.util.MathUtils;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -070074import android.util.PrintWriterPrinter;
Joe Onorato8a9b2202010-02-26 18:56:32 -080075import android.util.Slog;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -070076import android.util.SparseArray;
Jeff Brown96307042012-07-27 15:51:34 -070077import android.util.TimeUtils;
Netta P958d0a52017-02-07 11:20:55 -080078import android.util.proto.ProtoOutputStream;
Jeff Brown037c33e2014-04-09 00:31:55 -070079import android.view.Display;
Makoto Onukiaae89532017-11-08 14:32:03 -080080
jackqdyulei92681e82017-02-28 11:26:28 -080081import com.android.internal.annotations.VisibleForTesting;
Jason Monkafae4bd2015-12-15 14:20:06 -050082import com.android.internal.app.IAppOpsService;
83import com.android.internal.app.IBatteryStats;
Adrian Roos56021892017-02-27 20:25:09 +010084import com.android.internal.hardware.AmbientDisplayConfiguration;
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -070085import com.android.internal.logging.MetricsLogger;
86import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Jason Monkafae4bd2015-12-15 14:20:06 -050087import com.android.internal.os.BackgroundThread;
Jeff Sharkey3dee8d62016-03-02 13:07:56 -070088import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060089import com.android.internal.util.DumpUtils;
Jason Monkafae4bd2015-12-15 14:20:06 -050090import com.android.server.EventLogTags;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060091import com.android.server.LockGuard;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -070092import com.android.server.RescueParty;
Jason Monkafae4bd2015-12-15 14:20:06 -050093import com.android.server.ServiceThread;
94import com.android.server.SystemService;
Michael Wright64c820d2017-03-21 12:36:55 +000095import com.android.server.UiThread;
Jason Monkafae4bd2015-12-15 14:20:06 -050096import com.android.server.Watchdog;
97import com.android.server.am.BatteryStatsService;
98import com.android.server.lights.Light;
99import com.android.server.lights.LightsManager;
Adrian Roose99bc052017-11-20 17:55:31 +0100100import com.android.server.policy.WindowManagerPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800101import com.android.server.power.batterysaver.BatterySaverController;
102
Jason Monkafae4bd2015-12-15 14:20:06 -0500103import libcore.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
105import java.io.FileDescriptor;
106import java.io.PrintWriter;
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700107import java.lang.annotation.Retention;
108import java.lang.annotation.RetentionPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.ArrayList;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700110import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Jeff Brown96307042012-07-27 15:51:34 -0700112/**
113 * The power manager service is responsible for coordinating power management
114 * functions on the device.
115 */
Jeff Brown2175e9c2014-09-12 16:11:07 -0700116public final class PowerManagerService extends SystemService
Jeff Brown96307042012-07-27 15:51:34 -0700117 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Santos Cordon4ddb8012017-09-20 15:25:44 -0700120 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -0700121 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -0700122
Beverlyae79ab92017-12-11 09:20:02 -0500123 // if DEBUG_WIRELESS=true, plays wireless charging animation w/ sound on every plug + unplug
124 private static final boolean DEBUG_WIRELESS = false;
125
Jeff Brown96307042012-07-27 15:51:34 -0700126 // Message: Sent when a user activity timeout occurs to update the power state.
127 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -0800128 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -0700129 private static final int MSG_SANDMAN = 2;
Jeff Browne333e672014-10-28 13:48:55 -0700130 // Message: Sent when the screen brightness boost expires.
131 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700132 // Message: Polling to look for long held wake locks.
133 private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
Jeff Brown7304c342012-05-11 18:42:42 -0700134
Jeff Brown96307042012-07-27 15:51:34 -0700135 // Dirty bit: mWakeLocks changed
136 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
137 // Dirty bit: mWakefulness changed
138 private static final int DIRTY_WAKEFULNESS = 1 << 1;
139 // Dirty bit: user activity was poked or may have timed out
140 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
141 // Dirty bit: actual display power state was updated asynchronously
142 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
143 // Dirty bit: mBootCompleted changed
144 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
145 // Dirty bit: settings changed
146 private static final int DIRTY_SETTINGS = 1 << 5;
147 // Dirty bit: mIsPowered changed
148 private static final int DIRTY_IS_POWERED = 1 << 6;
149 // Dirty bit: mStayOn changed
150 private static final int DIRTY_STAY_ON = 1 << 7;
151 // Dirty bit: battery state changed
152 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700153 // Dirty bit: proximity state changed
154 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownec6aa592012-10-17 20:30:25 -0700155 // Dirty bit: dock state changed
Jeff Brown3ee549c2014-09-22 20:14:39 -0700156 private static final int DIRTY_DOCK_STATE = 1 << 10;
Jeff Browne333e672014-10-28 13:48:55 -0700157 // Dirty bit: brightness boost changed
158 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800159 // Dirty bit: sQuiescent changed
160 private static final int DIRTY_QUIESCENT = 1 << 12;
Santos Cordon3107d292016-09-20 15:50:35 -0700161 // Dirty bit: VR Mode enabled changed
162 private static final int DIRTY_VR_MODE_CHANGED = 1 << 13;
Jeff Brown7304c342012-05-11 18:42:42 -0700163
Jeff Brown96307042012-07-27 15:51:34 -0700164 // Summarizes the state of all active wakelocks.
165 private static final int WAKE_LOCK_CPU = 1 << 0;
166 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
167 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
168 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
169 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700170 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800171 private static final int WAKE_LOCK_DOZE = 1 << 6;
Jeff Brownc2932a12014-11-20 18:04:05 -0800172 private static final int WAKE_LOCK_DRAW = 1 << 7;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
Jeff Brown96307042012-07-27 15:51:34 -0700174 // Summarizes the user activity state.
175 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
176 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700177 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
Jeff Brown27736f52014-05-20 17:17:10 -0700179 // Default timeout in milliseconds. This is only used until the settings
180 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700181 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700182 private static final int DEFAULT_SLEEP_TIMEOUT = -1;
Jeff Brownff532542012-10-02 21:18:04 -0700183
Jeff Browne333e672014-10-28 13:48:55 -0700184 // Screen brightness boost timeout.
185 // Hardcoded for now until we decide what the right policy should be.
186 // This should perhaps be a setting.
187 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
188
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700189 // How long a partial wake lock must be held until we consider it a long wake lock.
190 static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
191
Jason Monk27bbb2d2015-03-31 16:46:39 -0400192 // Power features defined in hardware/libhardware/include/hardware/power.h.
193 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1;
194
195 // Default setting for double tap to wake.
196 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
197
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800198 // System property indicating that the screen should remain off until an explicit user action
199 private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
200
Christine Franks732c0432017-06-23 18:12:46 -0700201 // System Property indicating that retail demo mode is currently enabled.
202 private static final String SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED = "sys.retaildemo.enabled";
203
Salvador Martineza6f7b252017-04-10 10:46:15 -0700204 // Possible reasons for shutting down for use in data/misc/reboot/last_shutdown_reason
205 private static final String REASON_SHUTDOWN = "shutdown";
206 private static final String REASON_REBOOT = "reboot";
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700207 private static final String REASON_USERREQUESTED = "shutdown,userrequested";
208 private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
Sudheer Shanka292637f2017-09-25 10:36:23 -0700209 private static final String REASON_LOW_BATTERY = "shutdown,battery";
210 private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700211
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -0700212 private static final String TRACE_SCREEN_ON = "Screen turning on";
213
214 /** If turning screen on takes more than this long, we show a warning on logcat. */
215 private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
216
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700217 /** Constants for {@link #shutdownOrRebootInternal} */
218 @Retention(RetentionPolicy.SOURCE)
219 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
220 public @interface HaltMode {}
221 private static final int HALT_MODE_SHUTDOWN = 0;
222 private static final int HALT_MODE_REBOOT = 1;
223 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
224
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700225 // Persistent property for last reboot reason
226 private static final String LAST_REBOOT_PROPERTY = "persist.sys.boot.reason";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700227
Jeff Brownb880d882014-02-10 19:47:07 -0800228 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700229 private final ServiceThread mHandlerThread;
230 private final PowerManagerHandler mHandler;
Adrian Roos56021892017-02-27 20:25:09 +0100231 private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
jackqdyulei455e90a2017-02-09 15:29:16 -0800232 private final BatterySaverPolicy mBatterySaverPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800233 private final BatterySaverController mBatterySaverController;
Jeff Brown2c43c332014-06-12 22:38:59 -0700234
Adam Lesinski182f73f2013-12-05 16:48:06 -0800235 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700236 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800237 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700238 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700239 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700240 private WindowManagerPolicy mPolicy;
241 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800242 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700243 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800244 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800245 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700246
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600247 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
Jeff Brown96307042012-07-27 15:51:34 -0700248
249 // A bitfield that indicates what parts of the power state have
250 // changed and need to be recalculated.
251 private int mDirty;
252
253 // Indicates whether the device is awake or asleep or somewhere in between.
254 // This is distinct from the screen power state, which is managed separately.
255 private int mWakefulness;
Jeff Brownfbe96702014-11-19 18:30:58 -0800256 private boolean mWakefulnessChanging;
Jeff Brown96307042012-07-27 15:51:34 -0700257
Jeff Brown26875502014-01-30 21:47:47 -0800258 // True if the sandman has just been summoned for the first time since entering the
259 // dreaming or dozing state. Indicates whether a new dream should begin.
260 private boolean mSandmanSummoned;
261
Jeff Brown96307042012-07-27 15:51:34 -0700262 // True if MSG_SANDMAN has been scheduled.
263 private boolean mSandmanScheduled;
264
265 // Table of all suspend blockers.
266 // There should only be a few of these.
267 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
268
269 // Table of all wake locks acquired by applications.
270 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
271
272 // A bitfield that summarizes the state of all active wakelocks.
273 private int mWakeLockSummary;
274
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700275 // Have we scheduled a message to check for long wake locks? This is when we will check.
276 private long mNotifyLongScheduled;
277
278 // Last time we checked for long wake locks.
279 private long mNotifyLongDispatched;
280
281 // The time we decided to do next long check.
282 private long mNotifyLongNextCheck;
283
Jeff Brown96307042012-07-27 15:51:34 -0700284 // If true, instructs the display controller to wait for the proximity sensor to
285 // go negative before turning the screen on.
286 private boolean mRequestWaitForNegativeProximity;
287
288 // Timestamp of the last time the device was awoken or put to sleep.
289 private long mLastWakeTime;
290 private long mLastSleepTime;
291
Jeff Brown96307042012-07-27 15:51:34 -0700292 // Timestamp of the last call to user activity.
293 private long mLastUserActivityTime;
294 private long mLastUserActivityTimeNoChangeLights;
295
Jeff Brown0a571122014-08-21 21:50:43 -0700296 // Timestamp of last interactive power hint.
297 private long mLastInteractivePowerHintTime;
298
Jeff Browne333e672014-10-28 13:48:55 -0700299 // Timestamp of the last screen brightness boost.
300 private long mLastScreenBrightnessBoostTime;
301 private boolean mScreenBrightnessBoostInProgress;
302
Jeff Brown96307042012-07-27 15:51:34 -0700303 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700304 private int mUserActivitySummary;
305
306 // The desired display power state. The actual state may lag behind the
307 // requested because it is updated asynchronously by the display power controller.
308 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
309
Jeff Brown96307042012-07-27 15:51:34 -0700310 // True if the display power state has been fully applied, which means the display
311 // is actually on or actually off or whatever was requested.
312 private boolean mDisplayReady;
313
Jeff Brown27f7a862012-12-12 15:43:31 -0800314 // The suspend blocker used to keep the CPU alive when an application has acquired
315 // a wake lock.
316 private final SuspendBlocker mWakeLockSuspendBlocker;
317
318 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700319 private boolean mHoldingWakeLockSuspendBlocker;
320
Jeff Brown27f7a862012-12-12 15:43:31 -0800321 // The suspend blocker used to keep the CPU alive when the display is on, the
322 // display is getting ready or there is user activity (in which case the display
323 // must be on).
324 private final SuspendBlocker mDisplaySuspendBlocker;
325
326 // True if the display suspend blocker has been acquired.
327 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700328
329 // True if systemReady() has been called.
330 private boolean mSystemReady;
331
332 // True if boot completed occurred. We keep the screen on until this happens.
333 private boolean mBootCompleted;
334
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700335 // Runnables that should be triggered on boot completed
336 private Runnable[] mBootCompletedRunnables;
337
Jeff Brown26875502014-01-30 21:47:47 -0800338 // True if auto-suspend mode is enabled.
339 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700340 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800341
342 // True if interactive mode is enabled.
343 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700344 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800345
Jeff Brown96307042012-07-27 15:51:34 -0700346 // True if the device is plugged into a power source.
347 private boolean mIsPowered;
348
Jeff Brownf3fb8952012-10-02 20:57:05 -0700349 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
350 private int mPlugType;
351
Jeff Brown016ff142012-10-15 16:47:22 -0700352 // The current battery level percentage.
353 private int mBatteryLevel;
354
355 // The battery level percentage at the time the dream started.
356 // This is used to terminate a dream and go to sleep if the battery is
357 // draining faster than it is charging and the user activity timeout has expired.
358 private int mBatteryLevelWhenDreamStarted;
359
Jeff Brownec6aa592012-10-17 20:30:25 -0700360 // The current dock state.
361 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
362
Jeff Brown26875502014-01-30 21:47:47 -0800363 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700364 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800365
366 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700367 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800368
Jeff Brown96307042012-07-27 15:51:34 -0700369 // True if the device should wake up when plugged or unplugged.
370 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
371
Bryce Lee584a4452014-10-21 15:55:55 -0700372 // True if the device should wake up when plugged or unplugged in theater mode.
373 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
374
Jeff Brownec083212013-09-11 20:45:25 -0700375 // True if the device should suspend when the screen is off due to proximity.
376 private boolean mSuspendWhenScreenOffDueToProximityConfig;
377
Jeff Brown96307042012-07-27 15:51:34 -0700378 // True if dreams are supported on this device.
379 private boolean mDreamsSupportedConfig;
380
John Spurlocked108f32012-10-18 16:49:24 -0400381 // Default value for dreams enabled
382 private boolean mDreamsEnabledByDefaultConfig;
383
384 // Default value for dreams activate-on-sleep
385 private boolean mDreamsActivatedOnSleepByDefaultConfig;
386
387 // Default value for dreams activate-on-dock
388 private boolean mDreamsActivatedOnDockByDefaultConfig;
389
Jeff Brown26875502014-01-30 21:47:47 -0800390 // True if dreams can run while not plugged in.
391 private boolean mDreamsEnabledOnBatteryConfig;
392
393 // Minimum battery level to allow dreaming when powered.
394 // Use -1 to disable this safety feature.
395 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
396
397 // Minimum battery level to allow dreaming when not powered.
398 // Use -1 to disable this safety feature.
399 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
400
401 // If the battery level drops by this percentage and the user activity timeout
402 // has expired, then assume the device is receiving insufficient current to charge
403 // effectively and terminate the dream. Use -1 to disable this safety feature.
404 private int mDreamsBatteryLevelDrainCutoffConfig;
405
Jeff Brown96307042012-07-27 15:51:34 -0700406 // True if dreams are enabled by the user.
407 private boolean mDreamsEnabledSetting;
408
John Spurlock1a868b72012-08-22 09:56:51 -0400409 // True if dreams should be activated on sleep.
410 private boolean mDreamsActivateOnSleepSetting;
411
Jeff Brownec6aa592012-10-17 20:30:25 -0700412 // True if dreams should be activated on dock.
413 private boolean mDreamsActivateOnDockSetting;
414
Jeff Brown2175e9c2014-09-12 16:11:07 -0700415 // True if doze should not be started until after the screen off transition.
416 private boolean mDozeAfterScreenOffConfig;
417
Jeff Brown27736f52014-05-20 17:17:10 -0700418 // The minimum screen off timeout, in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100419 private long mMinimumScreenOffTimeoutConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700420
421 // The screen dim duration, in milliseconds.
422 // This is subtracted from the end of the screen off timeout so the
423 // minimum screen off timeout should be longer than this.
Pavel Grafov28939982017-10-03 15:11:52 +0100424 private long mMaximumScreenDimDurationConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700425
426 // The maximum screen dim time expressed as a ratio relative to the screen
427 // off timeout. If the screen off timeout is very short then we want the
428 // dim timeout to also be quite short so that most of the time is spent on.
429 // Otherwise the user won't get much screen on time before dimming occurs.
430 private float mMaximumScreenDimRatioConfig;
431
Jason Monk27bbb2d2015-03-31 16:46:39 -0400432 // Whether device supports double tap to wake.
433 private boolean mSupportsDoubleTapWakeConfig;
434
Jeff Brown96307042012-07-27 15:51:34 -0700435 // The screen off timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100436 private long mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -0700437
Jeff Brown05af6ad2014-09-30 20:54:30 -0700438 // The sleep timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100439 private long mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700440
Jeff Brown96307042012-07-27 15:51:34 -0700441 // The maximum allowable screen off timeout according to the device
442 // administration policy. Overrides other settings.
Pavel Grafov28939982017-10-03 15:11:52 +0100443 private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
Jeff Brown96307042012-07-27 15:51:34 -0700444
445 // The stay on while plugged in setting.
446 // A bitfield of battery conditions under which to make the screen stay on.
447 private int mStayOnWhilePluggedInSetting;
448
449 // True if the device should stay on.
450 private boolean mStayOn;
451
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800452 // True if the lights should stay off until an explicit user action.
453 private static boolean sQuiescent;
454
Jeff Brown93cbbb22012-10-04 13:18:36 -0700455 // True if the proximity sensor reads a positive result.
456 private boolean mProximityPositive;
457
Jeff Brown96307042012-07-27 15:51:34 -0700458 // Screen brightness setting limits.
459 private int mScreenBrightnessSettingMinimum;
460 private int mScreenBrightnessSettingMaximum;
461 private int mScreenBrightnessSettingDefault;
462
463 // The screen brightness setting, from 0 to 255.
464 // Use -1 if no value has been set.
465 private int mScreenBrightnessSetting;
466
467 // The screen brightness mode.
468 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
469 private int mScreenBrightnessModeSetting;
470
471 // The screen brightness setting override from the window manager
472 // to allow the current foreground activity to override the brightness.
473 // Use -1 to disable.
474 private int mScreenBrightnessOverrideFromWindowManager = -1;
475
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -0700476 // The window manager has determined the user to be inactive via other means.
477 // Set this to false to disable.
478 private boolean mUserInactiveOverrideFromWindowManager;
479
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -0700480 // The next possible user activity timeout after being explicitly told the user is inactive.
481 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
482 private long mOverriddenTimeout = -1;
483
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700484 // The user activity timeout override from the window manager
485 // to allow the current foreground activity to override the user activity timeout.
486 // Use -1 to disable.
487 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
488
Jeff Brown970d4132014-07-19 11:33:47 -0700489 // The screen state to use while dozing.
490 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
491
492 // The screen brightness to use while dozing.
493 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
494
Jeff Brown9ba8d782012-10-01 16:38:23 -0700495 // Time when we last logged a warning about calling userActivity() without permission.
496 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
497
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700498 // If true, the device is in low power mode.
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700499 private boolean mLowPowerModeEnabled;
500
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700501 // Current state of the low power mode setting.
502 private boolean mLowPowerModeSetting;
503
Dianne Hackborn14272302014-06-10 23:13:02 -0700504 // Current state of whether the settings are allowing auto low power mode.
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400505 private boolean mAutoLowPowerModeConfigured;
Dianne Hackborn14272302014-06-10 23:13:02 -0700506
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400507 // The user turned off low power mode below the trigger level
John Spurlock1bb480a2014-08-02 17:12:43 -0400508 private boolean mAutoLowPowerModeSnoozing;
509
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700510 // True if the battery level is currently considered low.
511 private boolean mBatteryLevelLow;
512
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700513 // True if we are currently in device idle mode.
514 private boolean mDeviceIdleMode;
515
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700516 // True if we are currently in light device idle mode.
517 private boolean mLightDeviceIdleMode;
518
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700519 // Set of app ids that we will always respect the wake locks for.
520 int[] mDeviceIdleWhitelist = new int[0];
521
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700522 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
523 int[] mDeviceIdleTempWhitelist = new int[0];
524
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -0700525 private final SparseArray<UidState> mUidState = new SparseArray<>();
526
527 // We are currently in the middle of a batch change of uids.
528 private boolean mUidsChanging;
529
530 // Some uids have actually changed while mUidsChanging was true.
531 private boolean mUidsChanged;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700532
Bryce Lee584a4452014-10-21 15:55:55 -0700533 // True if theater mode is enabled
534 private boolean mTheaterModeEnabled;
535
Adrian Roos56021892017-02-27 20:25:09 +0100536 // True if always on display is enabled
537 private boolean mAlwaysOnEnabled;
538
Jason Monk27bbb2d2015-03-31 16:46:39 -0400539 // True if double tap to wake is enabled
540 private boolean mDoubleTapWakeEnabled;
541
Santos Cordon3107d292016-09-20 15:50:35 -0700542 // True if we are currently in VR Mode.
543 private boolean mIsVrModeEnabled;
544
Pavel Grafov28939982017-10-03 15:11:52 +0100545 private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
546 @Override
547 public void onUserSwitching(int newUserId) throws RemoteException {}
548
549 @Override
550 public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
551 final long now = SystemClock.uptimeMillis();
552 synchronized(mLock) {
553 mForegroundProfile = newProfileId;
554 maybeUpdateForegroundProfileLastActivityLocked(now);
555 }
556 }
557 }
558
559 // User id corresponding to activity the user is currently interacting with.
560 private @UserIdInt int mForegroundProfile;
561
562 // Per-profile state to track when a profile should be locked.
563 private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
564
565 private static final class ProfilePowerState {
566 // Profile user id.
567 final @UserIdInt int mUserId;
568 // Maximum time to lock set by admin.
569 long mScreenOffTimeout;
570 // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
571 int mWakeLockSummary;
572 // Last user activity that happened in an app running in the profile.
573 long mLastUserActivityTime;
574 // Whether profile has been locked last time it timed out.
575 boolean mLockingNotified;
576
577 public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout) {
578 mUserId = userId;
579 mScreenOffTimeout = screenOffTimeout;
580 // Not accurate but at least won't cause immediate locking of the profile.
581 mLastUserActivityTime = SystemClock.uptimeMillis();
582 }
583 }
584
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800585 /**
586 * All times are in milliseconds. These constants are kept synchronized with the system
587 * global Settings. Any access to this class or its fields should be done while
588 * holding the PowerManagerService.mLock lock.
589 */
590 private final class Constants extends ContentObserver {
591 // Key names stored in the settings value.
592 private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
593
594 private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
595
596 // Prevent processes that are cached from holding wake locks?
597 public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
598
599 private ContentResolver mResolver;
600 private final KeyValueListParser mParser = new KeyValueListParser(',');
601
602 public Constants(Handler handler) {
603 super(handler);
604 }
605
606 public void start(ContentResolver resolver) {
607 mResolver = resolver;
608 mResolver.registerContentObserver(Settings.Global.getUriFor(
609 Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
610 updateConstants();
611 }
612
613 @Override
614 public void onChange(boolean selfChange, Uri uri) {
615 updateConstants();
616 }
617
618 private void updateConstants() {
619 synchronized (mLock) {
620 try {
621 mParser.setString(Settings.Global.getString(mResolver,
622 Settings.Global.POWER_MANAGER_CONSTANTS));
623 } catch (IllegalArgumentException e) {
624 // Failed to parse the settings string, log this and move on
625 // with defaults.
626 Slog.e(TAG, "Bad alarm manager settings", e);
627 }
628
629 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
630 DEFAULT_NO_CACHED_WAKE_LOCKS);
631 }
632 }
633
634 void dump(PrintWriter pw) {
635 pw.println(" Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
636
637 pw.print(" "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
638 pw.println(NO_CACHED_WAKE_LOCKS);
639 }
Netta P958d0a52017-02-07 11:20:55 -0800640
641 void dumpProto(ProtoOutputStream proto) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700642 final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
643 proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
Netta P958d0a52017-02-07 11:20:55 -0800644 NO_CACHED_WAKE_LOCKS);
645 proto.end(constantsToken);
646 }
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800647 }
648
649 final Constants mConstants;
650
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700651 private native void nativeInit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652
Jeff Brown96307042012-07-27 15:51:34 -0700653 private static native void nativeAcquireSuspendBlocker(String name);
654 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700655 private static native void nativeSetInteractive(boolean enable);
656 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700657 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400658 private static native void nativeSetFeature(int featureId, int data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659
Jeff Brownb880d882014-02-10 19:47:07 -0800660 public PowerManagerService(Context context) {
661 super(context);
662 mContext = context;
Jeff Brown2c43c332014-06-12 22:38:59 -0700663 mHandlerThread = new ServiceThread(TAG,
664 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
665 mHandlerThread.start();
666 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800667 mConstants = new Constants(mHandler);
Adrian Roos56021892017-02-27 20:25:09 +0100668 mAmbientDisplayConfiguration = new AmbientDisplayConfiguration(mContext);
Makoto Onuki66a78122017-11-14 15:03:21 -0800669
jackqdyulei455e90a2017-02-09 15:29:16 -0800670 mBatterySaverPolicy = new BatterySaverPolicy(mHandler);
Makoto Onuki66a78122017-11-14 15:03:21 -0800671 mBatterySaverController = new BatterySaverController(mContext,
672 BackgroundThread.get().getLooper(), mBatterySaverPolicy);
Jeff Brown2c43c332014-06-12 22:38:59 -0700673
Jeff Brown96307042012-07-27 15:51:34 -0700674 synchronized (mLock) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800675 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
676 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
677 mDisplaySuspendBlocker.acquire();
678 mHoldingDisplaySuspendBlocker = true;
Jeff Brown037c33e2014-04-09 00:31:55 -0700679 mHalAutoSuspendModeEnabled = false;
680 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800681
Jeff Brown96307042012-07-27 15:51:34 -0700682 mWakefulness = WAKEFULNESS_AWAKE;
Jeff Brown7304c342012-05-11 18:42:42 -0700683
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800684 sQuiescent = SystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
685
Jeff Brown037c33e2014-04-09 00:31:55 -0700686 nativeInit();
687 nativeSetAutoSuspend(false);
688 nativeSetInteractive(true);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400689 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 }
692
jackqdyulei92681e82017-02-28 11:26:28 -0800693 @VisibleForTesting
694 PowerManagerService(Context context, BatterySaverPolicy batterySaverPolicy) {
695 super(context);
696
jackqdyulei92681e82017-02-28 11:26:28 -0800697 mContext = context;
698 mHandlerThread = new ServiceThread(TAG,
699 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
700 mHandlerThread.start();
701 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
702 mConstants = new Constants(mHandler);
Adrian Roos56021892017-02-27 20:25:09 +0100703 mAmbientDisplayConfiguration = new AmbientDisplayConfiguration(mContext);
jackqdyulei92681e82017-02-28 11:26:28 -0800704 mDisplaySuspendBlocker = null;
705 mWakeLockSuspendBlocker = null;
Makoto Onuki66a78122017-11-14 15:03:21 -0800706
707 mBatterySaverPolicy = batterySaverPolicy;
708 mBatterySaverController = new BatterySaverController(context,
709 BackgroundThread.getHandler().getLooper(), batterySaverPolicy);
jackqdyulei92681e82017-02-28 11:26:28 -0800710 }
711
Jeff Brown6f357d32014-01-15 20:40:55 -0800712 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800713 public void onStart() {
714 publishBinderService(Context.POWER_SERVICE, new BinderService());
715 publishLocalService(PowerManagerInternal.class, new LocalService());
Jeff Brown9e316a12012-10-08 19:17:06 -0700716
717 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800718 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700719 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800720
Jeff Brown6d2a9492014-08-07 19:06:49 -0700721 @Override
722 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700723 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600724 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
725 incrementBootCount();
726
727 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700728 final long now = SystemClock.uptimeMillis();
729 mBootCompleted = true;
730 mDirty |= DIRTY_BOOT_COMPLETED;
731 userActivityNoUpdateLocked(
732 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
733 updatePowerStateLocked();
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700734
735 if (!ArrayUtils.isEmpty(mBootCompletedRunnables)) {
736 Slog.d(TAG, "Posting " + mBootCompletedRunnables.length + " delayed runnables");
737 for (Runnable r : mBootCompletedRunnables) {
738 BackgroundThread.getHandler().post(r);
739 }
740 }
741 mBootCompletedRunnables = null;
Craig Mautner6e2f3952014-09-09 14:26:41 -0700742 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700743 }
744 }
745
Jeff Brown21392762014-06-13 19:00:36 -0700746 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700747 synchronized (mLock) {
748 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700749 mAppOps = appOps;
750 mDreamManager = getLocalService(DreamManagerInternal.class);
751 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
752 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700753 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754
Adam Lesinski182f73f2013-12-05 16:48:06 -0800755 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700756 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
757 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
758 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700760 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800761
Jeff Brownc38c9be2012-10-04 13:16:19 -0700762 // The notifier runs on the system server's main looper so as not to interfere
763 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700764 mBatteryStats = BatteryStatsService.getService();
Jeff Brownc38c9be2012-10-04 13:16:19 -0700765 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
Dianne Hackborn713df152013-05-17 11:27:57 -0700766 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
Jeff Brown3ee549c2014-09-22 20:14:39 -0700767 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700768
Jeff Brown3b971592013-01-09 18:46:37 -0800769 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
Jeff Browndbcc8a22013-10-01 16:16:44 -0700770 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
771 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700772 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700773
774 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800775 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400776
Jeff Brown131206b2014-04-08 17:27:14 -0700777 // Initialize display power management.
778 mDisplayManagerInternal.initPowerManagement(
779 mDisplayPowerCallbacks, mHandler, sensorManager);
780
Pavel Grafov28939982017-10-03 15:11:52 +0100781 try {
782 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
783 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
784 } catch (RemoteException e) {
785 // Shouldn't happen since in-process.
786 }
Makoto Onuki66a78122017-11-14 15:03:21 -0800787
Jeff Brown96307042012-07-27 15:51:34 -0700788 // Go.
789 readConfigurationLocked();
790 updateSettingsLocked();
791 mDirty |= DIRTY_BATTERY_STATE;
792 updatePowerStateLocked();
793 }
Shibin George43f5de02016-07-06 02:12:10 +0530794
Jeff Sharkey6e544612017-02-20 11:02:26 -0700795 final ContentResolver resolver = mContext.getContentResolver();
796 mConstants.start(resolver);
Makoto Onuki66a78122017-11-14 15:03:21 -0800797
798 mBatterySaverController.systemReady();
799 mBatterySaverPolicy.systemReady(mContext);
Jeff Sharkey6e544612017-02-20 11:02:26 -0700800
801 // Register for settings changes.
802 resolver.registerContentObserver(Settings.Secure.getUriFor(
803 Settings.Secure.SCREENSAVER_ENABLED),
804 false, mSettingsObserver, UserHandle.USER_ALL);
805 resolver.registerContentObserver(Settings.Secure.getUriFor(
806 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
807 false, mSettingsObserver, UserHandle.USER_ALL);
808 resolver.registerContentObserver(Settings.Secure.getUriFor(
809 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
810 false, mSettingsObserver, UserHandle.USER_ALL);
811 resolver.registerContentObserver(Settings.System.getUriFor(
812 Settings.System.SCREEN_OFF_TIMEOUT),
813 false, mSettingsObserver, UserHandle.USER_ALL);
814 resolver.registerContentObserver(Settings.Secure.getUriFor(
815 Settings.Secure.SLEEP_TIMEOUT),
816 false, mSettingsObserver, UserHandle.USER_ALL);
817 resolver.registerContentObserver(Settings.Global.getUriFor(
818 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
819 false, mSettingsObserver, UserHandle.USER_ALL);
820 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700821 Settings.System.SCREEN_BRIGHTNESS_MODE),
822 false, mSettingsObserver, UserHandle.USER_ALL);
823 resolver.registerContentObserver(Settings.System.getUriFor(
824 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
825 false, mSettingsObserver, UserHandle.USER_ALL);
826 resolver.registerContentObserver(Settings.Global.getUriFor(
827 Settings.Global.LOW_POWER_MODE),
828 false, mSettingsObserver, UserHandle.USER_ALL);
829 resolver.registerContentObserver(Settings.Global.getUriFor(
830 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
831 false, mSettingsObserver, UserHandle.USER_ALL);
832 resolver.registerContentObserver(Settings.Global.getUriFor(
833 Settings.Global.THEATER_MODE_ON),
834 false, mSettingsObserver, UserHandle.USER_ALL);
835 resolver.registerContentObserver(Settings.Secure.getUriFor(
Adrian Roos56021892017-02-27 20:25:09 +0100836 Settings.Secure.DOZE_ALWAYS_ON),
837 false, mSettingsObserver, UserHandle.USER_ALL);
838 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700839 Settings.Secure.DOUBLE_TAP_TO_WAKE),
840 false, mSettingsObserver, UserHandle.USER_ALL);
Christine Franks732c0432017-06-23 18:12:46 -0700841 resolver.registerContentObserver(Settings.Global.getUriFor(
842 Settings.Global.DEVICE_DEMO_MODE),
843 false, mSettingsObserver, UserHandle.USER_SYSTEM);
Jeff Sharkey6e544612017-02-20 11:02:26 -0700844 IVrManager vrManager = (IVrManager) getBinderService(Context.VR_SERVICE);
845 if (vrManager != null) {
846 try {
847 vrManager.registerListener(mVrStateCallbacks);
848 } catch (RemoteException e) {
849 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
850 }
851 }
852
Shibin George43f5de02016-07-06 02:12:10 +0530853 // Register for broadcasts from other components of the system.
854 IntentFilter filter = new IntentFilter();
855 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
856 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
857 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
858
859 filter = new IntentFilter();
860 filter.addAction(Intent.ACTION_DREAMING_STARTED);
861 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
862 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
863
864 filter = new IntentFilter();
865 filter.addAction(Intent.ACTION_USER_SWITCHED);
866 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
867
868 filter = new IntentFilter();
869 filter.addAction(Intent.ACTION_DOCK_EVENT);
870 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700871 }
872
873 private void readConfigurationLocked() {
874 final Resources resources = mContext.getResources();
875
Jeff Brown037c33e2014-04-09 00:31:55 -0700876 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800877 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700878 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800879 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700880 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700881 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700882 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
883 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700884 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
885 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700886 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400887 com.android.internal.R.bool.config_dreamsSupported);
888 mDreamsEnabledByDefaultConfig = resources.getBoolean(
889 com.android.internal.R.bool.config_dreamsEnabledByDefault);
890 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
891 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
892 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
893 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800894 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
895 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
896 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
897 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
898 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
899 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
900 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
901 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Jeff Brown2175e9c2014-09-12 16:11:07 -0700902 mDozeAfterScreenOffConfig = resources.getBoolean(
903 com.android.internal.R.bool.config_dozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -0700904 mMinimumScreenOffTimeoutConfig = resources.getInteger(
905 com.android.internal.R.integer.config_minimumScreenOffTimeout);
906 mMaximumScreenDimDurationConfig = resources.getInteger(
907 com.android.internal.R.integer.config_maximumScreenDimDuration);
908 mMaximumScreenDimRatioConfig = resources.getFraction(
909 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400910 mSupportsDoubleTapWakeConfig = resources.getBoolean(
911 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
913
Jeff Brown96307042012-07-27 15:51:34 -0700914 private void updateSettingsLocked() {
915 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700916
Jeff Brownd4935962012-09-25 13:27:20 -0700917 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400918 Settings.Secure.SCREENSAVER_ENABLED,
919 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700920 UserHandle.USER_CURRENT) != 0);
921 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400922 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
923 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700924 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700925 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400926 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
927 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -0700928 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -0700929 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
930 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
931 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -0700932 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
933 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
934 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -0700935 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -0700936 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -0700937 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
938 Settings.Global.THEATER_MODE_ON, 0) == 1;
Adrian Roos56021892017-02-27 20:25:09 +0100939 mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
Jeff Brown7304c342012-05-11 18:42:42 -0700940
Jason Monk27bbb2d2015-03-31 16:46:39 -0400941 if (mSupportsDoubleTapWakeConfig) {
942 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
943 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
944 UserHandle.USER_CURRENT) != 0;
945 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
946 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
947 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
948 }
949 }
950
Christine Franks732c0432017-06-23 18:12:46 -0700951 final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
952 if (!retailDemoValue.equals(SystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED))) {
953 SystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
954 }
955
Jeff Brownd4935962012-09-25 13:27:20 -0700956 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -0700957 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -0700958 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700959
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700960 final boolean lowPowerModeEnabled = Settings.Global.getInt(resolver,
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700961 Settings.Global.LOW_POWER_MODE, 0) != 0;
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400962 final boolean autoLowPowerModeConfigured = Settings.Global.getInt(resolver,
John Spurlock1bb480a2014-08-02 17:12:43 -0400963 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0) != 0;
Dianne Hackborn14272302014-06-10 23:13:02 -0700964 if (lowPowerModeEnabled != mLowPowerModeSetting
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400965 || autoLowPowerModeConfigured != mAutoLowPowerModeConfigured) {
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700966 mLowPowerModeSetting = lowPowerModeEnabled;
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400967 mAutoLowPowerModeConfigured = autoLowPowerModeConfigured;
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700968 updateLowPowerModeLocked();
969 }
970
971 mDirty |= DIRTY_SETTINGS;
972 }
973
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700974 private void postAfterBootCompleted(Runnable r) {
975 if (mBootCompleted) {
976 BackgroundThread.getHandler().post(r);
977 } else {
978 Slog.d(TAG, "Delaying runnable until system is booted");
979 mBootCompletedRunnables = ArrayUtils.appendElement(Runnable.class,
980 mBootCompletedRunnables, r);
981 }
982 }
983
Daichi Hirono82ab9802016-03-02 13:23:29 +0900984 private void updateLowPowerModeLocked() {
Michael Wright2763c2b2016-08-11 15:45:49 +0100985 if ((mIsPowered || !mBatteryLevelLow && !mBootCompleted) && mLowPowerModeSetting) {
John Spurlock1bb480a2014-08-02 17:12:43 -0400986 if (DEBUG_SPEW) {
Michael Wright2763c2b2016-08-11 15:45:49 +0100987 Slog.d(TAG, "updateLowPowerModeLocked: powered or booting with sufficient battery,"
988 + " turning setting off");
John Spurlock1bb480a2014-08-02 17:12:43 -0400989 }
990 // Turn setting off if powered
991 Settings.Global.putInt(mContext.getContentResolver(),
992 Settings.Global.LOW_POWER_MODE, 0);
993 mLowPowerModeSetting = false;
John Spurlock1bb480a2014-08-02 17:12:43 -0400994 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400995 final boolean autoLowPowerModeEnabled = !mIsPowered && mAutoLowPowerModeConfigured
996 && !mAutoLowPowerModeSnoozing && mBatteryLevelLow;
997 final boolean lowPowerModeEnabled = mLowPowerModeSetting || autoLowPowerModeEnabled;
998
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700999 if (mLowPowerModeEnabled != lowPowerModeEnabled) {
1000 mLowPowerModeEnabled = lowPowerModeEnabled;
Makoto Onukiaae89532017-11-08 14:32:03 -08001001
Makoto Onuki66a78122017-11-14 15:03:21 -08001002 postAfterBootCompleted(() ->
1003 mBatterySaverController.enableBatterySaver(mLowPowerModeEnabled));
Ruchi Kandoi62b8a492014-04-17 18:01:40 -07001004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
1006
Jeff Brown96307042012-07-27 15:51:34 -07001007 private void handleSettingsChangedLocked() {
1008 updateSettingsLocked();
1009 updatePowerStateLocked();
1010 }
1011
Dianne Hackborn713df152013-05-17 11:27:57 -07001012 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001013 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -07001014 synchronized (mLock) {
1015 if (DEBUG_SPEW) {
1016 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1017 + ", flags=0x" + Integer.toHexString(flags)
1018 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020
Jeff Brown96307042012-07-27 15:51:34 -07001021 WakeLock wakeLock;
1022 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001023 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -07001024 if (index >= 0) {
1025 wakeLock = mWakeLocks.get(index);
1026 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
1027 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001028 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1029 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001030 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001032 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 } else {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001034 UidState state = mUidState.get(uid);
1035 if (state == null) {
1036 state = new UidState(uid);
1037 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1038 mUidState.put(uid, state);
1039 }
1040 state.mNumWakeLocks++;
1041 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
1042 state);
Jeff Brown96307042012-07-27 15:51:34 -07001043 try {
1044 lock.linkToDeath(wakeLock, 0);
1045 } catch (RemoteException ex) {
1046 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
Jeff Brown96307042012-07-27 15:51:34 -07001048 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001049 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001050 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052
Jeff Brownc12035c2014-08-13 18:52:25 -07001053 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001054 mDirty |= DIRTY_WAKE_LOCKS;
1055 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001056 if (notifyAcquire) {
1057 // This needs to be done last so we are sure we have acquired the
1058 // kernel wake lock. Otherwise we have a race where the system may
1059 // go to sleep between the time we start the accounting in battery
1060 // stats and when we actually get around to telling the kernel to
1061 // stay awake.
1062 notifyWakeLockAcquiredLocked(wakeLock);
1063 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001064 }
1065 }
1066
Jeff Brownec083212013-09-11 20:45:25 -07001067 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -08001068 private static boolean isScreenLock(final WakeLock wakeLock) {
1069 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1070 case PowerManager.FULL_WAKE_LOCK:
1071 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1072 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1073 return true;
1074 }
1075 return false;
1076 }
1077
Jeff Brownc12035c2014-08-13 18:52:25 -07001078 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -07001079 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1080 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001081 String opPackageName;
1082 int opUid;
1083 if (wakeLock.mWorkSource != null && wakeLock.mWorkSource.getName(0) != null) {
1084 opPackageName = wakeLock.mWorkSource.getName(0);
1085 opUid = wakeLock.mWorkSource.get(0);
1086 } else {
1087 opPackageName = wakeLock.mPackageName;
1088 opUid = wakeLock.mWorkSource != null ? wakeLock.mWorkSource.get(0)
1089 : wakeLock.mOwnerUid;
1090 }
1091 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), wakeLock.mTag, opUid,
1092 opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
1094 }
1095
Jeff Brown96307042012-07-27 15:51:34 -07001096 private void releaseWakeLockInternal(IBinder lock, int flags) {
1097 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -07001098 int index = findWakeLockIndexLocked(lock);
1099 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001100 if (DEBUG_SPEW) {
1101 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1102 + " [not found], flags=0x" + Integer.toHexString(flags));
1103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 return;
1105 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001106
Jeff Brown96307042012-07-27 15:51:34 -07001107 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001108 if (DEBUG_SPEW) {
1109 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1110 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1111 }
1112
Michael Wright1208e272014-09-08 19:57:50 -07001113 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001114 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116
Jeff Brown3edf5272014-08-14 19:25:14 -07001117 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1118 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 }
1120 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001121
Jeff Brown96307042012-07-27 15:51:34 -07001122 private void handleWakeLockDeath(WakeLock wakeLock) {
1123 synchronized (mLock) {
1124 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001125 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1126 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -07001127 }
1128
1129 int index = mWakeLocks.indexOf(wakeLock);
1130 if (index < 0) {
1131 return;
1132 }
1133
Jeff Brown3edf5272014-08-14 19:25:14 -07001134 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001135 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001136 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001137
Jeff Brown3edf5272014-08-14 19:25:14 -07001138 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1139 mWakeLocks.remove(index);
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001140 UidState state = wakeLock.mUidState;
1141 state.mNumWakeLocks--;
1142 if (state.mNumWakeLocks <= 0 &&
1143 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1144 mUidState.remove(state.mUid);
1145 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001146 notifyWakeLockReleasedLocked(wakeLock);
1147
1148 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1149 mDirty |= DIRTY_WAKE_LOCKS;
1150 updatePowerStateLocked();
1151 }
1152
Jeff Brown96307042012-07-27 15:51:34 -07001153 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001154 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1155 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001156 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1157 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1158 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1159 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 }
1162
Dianne Hackbornd953c532014-08-16 18:17:38 -07001163 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1164 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001165 synchronized (mLock) {
1166 int index = findWakeLockIndexLocked(lock);
1167 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001168 if (DEBUG_SPEW) {
1169 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1170 + " [not found], ws=" + ws);
1171 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001172 throw new IllegalArgumentException("Wake lock not active: " + lock
1173 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001174 }
1175
1176 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001177 if (DEBUG_SPEW) {
1178 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1179 + " [" + wakeLock.mTag + "], ws=" + ws);
1180 }
1181
Jeff Brown96307042012-07-27 15:51:34 -07001182 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001183 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1184 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001185 ws, historyTag);
1186 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001187 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001188 }
1189 }
1190 }
1191
1192 private int findWakeLockIndexLocked(IBinder lock) {
1193 final int count = mWakeLocks.size();
1194 for (int i = 0; i < count; i++) {
1195 if (mWakeLocks.get(i).mLock == lock) {
1196 return i;
1197 }
1198 }
1199 return -1;
1200 }
1201
1202 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001203 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001204 wakeLock.mNotifiedAcquired = true;
1205 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001206 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1207 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001208 restartNofifyLongTimerLocked(wakeLock);
1209 }
1210 }
1211
1212 private void enqueueNotifyLongMsgLocked(long time) {
1213 mNotifyLongScheduled = time;
1214 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1215 msg.setAsynchronous(true);
1216 mHandler.sendMessageAtTime(msg, time);
1217 }
1218
1219 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1220 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1221 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1222 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1223 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1224 }
1225 }
1226
1227 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1228 if (mSystemReady && !wakeLock.mDisabled) {
1229 wakeLock.mNotifiedLong = true;
1230 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1231 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1232 }
1233 }
1234
1235 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1236 if (wakeLock.mNotifiedLong) {
1237 wakeLock.mNotifiedLong = false;
1238 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1239 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001240 }
1241 }
1242
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001243 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1244 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1245 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1246 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1247 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1248 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001249 notifyWakeLockLongFinishedLocked(wakeLock);
1250 // Changing the wake lock will count as releasing the old wake lock(s) and
1251 // acquiring the new ones... we do this because otherwise once a wakelock
1252 // becomes long, if we just continued to treat it as long we can get in to
1253 // situations where we spam battery stats with every following change to it.
1254 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001255 }
1256 }
1257
Jeff Brown96307042012-07-27 15:51:34 -07001258 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001259 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1260 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001261 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001262 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1263 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1264 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001265 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001266 }
1267 }
1268
Jeff Brownec083212013-09-11 20:45:25 -07001269 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001270 private boolean isWakeLockLevelSupportedInternal(int level) {
1271 synchronized (mLock) {
1272 switch (level) {
1273 case PowerManager.PARTIAL_WAKE_LOCK:
1274 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1275 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1276 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001277 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001278 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001279 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001280
1281 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001282 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001283
1284 default:
1285 return false;
1286 }
1287 }
1288 }
1289
Jeff Brown96307042012-07-27 15:51:34 -07001290 // Called from native code.
1291 private void userActivityFromNative(long eventTime, int event, int flags) {
1292 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1293 }
1294
1295 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1296 synchronized (mLock) {
1297 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1298 updatePowerStateLocked();
1299 }
1300 }
1301 }
1302
1303 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1304 if (DEBUG_SPEW) {
1305 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1306 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1307 + ", uid=" + uid);
1308 }
1309
1310 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -08001311 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001312 return false;
1313 }
1314
Jeff Brown3edf5272014-08-14 19:25:14 -07001315 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1316 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001317 if (eventTime > mLastInteractivePowerHintTime) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07001318 powerHintInternal(PowerHint.INTERACTION, 0);
Jeff Brown0a571122014-08-21 21:50:43 -07001319 mLastInteractivePowerHintTime = eventTime;
1320 }
1321
Jeff Brown3edf5272014-08-14 19:25:14 -07001322 mNotifier.onUserActivity(event, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001323
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001324 if (mUserInactiveOverrideFromWindowManager) {
1325 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001326 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001327 }
1328
Jeff Brown0a571122014-08-21 21:50:43 -07001329 if (mWakefulness == WAKEFULNESS_ASLEEP
1330 || mWakefulness == WAKEFULNESS_DOZING
1331 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1332 return false;
1333 }
1334
Pavel Grafov28939982017-10-03 15:11:52 +01001335 maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1336
Jeff Brown3edf5272014-08-14 19:25:14 -07001337 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1338 if (eventTime > mLastUserActivityTimeNoChangeLights
1339 && eventTime > mLastUserActivityTime) {
1340 mLastUserActivityTimeNoChangeLights = eventTime;
1341 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001342 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1343 mDirty |= DIRTY_QUIESCENT;
1344 }
1345
Jeff Brown3edf5272014-08-14 19:25:14 -07001346 return true;
1347 }
1348 } else {
1349 if (eventTime > mLastUserActivityTime) {
1350 mLastUserActivityTime = eventTime;
1351 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001352 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1353 mDirty |= DIRTY_QUIESCENT;
1354 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001355 return true;
1356 }
Jeff Brown96307042012-07-27 15:51:34 -07001357 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001358 } finally {
1359 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001360 }
1361 return false;
1362 }
1363
Pavel Grafov28939982017-10-03 15:11:52 +01001364 private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1365 final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1366 if (profile != null && eventTime > profile.mLastUserActivityTime) {
1367 profile.mLastUserActivityTime = eventTime;
1368 }
1369 }
1370
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001371 private void wakeUpInternal(long eventTime, String reason, int uid, String opPackageName,
1372 int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001373 synchronized (mLock) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001374 if (wakeUpNoUpdateLocked(eventTime, reason, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001375 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001376 }
1377 }
Jeff Brown96307042012-07-27 15:51:34 -07001378 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001379
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001380 private boolean wakeUpNoUpdateLocked(long eventTime, String reason, int reasonUid,
1381 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001382 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001383 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001384 }
Jeff Brown96307042012-07-27 15:51:34 -07001385
1386 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
1387 || !mBootCompleted || !mSystemReady) {
1388 return false;
1389 }
1390
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001391 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1392
Jeff Brown3edf5272014-08-14 19:25:14 -07001393 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1394 try {
1395 switch (mWakefulness) {
1396 case WAKEFULNESS_ASLEEP:
Adrian Roos7ac5a0b2017-05-17 14:23:54 -07001397 Slog.i(TAG, "Waking up from sleep (uid=" + reasonUid + " reason=" + reason
1398 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001399 break;
1400 case WAKEFULNESS_DREAMING:
Adrian Roos7ac5a0b2017-05-17 14:23:54 -07001401 Slog.i(TAG, "Waking up from dream (uid=" + reasonUid + " reason=" + reason
1402 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001403 break;
1404 case WAKEFULNESS_DOZING:
Adrian Roos7ac5a0b2017-05-17 14:23:54 -07001405 Slog.i(TAG, "Waking up from dozing (uid=" + reasonUid + " reason=" + reason
1406 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001407 break;
1408 }
1409
1410 mLastWakeTime = eventTime;
Jeff Brownfbe96702014-11-19 18:30:58 -08001411 setWakefulnessLocked(WAKEFULNESS_AWAKE, 0);
Jeff Brown3edf5272014-08-14 19:25:14 -07001412
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001413 mNotifier.onWakeUp(reason, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001414 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001415 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001416 } finally {
1417 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001418 }
Jeff Brown96307042012-07-27 15:51:34 -07001419 return true;
1420 }
1421
Jeff Brownc12035c2014-08-13 18:52:25 -07001422 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001423 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001424 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001425 updatePowerStateLocked();
1426 }
1427 }
1428 }
1429
Jeff Brown26875502014-01-30 21:47:47 -08001430 // This method is called goToSleep for historical reasons but we actually start
1431 // dozing before really going to sleep.
Jeff Brownec083212013-09-11 20:45:25 -07001432 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001433 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001434 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001435 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001436 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001437 }
1438
Jeff Brown26875502014-01-30 21:47:47 -08001439 if (eventTime < mLastWakeTime
1440 || mWakefulness == WAKEFULNESS_ASLEEP
1441 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001442 || !mBootCompleted || !mSystemReady) {
1443 return false;
1444 }
1445
Jeff Brown3edf5272014-08-14 19:25:14 -07001446 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1447 try {
1448 switch (reason) {
1449 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
1450 Slog.i(TAG, "Going to sleep due to device administration policy "
1451 + "(uid " + uid +")...");
1452 break;
1453 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
1454 Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")...");
1455 break;
1456 case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH:
1457 Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")...");
1458 break;
1459 case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON:
1460 Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")...");
1461 break;
Filip Gruszczynski9779e122015-03-13 17:39:31 -07001462 case PowerManager.GO_TO_SLEEP_REASON_SLEEP_BUTTON:
1463 Slog.i(TAG, "Going to sleep due to sleep button (uid " + uid +")...");
1464 break;
Jeff Brown3edf5272014-08-14 19:25:14 -07001465 case PowerManager.GO_TO_SLEEP_REASON_HDMI:
1466 Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")...");
1467 break;
Eugene Suslaf9a651d2017-10-11 12:06:27 -07001468 case PowerManager.GO_TO_SLEEP_REASON_ACCESSIBILITY:
1469 Slog.i(TAG, "Going to sleep by an accessibility service request (uid "
1470 + uid +")...");
1471 break;
Jeff Brown3edf5272014-08-14 19:25:14 -07001472 default:
1473 Slog.i(TAG, "Going to sleep by application request (uid " + uid +")...");
1474 reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION;
Jeff Brown96307042012-07-27 15:51:34 -07001475 break;
1476 }
Jeff Brown6d8fd272014-05-20 21:24:38 -07001477
Jeff Brown3edf5272014-08-14 19:25:14 -07001478 mLastSleepTime = eventTime;
Jeff Brown3edf5272014-08-14 19:25:14 -07001479 mSandmanSummoned = true;
Jeff Brownfbe96702014-11-19 18:30:58 -08001480 setWakefulnessLocked(WAKEFULNESS_DOZING, reason);
Jeff Brown3edf5272014-08-14 19:25:14 -07001481
1482 // Report the number of wake locks that will be cleared by going to sleep.
1483 int numWakeLocksCleared = 0;
1484 final int numWakeLocks = mWakeLocks.size();
1485 for (int i = 0; i < numWakeLocks; i++) {
1486 final WakeLock wakeLock = mWakeLocks.get(i);
1487 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1488 case PowerManager.FULL_WAKE_LOCK:
1489 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1490 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1491 numWakeLocksCleared += 1;
1492 break;
1493 }
1494 }
1495 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
1496
1497 // Skip dozing if requested.
1498 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1499 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1500 }
1501 } finally {
1502 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001503 }
Jeff Brown96307042012-07-27 15:51:34 -07001504 return true;
1505 }
1506
Jeff Brownc12035c2014-08-13 18:52:25 -07001507 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001508 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001509 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001510 updatePowerStateLocked();
1511 }
1512 }
1513 }
1514
Jeff Brownc12035c2014-08-13 18:52:25 -07001515 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001516 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001517 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001518 }
1519
1520 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1521 || !mBootCompleted || !mSystemReady) {
1522 return false;
1523 }
1524
Jeff Brown3edf5272014-08-14 19:25:14 -07001525 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1526 try {
1527 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001528
Jeff Brown3edf5272014-08-14 19:25:14 -07001529 mSandmanSummoned = true;
Jeff Brownfbe96702014-11-19 18:30:58 -08001530 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0);
Jeff Brown3edf5272014-08-14 19:25:14 -07001531 } finally {
1532 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1533 }
Jeff Brown26875502014-01-30 21:47:47 -08001534 return true;
1535 }
1536
1537 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001538 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001539 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001540 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1541 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001542 }
1543
1544 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1545 || !mBootCompleted || !mSystemReady) {
1546 return false;
1547 }
1548
Jeff Brown3edf5272014-08-14 19:25:14 -07001549 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1550 try {
1551 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001552
Jeff Brownfbe96702014-11-19 18:30:58 -08001553 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
Jeff Brown3edf5272014-08-14 19:25:14 -07001554 } finally {
1555 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1556 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001557 return true;
1558 }
1559
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001560 @VisibleForTesting
1561 void setWakefulnessLocked(int wakefulness, int reason) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001562 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001563 mWakefulness = wakefulness;
1564 mWakefulnessChanging = true;
1565 mDirty |= DIRTY_WAKEFULNESS;
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001566 if (mNotifier != null) {
1567 mNotifier.onWakefulnessChangeStarted(wakefulness, reason);
1568 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001569 }
1570 }
1571
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001572 /**
1573 * Logs the time the device would have spent awake before user activity timeout,
1574 * had the system not been told the user was inactive.
1575 */
1576 private void logSleepTimeoutRecapturedLocked() {
1577 final long now = SystemClock.uptimeMillis();
1578 final long savedWakeTimeMs = mOverriddenTimeout - now;
1579 if (savedWakeTimeMs >= 0) {
1580 EventLog.writeEvent(EventLogTags.POWER_SOFT_SLEEP_REQUESTED, savedWakeTimeMs);
1581 mOverriddenTimeout = -1;
1582 }
1583 }
1584
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001585 private void logScreenOn() {
1586 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1587
1588 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1589
1590 LogMaker log = new LogMaker(MetricsEvent.SCREEN);
1591 log.setType(MetricsEvent.TYPE_OPEN);
1592 log.setSubtype(0); // not user initiated
1593 log.setLatency(latencyMs); // How long it took.
1594 MetricsLogger.action(log);
1595 EventLogTags.writePowerScreenState(1, 0, 0, 0, latencyMs);
1596
1597 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1598 Slog.w(TAG, "Screen on took " + latencyMs+ " ms");
1599 }
1600 }
1601
Jeff Brown416c49c2015-05-26 19:50:18 -07001602 private void finishWakefulnessChangeIfNeededLocked() {
1603 if (mWakefulnessChanging && mDisplayReady) {
1604 if (mWakefulness == WAKEFULNESS_DOZING
1605 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1606 return; // wait until dream has enabled dozing
1607 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001608 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1609 logSleepTimeoutRecapturedLocked();
1610 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001611 if (mWakefulness == WAKEFULNESS_AWAKE) {
1612 logScreenOn();
1613 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001614 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001615 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001616 }
1617 }
1618
Jeff Brown96307042012-07-27 15:51:34 -07001619 /**
1620 * Updates the global power state based on dirty bits recorded in mDirty.
1621 *
1622 * This is the main function that performs power state transitions.
1623 * We centralize them here so that we can recompute the power state completely
1624 * each time something important changes, and ensure that we do it the same
1625 * way each time. The point is to gather all of the transition logic here.
1626 */
1627 private void updatePowerStateLocked() {
1628 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001629 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001631 if (!Thread.holdsLock(mLock)) {
1632 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001634
Jeff Brown3edf5272014-08-14 19:25:14 -07001635 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1636 try {
1637 // Phase 0: Basic state updates.
1638 updateIsPoweredLocked(mDirty);
1639 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001640 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641
Jeff Brown3edf5272014-08-14 19:25:14 -07001642 // Phase 1: Update wakefulness.
1643 // Loop because the wake lock and user activity computations are influenced
1644 // by changes in wakefulness.
1645 final long now = SystemClock.uptimeMillis();
1646 int dirtyPhase2 = 0;
1647 for (;;) {
1648 int dirtyPhase1 = mDirty;
1649 dirtyPhase2 |= dirtyPhase1;
1650 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001651
Jeff Brown3edf5272014-08-14 19:25:14 -07001652 updateWakeLockSummaryLocked(dirtyPhase1);
1653 updateUserActivitySummaryLocked(now, dirtyPhase1);
1654 if (!updateWakefulnessLocked(dirtyPhase1)) {
1655 break;
1656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001658
Pavel Grafov28939982017-10-03 15:11:52 +01001659 // Phase 2: Lock profiles that became inactive/not kept awake.
1660 updateProfilesLocked(now);
Jeff Brown3edf5272014-08-14 19:25:14 -07001661
Pavel Grafov28939982017-10-03 15:11:52 +01001662 // Phase 3: Update display power state.
1663 final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1664
1665 // Phase 4: Update dream state (depends on display ready signal).
Jeff Brown2175e9c2014-09-12 16:11:07 -07001666 updateDreamLocked(dirtyPhase2, displayBecameReady);
1667
Pavel Grafov28939982017-10-03 15:11:52 +01001668 // Phase 5: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001669 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001670
Pavel Grafov28939982017-10-03 15:11:52 +01001671 // Phase 6: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001672 // Because we might release the last suspend blocker here, we need to make sure
1673 // we finished everything else first!
1674 updateSuspendBlockerLocked();
1675 } finally {
1676 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
Jeff Brown96307042012-07-27 15:51:34 -07001678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001679
Jim Miller92e66dd2012-02-21 18:57:12 -08001680 /**
Pavel Grafov28939982017-10-03 15:11:52 +01001681 * Check profile timeouts and notify profiles that should be locked.
1682 */
1683 private void updateProfilesLocked(long now) {
1684 final int numProfiles = mProfilePowerState.size();
1685 for (int i = 0; i < numProfiles; i++) {
1686 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1687 if (isProfileBeingKeptAwakeLocked(profile, now)) {
1688 profile.mLockingNotified = false;
1689 } else if (!profile.mLockingNotified) {
1690 profile.mLockingNotified = true;
1691 mNotifier.onProfileTimeout(profile.mUserId);
1692 }
1693 }
1694 }
1695
1696 private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1697 return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1698 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1699 || (mProximityPositive &&
1700 (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1701 }
1702
1703 /**
Jeff Brown96307042012-07-27 15:51:34 -07001704 * Updates the value of mIsPowered.
1705 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001706 */
Jeff Brown96307042012-07-27 15:51:34 -07001707 private void updateIsPoweredLocked(int dirty) {
1708 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001709 final boolean wasPowered = mIsPowered;
1710 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001711 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001712 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1713 mPlugType = mBatteryManagerInternal.getPlugType();
1714 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1715 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001716
Jeff Brown26875502014-01-30 21:47:47 -08001717 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001718 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001719 + ", mIsPowered=" + mIsPowered
1720 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001721 + ", mPlugType=" + mPlugType
1722 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001723 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001724
Jeff Brownf3fb8952012-10-02 20:57:05 -07001725 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001726 mDirty |= DIRTY_IS_POWERED;
1727
Jeff Brown3b971592013-01-09 18:46:37 -08001728 // Update wireless dock detection state.
1729 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1730 mIsPowered, mPlugType, mBatteryLevel);
1731
Jeff Brown96307042012-07-27 15:51:34 -07001732 // Treat plugging and unplugging the devices as a user activity.
1733 // Users find it disconcerting when they plug or unplug the device
1734 // and it shuts off right away.
1735 // Some devices also wake the device when plugged or unplugged because
1736 // they don't have a charging LED.
1737 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001738 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1739 dockedOnWirelessCharger)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001740 wakeUpNoUpdateLocked(now, "android.server.power:POWER", Process.SYSTEM_UID,
1741 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001742 }
1743 userActivityNoUpdateLocked(
1744 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001745
1746 // Tell the notifier whether wireless charging has started so that
Jeff Brown3b971592013-01-09 18:46:37 -08001747 // it can provide feedback to the user.
Beverlyae79ab92017-12-11 09:20:02 -05001748 if (dockedOnWirelessCharger || DEBUG_WIRELESS) {
1749 mNotifier.onWirelessChargingStarted(mBatteryLevel);
Beverlyc1313eb2018-01-31 18:07:21 -05001750 } else if (mIsPowered && !wasPowered
1751 && (mPlugType == BatteryManager.BATTERY_PLUGGED_AC
1752 || mPlugType == BatteryManager.BATTERY_PLUGGED_USB)) {
1753 mNotifier.onWiredChargingStarted();
Jeff Brown84e27562012-12-07 13:56:34 -08001754 }
Jeff Brown96307042012-07-27 15:51:34 -07001755 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001756
Dianne Hackborn14272302014-06-10 23:13:02 -07001757 if (wasPowered != mIsPowered || oldLevelLow != mBatteryLevelLow) {
John Spurlock1bb480a2014-08-02 17:12:43 -04001758 if (oldLevelLow != mBatteryLevelLow && !mBatteryLevelLow) {
1759 if (DEBUG_SPEW) {
1760 Slog.d(TAG, "updateIsPoweredLocked: resetting low power snooze");
1761 }
1762 mAutoLowPowerModeSnoozing = false;
1763 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001764 updateLowPowerModeLocked();
1765 }
Jeff Brown96307042012-07-27 15:51:34 -07001766 }
1767 }
1768
Jeff Brown3b971592013-01-09 18:46:37 -08001769 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1770 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001771 // Don't wake when powered unless configured to do so.
1772 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1773 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001774 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001775
Jeff Brown3b971592013-01-09 18:46:37 -08001776 // Don't wake when undocked from wireless charger.
1777 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001778 if (wasPowered && !mIsPowered
1779 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1780 return false;
1781 }
Jeff Brown3b971592013-01-09 18:46:37 -08001782
1783 // Don't wake when docked on wireless charger unless we are certain of it.
1784 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001785 if (!wasPowered && mIsPowered
1786 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001787 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001788 return false;
1789 }
1790
1791 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001792 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001793 return false;
1794 }
1795
Bryce Lee584a4452014-10-21 15:55:55 -07001796 // Don't wake while theater mode is enabled.
1797 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1798 return false;
1799 }
1800
Adrian Roos56021892017-02-27 20:25:09 +01001801 // On Always On Display, SystemUI shows the charging indicator
1802 if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
1803 return false;
1804 }
1805
Jeff Brown9fca9e92012-10-05 14:42:56 -07001806 // Otherwise wake up!
1807 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001808 }
1809
Jeff Brown96307042012-07-27 15:51:34 -07001810 /**
1811 * Updates the value of mStayOn.
1812 * Sets DIRTY_STAY_ON if a change occurred.
1813 */
1814 private void updateStayOnLocked(int dirty) {
1815 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001816 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001817 if (mStayOnWhilePluggedInSetting != 0
1818 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001819 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001820 } else {
1821 mStayOn = false;
1822 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001823
1824 if (mStayOn != wasStayOn) {
1825 mDirty |= DIRTY_STAY_ON;
1826 }
Jeff Brown96307042012-07-27 15:51:34 -07001827 }
1828 }
1829
1830 /**
1831 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1832 * Note that most wake-locks are ignored when the system is asleep.
1833 *
1834 * This function must have no other side-effects.
1835 */
Jeff Brownec083212013-09-11 20:45:25 -07001836 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001837 private void updateWakeLockSummaryLocked(int dirty) {
1838 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1839 mWakeLockSummary = 0;
1840
Pavel Grafov28939982017-10-03 15:11:52 +01001841 final int numProfiles = mProfilePowerState.size();
1842 for (int i = 0; i < numProfiles; i++) {
1843 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
1844 }
1845
Jeff Brown96307042012-07-27 15:51:34 -07001846 final int numWakeLocks = mWakeLocks.size();
1847 for (int i = 0; i < numWakeLocks; i++) {
1848 final WakeLock wakeLock = mWakeLocks.get(i);
Pavel Grafov28939982017-10-03 15:11:52 +01001849 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
1850 mWakeLockSummary |= wakeLockFlags;
1851 for (int j = 0; j < numProfiles; j++) {
1852 final ProfilePowerState profile = mProfilePowerState.valueAt(j);
1853 if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
1854 profile.mWakeLockSummary |= wakeLockFlags;
1855 }
Jeff Brown96307042012-07-27 15:51:34 -07001856 }
1857 }
1858
Pavel Grafov28939982017-10-03 15:11:52 +01001859 mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
1860 for (int i = 0; i < numProfiles; i++) {
1861 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1862 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
Jeff Brownc2932a12014-11-20 18:04:05 -08001863 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001864
Jeff Brown96307042012-07-27 15:51:34 -07001865 if (DEBUG_SPEW) {
1866 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001867 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001868 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1869 }
1870 }
1871 }
1872
Pavel Grafov28939982017-10-03 15:11:52 +01001873 private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
1874 // Cancel wake locks that make no sense based on the current state.
1875 if (mWakefulness != WAKEFULNESS_DOZING) {
1876 wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
1877 }
1878 if (mWakefulness == WAKEFULNESS_ASLEEP
1879 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1880 wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1881 | WAKE_LOCK_BUTTON_BRIGHT);
1882 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1883 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1884 }
1885 }
1886
1887 // Infer implied wake locks where necessary based on the current state.
1888 if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1889 if (mWakefulness == WAKEFULNESS_AWAKE) {
1890 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1891 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1892 wakeLockSummary |= WAKE_LOCK_CPU;
1893 }
1894 }
1895 if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1896 wakeLockSummary |= WAKE_LOCK_CPU;
1897 }
1898
1899 return wakeLockSummary;
1900 }
1901
1902 /** Get wake lock summary flags that correspond to the given wake lock. */
1903 private int getWakeLockSummaryFlags(WakeLock wakeLock) {
1904 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1905 case PowerManager.PARTIAL_WAKE_LOCK:
1906 if (!wakeLock.mDisabled) {
1907 // We only respect this if the wake lock is not disabled.
1908 return WAKE_LOCK_CPU;
1909 }
1910 break;
1911 case PowerManager.FULL_WAKE_LOCK:
1912 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1913 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1914 return WAKE_LOCK_SCREEN_BRIGHT;
1915 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1916 return WAKE_LOCK_SCREEN_DIM;
1917 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1918 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1919 case PowerManager.DOZE_WAKE_LOCK:
1920 return WAKE_LOCK_DOZE;
1921 case PowerManager.DRAW_WAKE_LOCK:
1922 return WAKE_LOCK_DRAW;
1923 }
1924 return 0;
1925 }
1926
1927 private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
1928 if (wakeLock.mWorkSource != null) {
1929 for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
1930 final int uid = wakeLock.mWorkSource.get(k);
1931 if (userId == UserHandle.getUserId(uid)) {
1932 return true;
1933 }
1934 }
Narayan Kamath2f916ed2017-12-29 13:02:15 +00001935
1936 final ArrayList<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
1937 if (workChains != null) {
1938 for (int k = 0; k < workChains.size(); k++) {
1939 final int uid = workChains.get(k).getAttributionUid();
1940 if (userId == UserHandle.getUserId(uid)) {
1941 return true;
1942 }
1943 }
1944 }
Pavel Grafov28939982017-10-03 15:11:52 +01001945 }
1946 return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
1947 }
1948
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001949 void checkForLongWakeLocks() {
1950 synchronized (mLock) {
1951 final long now = SystemClock.uptimeMillis();
1952 mNotifyLongDispatched = now;
1953 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
1954 long nextCheckTime = Long.MAX_VALUE;
1955 final int numWakeLocks = mWakeLocks.size();
1956 for (int i = 0; i < numWakeLocks; i++) {
1957 final WakeLock wakeLock = mWakeLocks.get(i);
1958 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1959 == PowerManager.PARTIAL_WAKE_LOCK) {
1960 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
1961 if (wakeLock.mAcquireTime < when) {
1962 // This wake lock has exceeded the long acquire time, report!
1963 notifyWakeLockLongStartedLocked(wakeLock);
1964 } else {
1965 // This wake lock could still become a long one, at this time.
1966 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
1967 if (checkTime < nextCheckTime) {
1968 nextCheckTime = checkTime;
1969 }
1970 }
1971 }
1972 }
1973 }
1974 mNotifyLongScheduled = 0;
1975 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
1976 if (nextCheckTime != Long.MAX_VALUE) {
1977 mNotifyLongNextCheck = nextCheckTime;
1978 enqueueNotifyLongMsgLocked(nextCheckTime);
1979 } else {
1980 mNotifyLongNextCheck = 0;
1981 }
1982 }
1983 }
1984
Jeff Brown96307042012-07-27 15:51:34 -07001985 /**
1986 * Updates the value of mUserActivitySummary to summarize the user requested
1987 * state of the system such as whether the screen should be bright or dim.
1988 * Note that user activity is ignored when the system is asleep.
1989 *
1990 * This function must have no other side-effects.
1991 */
1992 private void updateUserActivitySummaryLocked(long now, int dirty) {
1993 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07001994 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08001995 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001996 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1997
1998 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08001999 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07002000 || mWakefulness == WAKEFULNESS_DREAMING
2001 || mWakefulness == WAKEFULNESS_DOZING) {
Pavel Grafov28939982017-10-03 15:11:52 +01002002 final long sleepTimeout = getSleepTimeoutLocked();
2003 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
2004 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002005 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Pavel Grafov28939982017-10-03 15:11:52 +01002006 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
Jeff Brown96307042012-07-27 15:51:34 -07002007
2008 mUserActivitySummary = 0;
2009 if (mLastUserActivityTime >= mLastWakeTime) {
2010 nextTimeout = mLastUserActivityTime
2011 + screenOffTimeout - screenDimDuration;
2012 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002013 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002014 } else {
2015 nextTimeout = mLastUserActivityTime + screenOffTimeout;
2016 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002017 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002018 }
2019 }
2020 }
2021 if (mUserActivitySummary == 0
2022 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
2023 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07002024 if (now < nextTimeout) {
Andrii Kulian9407a6b2017-05-24 12:24:09 -07002025 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
2026 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
Jeff Brown970d4132014-07-19 11:33:47 -07002027 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2028 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
2029 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2030 }
Jeff Brown96307042012-07-27 15:51:34 -07002031 }
2032 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002033
Jeff Brown05af6ad2014-09-30 20:54:30 -07002034 if (mUserActivitySummary == 0) {
2035 if (sleepTimeout >= 0) {
2036 final long anyUserActivity = Math.max(mLastUserActivityTime,
2037 mLastUserActivityTimeNoChangeLights);
2038 if (anyUserActivity >= mLastWakeTime) {
2039 nextTimeout = anyUserActivity + sleepTimeout;
2040 if (now < nextTimeout) {
2041 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2042 }
2043 }
2044 } else {
2045 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2046 nextTimeout = -1;
2047 }
2048 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002049
2050 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07002051 if ((mUserActivitySummary &
2052 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07002053 // Device is being kept awake by recent user activity
2054 if (nextTimeout >= now && mOverriddenTimeout == -1) {
2055 // Save when the next timeout would have occurred
2056 mOverriddenTimeout = nextTimeout;
2057 }
Mojtaba2d80edc2015-09-18 16:35:24 -07002058 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002059 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2060 nextTimeout = -1;
2061 }
2062
Pavel Grafov28939982017-10-03 15:11:52 +01002063 if (nextProfileTimeout > 0) {
2064 nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2065 }
2066
Jeff Brown05af6ad2014-09-30 20:54:30 -07002067 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002068 scheduleUserInactivityTimeout(nextTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07002069 }
2070 } else {
2071 mUserActivitySummary = 0;
2072 }
2073
2074 if (DEBUG_SPEW) {
2075 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002076 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002077 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2078 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2079 }
2080 }
2081 }
2082
Pavel Grafov28939982017-10-03 15:11:52 +01002083 private void scheduleUserInactivityTimeout(long timeMs) {
2084 final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2085 msg.setAsynchronous(true);
2086 mHandler.sendMessageAtTime(msg, timeMs);
2087 }
2088
2089 /**
2090 * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2091 */
2092 private long getNextProfileTimeoutLocked(long now) {
2093 long nextTimeout = -1;
2094 final int numProfiles = mProfilePowerState.size();
2095 for (int i = 0; i < numProfiles; i++) {
2096 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2097 final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2098 if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2099 nextTimeout = timeout;
2100 }
2101 }
2102 return nextTimeout;
2103 }
2104
Jeff Brown96307042012-07-27 15:51:34 -07002105 /**
2106 * Called when a user activity timeout has occurred.
2107 * Simply indicates that something about user activity has changed so that the new
2108 * state can be recomputed when the power state is updated.
2109 *
2110 * This function must have no other side-effects besides setting the dirty
2111 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
2112 */
2113 private void handleUserActivityTimeout() { // runs on handler thread
2114 synchronized (mLock) {
2115 if (DEBUG_SPEW) {
2116 Slog.d(TAG, "handleUserActivityTimeout");
2117 }
2118
2119 mDirty |= DIRTY_USER_ACTIVITY;
2120 updatePowerStateLocked();
2121 }
2122 }
2123
Pavel Grafov28939982017-10-03 15:11:52 +01002124 private long getSleepTimeoutLocked() {
2125 final long timeout = mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -07002126 if (timeout <= 0) {
2127 return -1;
2128 }
2129 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2130 }
2131
Pavel Grafov28939982017-10-03 15:11:52 +01002132 private long getScreenOffTimeoutLocked(long sleepTimeout) {
2133 long timeout = mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002134 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2135 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2136 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002137 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002138 timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002139 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002140 if (sleepTimeout >= 0) {
2141 timeout = Math.min(timeout, sleepTimeout);
2142 }
Jeff Brown27736f52014-05-20 17:17:10 -07002143 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002144 }
2145
Pavel Grafov28939982017-10-03 15:11:52 +01002146 private long getScreenDimDurationLocked(long screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07002147 return Math.min(mMaximumScreenDimDurationConfig,
Pavel Grafov28939982017-10-03 15:11:52 +01002148 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07002149 }
2150
2151 /**
2152 * Updates the wakefulness of the device.
2153 *
Jeff Brown26875502014-01-30 21:47:47 -08002154 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07002155 * based on the current wake locks and user activity state. It may modify mDirty
2156 * if the wakefulness changes.
2157 *
2158 * Returns true if the wakefulness changed and we need to restart power state calculation.
2159 */
2160 private boolean updateWakefulnessLocked(int dirty) {
2161 boolean changed = false;
2162 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07002163 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
2164 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002165 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2166 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002167 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07002168 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002169 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07002170 if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07002171 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002172 } else {
2173 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07002174 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002175 }
Jeff Brown96307042012-07-27 15:51:34 -07002176 }
2177 }
2178 return changed;
2179 }
2180
Jeff Brown645832d2012-10-03 14:57:03 -07002181 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07002182 * Returns true if the device should automatically nap and start dreaming when the user
2183 * activity timeout has expired and it's bedtime.
2184 */
2185 private boolean shouldNapAtBedTimeLocked() {
2186 return mDreamsActivateOnSleepSetting
2187 || (mDreamsActivateOnDockSetting
2188 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2189 }
2190
2191 /**
Jeff Brown645832d2012-10-03 14:57:03 -07002192 * Returns true if the device should go to sleep now.
2193 * Also used when exiting a dream to determine whether we should go back
2194 * to being fully awake or else go to sleep for good.
2195 */
Jeff Brown96307042012-07-27 15:51:34 -07002196 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07002197 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07002198 }
2199
2200 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07002201 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07002202 * or the stay on while powered setting. We also keep the phone awake when
2203 * the proximity sensor returns a positive result so that the device does not
2204 * lock while in a phone call. This function only controls whether the device
2205 * will go to sleep or dream which is independent of whether it will be allowed
2206 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07002207 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07002208 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07002209 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07002210 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07002211 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07002212 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002213 | USER_ACTIVITY_SCREEN_DIM)) != 0
2214 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07002215 }
2216
2217 /**
2218 * Determines whether to post a message to the sandman to update the dream state.
2219 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002220 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002221 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07002222 | DIRTY_USER_ACTIVITY
2223 | DIRTY_WAKE_LOCKS
2224 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002225 | DIRTY_SETTINGS
2226 | DIRTY_IS_POWERED
2227 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07002228 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07002229 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2230 if (mDisplayReady) {
2231 scheduleSandmanLocked();
2232 }
Jeff Brown96307042012-07-27 15:51:34 -07002233 }
2234 }
2235
2236 private void scheduleSandmanLocked() {
2237 if (!mSandmanScheduled) {
2238 mSandmanScheduled = true;
2239 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2240 msg.setAsynchronous(true);
2241 mHandler.sendMessage(msg);
2242 }
2243 }
2244
2245 /**
Jeff Brown26875502014-01-30 21:47:47 -08002246 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07002247 *
2248 * We do this asynchronously because we must call out of the power manager to start
2249 * the dream and we don't want to hold our lock while doing so. There is a risk that
2250 * the device will wake or go to sleep in the meantime so we have to handle that case.
2251 */
2252 private void handleSandman() { // runs on handler thread
2253 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08002254 final boolean startDreaming;
2255 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07002256 synchronized (mLock) {
2257 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08002258 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07002259 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002260 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08002261 mSandmanSummoned = false;
2262 } else {
2263 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002264 }
2265 }
2266
Jeff Brown96307042012-07-27 15:51:34 -07002267 // Start dreaming if needed.
2268 // We only control the dream on the handler thread, so we don't need to worry about
2269 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08002270 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07002271 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08002272 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07002273 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002274 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08002275 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07002276 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002277 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08002278 } else {
2279 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002280 }
2281
2282 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07002283 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08002284 // Remember the initial battery level when the dream started.
2285 if (startDreaming && isDreaming) {
2286 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2287 if (wakefulness == WAKEFULNESS_DOZING) {
2288 Slog.i(TAG, "Dozing...");
2289 } else {
2290 Slog.i(TAG, "Dreaming...");
2291 }
2292 }
2293
2294 // If preconditions changed, wait for the next iteration to determine
2295 // whether the dream should continue (or be restarted).
2296 if (mSandmanSummoned || mWakefulness != wakefulness) {
2297 return; // wait for next cycle
2298 }
2299
2300 // Determine whether the dream should continue.
2301 if (wakefulness == WAKEFULNESS_DREAMING) {
2302 if (isDreaming && canDreamLocked()) {
2303 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002304 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002305 - mDreamsBatteryLevelDrainCutoffConfig
2306 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002307 // If the user activity timeout expired and the battery appears
2308 // to be draining faster than it is charging then stop dreaming
2309 // and go to sleep.
2310 Slog.i(TAG, "Stopping dream because the battery appears to "
2311 + "be draining faster than it is charging. "
2312 + "Battery level when dream started: "
2313 + mBatteryLevelWhenDreamStarted + "%. "
2314 + "Battery level now: " + mBatteryLevel + "%.");
2315 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002316 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002317 }
Jeff Brown96307042012-07-27 15:51:34 -07002318 }
Jeff Brown26875502014-01-30 21:47:47 -08002319
2320 // Dream has ended or will be stopped. Update the power state.
2321 if (isItBedTimeYetLocked()) {
2322 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
Jeff Brownc12035c2014-08-13 18:52:25 -07002323 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002324 updatePowerStateLocked();
2325 } else {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07002326 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), "android.server.power:DREAM",
2327 Process.SYSTEM_UID, mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002328 updatePowerStateLocked();
2329 }
2330 } else if (wakefulness == WAKEFULNESS_DOZING) {
2331 if (isDreaming) {
2332 return; // continue dozing
2333 }
2334
2335 // Doze has ended or will be stopped. Update the power state.
Jeff Brownc12035c2014-08-13 18:52:25 -07002336 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002337 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002338 }
Jeff Brown96307042012-07-27 15:51:34 -07002339 }
2340
Jeff Brown26875502014-01-30 21:47:47 -08002341 // Stop dream.
2342 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002343 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002344 }
2345 }
2346
2347 /**
Jeff Brown26875502014-01-30 21:47:47 -08002348 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002349 */
2350 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002351 if (mWakefulness != WAKEFULNESS_DREAMING
2352 || !mDreamsSupportedConfig
2353 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002354 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordon3107d292016-09-20 15:50:35 -07002355 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002356 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2357 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002358 || !mBootCompleted) {
2359 return false;
2360 }
2361 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002362 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002363 return false;
2364 }
2365 if (!mIsPowered
2366 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2367 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2368 return false;
2369 }
2370 if (mIsPowered
2371 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2372 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2373 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002374 }
2375 }
Jeff Brown26875502014-01-30 21:47:47 -08002376 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002377 }
2378
Jeff Brown96307042012-07-27 15:51:34 -07002379 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002380 * Returns true if the device is allowed to doze in its current state.
2381 */
2382 private boolean canDozeLocked() {
2383 return mWakefulness == WAKEFULNESS_DOZING;
2384 }
2385
2386 /**
Jeff Brown96307042012-07-27 15:51:34 -07002387 * Updates the display power state asynchronously.
2388 * When the update is finished, mDisplayReady will be set to true. The display
2389 * controller posts a message to tell us when the actual display power state
2390 * has been updated so we come back here to double-check and finish up.
2391 *
2392 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002393 *
2394 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002395 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002396 private boolean updateDisplayPowerStateLocked(int dirty) {
2397 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002398 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2399 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordon3107d292016-09-20 15:50:35 -07002400 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2401 DIRTY_QUIESCENT)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07002402 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002403
Jeff Browne333e672014-10-28 13:48:55 -07002404 // Determine appropriate screen brightness and auto-brightness adjustments.
Michael Wrightd8460232018-01-16 18:04:59 +00002405 final boolean autoBrightness;
2406 final int screenBrightnessOverride;
Michael Wright9f818ea2016-07-29 19:59:39 +01002407 if (!mBootCompleted) {
2408 // Keep the brightness steady during boot. This requires the
2409 // bootloader brightness and the default brightness to be identical.
2410 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002411 screenBrightnessOverride = mScreenBrightnessSettingDefault;
Michael Wright9f818ea2016-07-29 19:59:39 +01002412 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002413 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002414 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManager;
2415 } else {
2416 autoBrightness = (mScreenBrightnessModeSetting ==
2417 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2418 screenBrightnessOverride = -1;
Jeff Brown96307042012-07-27 15:51:34 -07002419 }
Jeff Browne333e672014-10-28 13:48:55 -07002420
2421 // Update display power request.
Michael Wrightd8460232018-01-16 18:04:59 +00002422 mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
Jeff Brown96307042012-07-27 15:51:34 -07002423 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002424 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Santos Cordon3107d292016-09-20 15:50:35 -07002425 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002426
jackqdyulei92681e82017-02-28 11:26:28 -08002427 updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2428
Jeff Brown970d4132014-07-19 11:33:47 -07002429 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2430 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Chris Phoenix10a4a642017-09-25 13:21:00 -07002431 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0) {
2432 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2433 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2434 }
2435 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2436 mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2437 }
Jeff Brownc2932a12014-11-20 18:04:05 -08002438 }
Jeff Brown970d4132014-07-19 11:33:47 -07002439 mDisplayPowerRequest.dozeScreenBrightness =
2440 mDozeScreenBrightnessOverrideFromDreamManager;
2441 } else {
2442 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2443 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2444 }
2445
Jeff Brown131206b2014-04-08 17:27:14 -07002446 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002447 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002448 mRequestWaitForNegativeProximity = false;
2449
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002450 if ((dirty & DIRTY_QUIESCENT) != 0) {
2451 sQuiescent = false;
2452 }
Jeff Brown96307042012-07-27 15:51:34 -07002453 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002454 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002455 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002456 + ", mWakefulness=" + mWakefulness
2457 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2458 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002459 + ", mBootCompleted=" + mBootCompleted
Michael Wrightd8460232018-01-16 18:04:59 +00002460 + ", screenBrightnessOverride=" + screenBrightnessOverride
2461 + ", useAutoBrightness=" + autoBrightness
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002462 + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
Santos Cordon3107d292016-09-20 15:50:35 -07002463 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002464 + ", sQuiescent=" + sQuiescent);
Jeff Brown96307042012-07-27 15:51:34 -07002465 }
2466 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002467 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002468 }
2469
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002470 private void updateScreenBrightnessBoostLocked(int dirty) {
2471 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2472 if (mScreenBrightnessBoostInProgress) {
2473 final long now = SystemClock.uptimeMillis();
2474 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2475 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2476 final long boostTimeout = mLastScreenBrightnessBoostTime +
2477 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2478 if (boostTimeout > now) {
2479 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2480 msg.setAsynchronous(true);
2481 mHandler.sendMessageAtTime(msg, boostTimeout);
2482 return;
2483 }
Jeff Browne333e672014-10-28 13:48:55 -07002484 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002485 mScreenBrightnessBoostInProgress = false;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07002486 mNotifier.onScreenBrightnessBoostChanged();
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002487 userActivityNoUpdateLocked(now,
2488 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002489 }
Jeff Browne333e672014-10-28 13:48:55 -07002490 }
2491 }
2492
Santos Cordon3107d292016-09-20 15:50:35 -07002493 private boolean shouldBoostScreenBrightness() {
2494 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2495 }
2496
Jeff Brown96307042012-07-27 15:51:34 -07002497 private static boolean isValidBrightness(int value) {
2498 return value >= 0 && value <= 255;
2499 }
2500
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002501 @VisibleForTesting
2502 int getDesiredScreenPolicyLocked() {
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002503 if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
Jeff Brown970d4132014-07-19 11:33:47 -07002504 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002505 }
2506
Jeff Brown2175e9c2014-09-12 16:11:07 -07002507 if (mWakefulness == WAKEFULNESS_DOZING) {
2508 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2509 return DisplayPowerRequest.POLICY_DOZE;
2510 }
2511 if (mDozeAfterScreenOffConfig) {
2512 return DisplayPowerRequest.POLICY_OFF;
2513 }
2514 // Fall through and preserve the current screen policy if not configured to
2515 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002516 }
2517
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002518 // It is important that POLICY_VR check happens after the wakefulness checks above so
2519 // that VR-mode does not prevent displays from transitioning to the correct state when
2520 // dozing or sleeping.
2521 if (mIsVrModeEnabled) {
2522 return DisplayPowerRequest.POLICY_VR;
2523 }
2524
Jeff Brown96307042012-07-27 15:51:34 -07002525 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2526 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002527 || !mBootCompleted
2528 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002529 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002530 }
2531
Jeff Brown970d4132014-07-19 11:33:47 -07002532 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002533 }
2534
Jeff Brown131206b2014-04-08 17:27:14 -07002535 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2536 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002537 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002538
Jeff Brown96307042012-07-27 15:51:34 -07002539 @Override
2540 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002541 synchronized (mLock) {
2542 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2543 updatePowerStateLocked();
2544 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002545 }
2546
2547 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002548 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002549 synchronized (mLock) {
2550 mProximityPositive = true;
2551 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2552 updatePowerStateLocked();
2553 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002554 }
2555
2556 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002557 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002558 synchronized (mLock) {
2559 mProximityPositive = false;
2560 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2561 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2562 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2563 updatePowerStateLocked();
2564 }
Jeff Brown96307042012-07-27 15:51:34 -07002565 }
Jeff Brown131206b2014-04-08 17:27:14 -07002566
2567 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002568 public void onDisplayStateChange(int state) {
2569 // This method is only needed to support legacy display blanking behavior
2570 // where the display's power state is coupled to suspend or to the power HAL.
2571 // The order of operations matters here.
2572 synchronized (mLock) {
2573 if (mDisplayState != state) {
2574 mDisplayState = state;
2575 if (state == Display.STATE_OFF) {
2576 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2577 setHalInteractiveModeLocked(false);
2578 }
2579 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2580 setHalAutoSuspendModeLocked(true);
2581 }
2582 } else {
2583 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2584 setHalAutoSuspendModeLocked(false);
2585 }
2586 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2587 setHalInteractiveModeLocked(true);
2588 }
2589 }
2590 }
2591 }
2592 }
2593
2594 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002595 public void acquireSuspendBlocker() {
2596 mDisplaySuspendBlocker.acquire();
2597 }
2598
2599 @Override
2600 public void releaseSuspendBlocker() {
2601 mDisplaySuspendBlocker.release();
2602 }
2603
2604 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002605 public String toString() {
2606 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002607 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002608 }
2609 }
Jeff Brown96307042012-07-27 15:51:34 -07002610 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002611
Jeff Brown96307042012-07-27 15:51:34 -07002612 private boolean shouldUseProximitySensorLocked() {
Santos Cordon3107d292016-09-20 15:50:35 -07002613 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002614 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002615
Jeff Brown96307042012-07-27 15:51:34 -07002616 /**
2617 * Updates the suspend blocker that keeps the CPU alive.
2618 *
2619 * This function must have no other side-effects.
2620 */
2621 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002622 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002623 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2624 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002625 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002626
2627 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002628 // FIXME We should consider just leaving auto-suspend enabled forever since
2629 // we already hold the necessary wakelocks.
2630 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2631 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002632 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002633
2634 // First acquire suspend blockers if needed.
2635 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2636 mWakeLockSuspendBlocker.acquire();
2637 mHoldingWakeLockSuspendBlocker = true;
2638 }
2639 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2640 mDisplaySuspendBlocker.acquire();
2641 mHoldingDisplaySuspendBlocker = true;
2642 }
2643
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002644 // Inform the power HAL about interactive mode.
2645 // Although we could set interactive strictly based on the wakefulness
2646 // as reported by isInteractive(), it is actually more desirable to track
2647 // the display policy state instead so that the interactive state observed
2648 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2649 // Refer to getDesiredScreenPolicyLocked() for details.
2650 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2651 // When becoming non-interactive, we want to defer sending this signal
2652 // until the display is actually ready so that all transitions have
2653 // completed. This is probably a good sign that things have gotten
2654 // too tangled over here...
2655 if (interactive || mDisplayReady) {
2656 setHalInteractiveModeLocked(interactive);
2657 }
2658 }
2659
Jeff Brown27f7a862012-12-12 15:43:31 -08002660 // Then release suspend blockers if needed.
2661 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2662 mWakeLockSuspendBlocker.release();
2663 mHoldingWakeLockSuspendBlocker = false;
2664 }
2665 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2666 mDisplaySuspendBlocker.release();
2667 mHoldingDisplaySuspendBlocker = false;
2668 }
Jeff Brown26875502014-01-30 21:47:47 -08002669
2670 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002671 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2672 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002673 }
Jeff Brown96307042012-07-27 15:51:34 -07002674 }
2675
Jeff Brownec083212013-09-11 20:45:25 -07002676 /**
2677 * Return true if we must keep a suspend blocker active on behalf of the display.
2678 * We do so if the screen is on or is in transition between states.
2679 */
Jeff Brown26875502014-01-30 21:47:47 -08002680 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002681 if (!mDisplayReady) {
2682 return true;
2683 }
Jeff Brown970d4132014-07-19 11:33:47 -07002684 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002685 // If we asked for the screen to be on but it is off due to the proximity
2686 // sensor then we may suspend but only if the configuration allows it.
2687 // On some hardware it may not be safe to suspend because the proximity
2688 // sensor may not be correctly configured as a wake-up source.
2689 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2690 || !mSuspendWhenScreenOffDueToProximityConfig) {
2691 return true;
2692 }
2693 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002694 if (mScreenBrightnessBoostInProgress) {
2695 return true;
2696 }
Jeff Brown26875502014-01-30 21:47:47 -08002697 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002698 return false;
2699 }
2700
Jeff Brown037c33e2014-04-09 00:31:55 -07002701 private void setHalAutoSuspendModeLocked(boolean enable) {
2702 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002703 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002704 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002705 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002706 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002707 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2708 try {
2709 nativeSetAutoSuspend(enable);
2710 } finally {
2711 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2712 }
Jeff Brown26875502014-01-30 21:47:47 -08002713 }
2714 }
2715
Jeff Brown037c33e2014-04-09 00:31:55 -07002716 private void setHalInteractiveModeLocked(boolean enable) {
2717 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002718 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002719 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002720 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002721 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002722 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2723 try {
2724 nativeSetInteractive(enable);
2725 } finally {
2726 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2727 }
Jeff Brown26875502014-01-30 21:47:47 -08002728 }
2729 }
2730
Jeff Brown037c33e2014-04-09 00:31:55 -07002731 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002732 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08002733 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002734 }
2735 }
2736
Dianne Hackborneb94fa72014-06-03 17:48:12 -07002737 private boolean isLowPowerModeInternal() {
2738 synchronized (mLock) {
2739 return mLowPowerModeEnabled;
2740 }
2741 }
2742
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002743 private boolean setLowPowerModeInternal(boolean mode) {
2744 synchronized (mLock) {
2745 if (DEBUG) Slog.d(TAG, "setLowPowerModeInternal " + mode + " mIsPowered=" + mIsPowered);
2746 if (mIsPowered) {
2747 return false;
2748 }
2749 Settings.Global.putInt(mContext.getContentResolver(),
2750 Settings.Global.LOW_POWER_MODE, mode ? 1 : 0);
2751 mLowPowerModeSetting = mode;
2752
2753 if (mAutoLowPowerModeConfigured && mBatteryLevelLow) {
2754 if (mode && mAutoLowPowerModeSnoozing) {
2755 if (DEBUG_SPEW) {
2756 Slog.d(TAG, "setLowPowerModeInternal: clearing low power mode snooze");
2757 }
2758 mAutoLowPowerModeSnoozing = false;
2759 } else if (!mode && !mAutoLowPowerModeSnoozing) {
2760 if (DEBUG_SPEW) {
2761 Slog.d(TAG, "setLowPowerModeInternal: snoozing low power mode");
2762 }
2763 mAutoLowPowerModeSnoozing = true;
2764 }
2765 }
2766
2767 updateLowPowerModeLocked();
2768 return true;
2769 }
2770 }
2771
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002772 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002773 synchronized (mLock) {
2774 return mDeviceIdleMode;
2775 }
2776 }
2777
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002778 boolean isLightDeviceIdleModeInternal() {
2779 synchronized (mLock) {
2780 return mLightDeviceIdleMode;
2781 }
2782 }
2783
Jeff Brown96307042012-07-27 15:51:34 -07002784 private void handleBatteryStateChangedLocked() {
2785 mDirty |= DIRTY_BATTERY_STATE;
2786 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002787 }
2788
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002789 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002790 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07002791 if (mHandler == null || !mSystemReady) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07002792 if (RescueParty.isAttemptingFactoryReset()) {
2793 // If we're stuck in a really low-level reboot loop, and a
2794 // rescue party is trying to prompt the user for a factory data
2795 // reset, we must GET TO DA CHOPPA!
2796 PowerManagerService.lowLevelReboot(reason);
2797 } else {
2798 throw new IllegalStateException("Too early to call shutdown() or reboot()");
2799 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002800 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002801
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002802 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07002803 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002804 public void run() {
2805 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002806 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002807 ShutdownThread.rebootSafeMode(getUiContext(), confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002808 } else if (haltMode == HALT_MODE_REBOOT) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002809 ShutdownThread.reboot(getUiContext(), reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002810 } else {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002811 ShutdownThread.shutdown(getUiContext(), reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002812 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002813 }
San Mehat1e512792010-01-07 10:40:29 -08002814 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002815 };
Jeff Brown96307042012-07-27 15:51:34 -07002816
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002817 // ShutdownThread must run on a looper capable of displaying the UI.
Michael Wright64c820d2017-03-21 12:36:55 +00002818 Message msg = Message.obtain(UiThread.getHandler(), runnable);
Jeff Brown96307042012-07-27 15:51:34 -07002819 msg.setAsynchronous(true);
Michael Wright64c820d2017-03-21 12:36:55 +00002820 UiThread.getHandler().sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002821
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002822 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002823 if (wait) {
2824 synchronized (runnable) {
2825 while (true) {
2826 try {
2827 runnable.wait();
2828 } catch (InterruptedException e) {
2829 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002830 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002831 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002832 }
2833 }
2834
Jeff Brown96307042012-07-27 15:51:34 -07002835 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08002836 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07002837 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002838 public void run() {
2839 throw new RuntimeException(message);
2840 }
Dan Egnor60d87622009-12-16 16:32:58 -08002841 };
2842 try {
2843 t.start();
2844 t.join();
2845 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002846 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08002847 }
2848 }
2849
jackqdyulei92681e82017-02-28 11:26:28 -08002850 @VisibleForTesting
2851 void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
2852 PowerSaveState state = mBatterySaverPolicy.
2853 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS, mLowPowerModeEnabled);
2854 displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
2855 displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
2856 }
2857
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002858 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07002859 Settings.Global.putInt(mContext.getContentResolver(),
2860 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 }
2862
Pavel Grafov28939982017-10-03 15:11:52 +01002863 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
2864 if (userId < 0) {
2865 Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
2866 return;
2867 }
Jeff Brown96307042012-07-27 15:51:34 -07002868 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01002869 // System-wide timeout
2870 if (userId == UserHandle.USER_SYSTEM) {
2871 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2872 } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
2873 mProfilePowerState.delete(userId);
2874 } else {
2875 final ProfilePowerState profile = mProfilePowerState.get(userId);
2876 if (profile != null) {
2877 profile.mScreenOffTimeout = timeMs;
2878 } else {
2879 mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
2880 // We need to recalculate wake locks for the new profile state.
2881 mDirty |= DIRTY_WAKE_LOCKS;
2882 }
2883 }
Jeff Brown96307042012-07-27 15:51:34 -07002884 mDirty |= DIRTY_SETTINGS;
2885 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 }
2887 }
2888
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002889 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002890 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002891 if (mDeviceIdleMode == enabled) {
2892 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002893 }
Felipe Lemeea014392016-09-06 13:59:54 -07002894 mDeviceIdleMode = enabled;
2895 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002896 }
Felipe Lemeea014392016-09-06 13:59:54 -07002897 if (enabled) {
2898 EventLogTags.writeDeviceIdleOnPhase("power");
2899 } else {
2900 EventLogTags.writeDeviceIdleOffPhase("power");
2901 }
2902 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002903 }
2904
2905 boolean setLightDeviceIdleModeInternal(boolean enabled) {
2906 synchronized (mLock) {
2907 if (mLightDeviceIdleMode != enabled) {
2908 mLightDeviceIdleMode = enabled;
2909 return true;
2910 }
2911 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002912 }
2913 }
2914
2915 void setDeviceIdleWhitelistInternal(int[] appids) {
2916 synchronized (mLock) {
2917 mDeviceIdleWhitelist = appids;
2918 if (mDeviceIdleMode) {
2919 updateWakeLockDisabledStatesLocked();
2920 }
2921 }
2922 }
2923
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002924 void setDeviceIdleTempWhitelistInternal(int[] appids) {
2925 synchronized (mLock) {
2926 mDeviceIdleTempWhitelist = appids;
2927 if (mDeviceIdleMode) {
2928 updateWakeLockDisabledStatesLocked();
2929 }
2930 }
2931 }
2932
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002933 void startUidChangesInternal() {
2934 synchronized (mLock) {
2935 mUidsChanging = true;
2936 }
2937 }
2938
2939 void finishUidChangesInternal() {
2940 synchronized (mLock) {
2941 mUidsChanging = false;
2942 if (mUidsChanged) {
2943 updateWakeLockDisabledStatesLocked();
2944 mUidsChanged = false;
2945 }
2946 }
2947 }
2948
2949 private void handleUidStateChangeLocked() {
2950 if (mUidsChanging) {
2951 mUidsChanged = true;
2952 } else {
2953 updateWakeLockDisabledStatesLocked();
2954 }
2955 }
2956
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002957 void updateUidProcStateInternal(int uid, int procState) {
2958 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002959 UidState state = mUidState.get(uid);
2960 if (state == null) {
2961 state = new UidState(uid);
2962 mUidState.put(uid, state);
2963 }
Dianne Hackborn951ea692016-11-02 10:41:53 -07002964 final boolean oldShouldAllow = state.mProcState
2965 <= ActivityManager.PROCESS_STATE_RECEIVER;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002966 state.mProcState = procState;
Dianne Hackborn951ea692016-11-02 10:41:53 -07002967 if (state.mNumWakeLocks > 0) {
2968 if (mDeviceIdleMode) {
2969 handleUidStateChangeLocked();
2970 } else if (!state.mActive && oldShouldAllow !=
2971 (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
2972 // If this uid is not active, but the process state has changed such
2973 // that we may still want to allow it to hold a wake lock, then take care of it.
2974 handleUidStateChangeLocked();
2975 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002976 }
2977 }
2978 }
2979
2980 void uidGoneInternal(int uid) {
2981 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002982 final int index = mUidState.indexOfKey(uid);
2983 if (index >= 0) {
2984 UidState state = mUidState.valueAt(index);
2985 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
2986 state.mActive = false;
2987 mUidState.removeAt(index);
2988 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
2989 handleUidStateChangeLocked();
2990 }
2991 }
2992 }
2993 }
2994
2995 void uidActiveInternal(int uid) {
2996 synchronized (mLock) {
2997 UidState state = mUidState.get(uid);
2998 if (state == null) {
2999 state = new UidState(uid);
3000 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
3001 mUidState.put(uid, state);
3002 }
3003 state.mActive = true;
3004 if (state.mNumWakeLocks > 0) {
3005 handleUidStateChangeLocked();
3006 }
3007 }
3008 }
3009
3010 void uidIdleInternal(int uid) {
3011 synchronized (mLock) {
3012 UidState state = mUidState.get(uid);
3013 if (state != null) {
3014 state.mActive = false;
3015 if (state.mNumWakeLocks > 0) {
3016 handleUidStateChangeLocked();
3017 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003018 }
3019 }
3020 }
3021
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003022 private void updateWakeLockDisabledStatesLocked() {
3023 boolean changed = false;
3024 final int numWakeLocks = mWakeLocks.size();
3025 for (int i = 0; i < numWakeLocks; i++) {
3026 final WakeLock wakeLock = mWakeLocks.get(i);
3027 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003028 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003029 if (setWakeLockDisabledStateLocked(wakeLock)) {
3030 changed = true;
3031 if (wakeLock.mDisabled) {
3032 // This wake lock is no longer being respected.
3033 notifyWakeLockReleasedLocked(wakeLock);
3034 } else {
3035 notifyWakeLockAcquiredLocked(wakeLock);
3036 }
3037 }
3038 }
3039 }
3040 if (changed) {
3041 mDirty |= DIRTY_WAKE_LOCKS;
3042 updatePowerStateLocked();
3043 }
3044 }
3045
3046 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
3047 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3048 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003049 boolean disabled = false;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003050 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
3051 if (appid >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003052 // Cached inactive processes are never allowed to hold wake locks.
3053 if (mConstants.NO_CACHED_WAKE_LOCKS) {
3054 disabled = !wakeLock.mUidState.mActive &&
3055 wakeLock.mUidState.mProcState
3056 != ActivityManager.PROCESS_STATE_NONEXISTENT &&
3057 wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER;
3058 }
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003059 if (mDeviceIdleMode) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003060 // If we are in idle mode, we will also ignore all partial wake locks that are
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003061 // for application uids that are not whitelisted.
3062 final UidState state = wakeLock.mUidState;
3063 if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
3064 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
3065 state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003066 state.mProcState >
3067 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003068 disabled = true;
3069 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003070 }
3071 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003072 if (wakeLock.mDisabled != disabled) {
3073 wakeLock.mDisabled = disabled;
3074 return true;
3075 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003076 }
3077 return false;
3078 }
3079
Jeff Brown96307042012-07-27 15:51:34 -07003080 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3081 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
Pavel Grafov28939982017-10-03 15:11:52 +01003082 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003084
Jeff Brown96307042012-07-27 15:51:34 -07003085 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003086 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07003087 synchronized (mLock) {
3088 if (!mSystemReady) {
3089 return;
3090 }
3091 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07003092 }
Jeff Brown96307042012-07-27 15:51:34 -07003093
3094 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003095 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07003096 }
3097
Jeff Browne333e672014-10-28 13:48:55 -07003098 private void boostScreenBrightnessInternal(long eventTime, int uid) {
3099 synchronized (mLock) {
3100 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3101 || eventTime < mLastScreenBrightnessBoostTime) {
3102 return;
3103 }
3104
3105 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3106 mLastScreenBrightnessBoostTime = eventTime;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003107 if (!mScreenBrightnessBoostInProgress) {
3108 mScreenBrightnessBoostInProgress = true;
3109 mNotifier.onScreenBrightnessBoostChanged();
3110 }
Jeff Browne333e672014-10-28 13:48:55 -07003111 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3112
3113 userActivityNoUpdateLocked(eventTime,
3114 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3115 updatePowerStateLocked();
3116 }
3117 }
3118
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003119 private boolean isScreenBrightnessBoostedInternal() {
3120 synchronized (mLock) {
3121 return mScreenBrightnessBoostInProgress;
3122 }
3123 }
3124
Jeff Browne333e672014-10-28 13:48:55 -07003125 /**
3126 * Called when a screen brightness boost timeout has occurred.
3127 *
3128 * This function must have no other side-effects besides setting the dirty
3129 * bit and calling update power state.
3130 */
3131 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3132 synchronized (mLock) {
3133 if (DEBUG_SPEW) {
3134 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3135 }
3136
3137 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3138 updatePowerStateLocked();
3139 }
3140 }
3141
Jeff Brown96307042012-07-27 15:51:34 -07003142 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3143 synchronized (mLock) {
3144 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3145 mScreenBrightnessOverrideFromWindowManager = brightness;
3146 mDirty |= DIRTY_SETTINGS;
3147 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003148 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003149 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003150 }
3151
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003152 private void setUserInactiveOverrideFromWindowManagerInternal() {
3153 synchronized (mLock) {
3154 mUserInactiveOverrideFromWindowManager = true;
3155 mDirty |= DIRTY_USER_ACTIVITY;
3156 updatePowerStateLocked();
3157 }
3158 }
3159
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003160 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3161 synchronized (mLock) {
3162 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3163 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
3164 mDirty |= DIRTY_SETTINGS;
3165 updatePowerStateLocked();
3166 }
3167 }
3168 }
3169
Jeff Brown970d4132014-07-19 11:33:47 -07003170 private void setDozeOverrideFromDreamManagerInternal(
3171 int screenState, int screenBrightness) {
3172 synchronized (mLock) {
3173 if (mDozeScreenStateOverrideFromDreamManager != screenState
3174 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3175 mDozeScreenStateOverrideFromDreamManager = screenState;
3176 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
3177 mDirty |= DIRTY_SETTINGS;
3178 updatePowerStateLocked();
3179 }
3180 }
3181 }
3182
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003183 @VisibleForTesting
3184 void setVrModeEnabled(boolean enabled) {
3185 mIsVrModeEnabled = enabled;
3186 }
3187
Makoto Onukia7d8c4d2017-11-20 15:20:16 -08003188 private void powerHintInternal(int hintId, int data) {
3189 // Maybe filter the event.
3190 switch (hintId) {
3191 case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3192 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3193 return;
3194 }
3195 break;
3196 }
3197
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003198 nativeSendPowerHint(hintId, data);
3199 }
3200
Jeff Brown96307042012-07-27 15:51:34 -07003201 /**
3202 * Low-level function turn the device off immediately, without trying
3203 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07003204 *
3205 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003206 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07003207 public static void lowLevelShutdown(String reason) {
3208 if (reason == null) {
3209 reason = "";
3210 }
3211 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07003212 }
3213
3214 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08003215 * Low-level function to reboot the device. On success, this
3216 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07003217 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07003218 *
3219 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003220 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003221 public static void lowLevelReboot(String reason) {
3222 if (reason == null) {
3223 reason = "";
3224 }
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003225
3226 // If the reason is "quiescent", it means that the boot process should proceed
3227 // without turning on the screen/lights.
3228 // The "quiescent" property is sticky, meaning that any number
3229 // of subsequent reboots should honor the property until it is reset.
3230 if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3231 sQuiescent = true;
3232 reason = "";
Dmitri Plotnikov690c6bd2017-05-10 16:26:38 -07003233 } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3234 sQuiescent = true;
3235 reason = reason.substring(0,
3236 reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3237 }
3238
3239 if (reason.equals(PowerManager.REBOOT_RECOVERY)
3240 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3241 reason = "recovery";
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003242 }
3243
3244 if (sQuiescent) {
3245 // Pass the optional "quiescent" argument to the bootloader to let it know
3246 // that it should not turn the screen/lights on.
3247 reason = reason + ",quiescent";
3248 }
3249
3250 SystemProperties.set("sys.powerctl", "reboot," + reason);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003251 try {
Tao Bao90237f72015-05-21 16:25:19 -07003252 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003253 } catch (InterruptedException e) {
3254 Thread.currentThread().interrupt();
3255 }
Tao Bao90237f72015-05-21 16:25:19 -07003256 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07003257 }
3258
3259 @Override // Watchdog.Monitor implementation
3260 public void monitor() {
3261 // Grab and release lock for watchdog monitor to detect deadlocks.
3262 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003263 }
Jeff Brown96307042012-07-27 15:51:34 -07003264 }
3265
Jeff Brown6f357d32014-01-15 20:40:55 -08003266 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07003267 pw.println("POWER MANAGER (dumpsys power)\n");
3268
Jeff Brown3b971592013-01-09 18:46:37 -08003269 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07003270 synchronized (mLock) {
3271 pw.println("Power Manager State:");
Dianne Hackborn0ef403e2017-01-24 18:22:15 -08003272 mConstants.dump(pw);
Jeff Brown96307042012-07-27 15:51:34 -07003273 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08003274 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3275 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07003276 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07003277 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07003278 pw.println(" mBatteryLevel=" + mBatteryLevel);
3279 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07003280 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07003281 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07003282 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07003283 pw.println(" mBootCompleted=" + mBootCompleted);
3284 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07003285 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3286 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003287 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003288 pw.print(" mNotifyLongScheduled=");
3289 if (mNotifyLongScheduled == 0) {
3290 pw.print("(none)");
3291 } else {
3292 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3293 }
3294 pw.println();
3295 pw.print(" mNotifyLongDispatched=");
3296 if (mNotifyLongDispatched == 0) {
3297 pw.print("(none)");
3298 } else {
3299 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3300 }
3301 pw.println();
3302 pw.print(" mNotifyLongNextCheck=");
3303 if (mNotifyLongNextCheck == 0) {
3304 pw.print("(none)");
3305 } else {
3306 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3307 }
3308 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003309 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3310 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3311 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08003312 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07003313 pw.println(" mLowPowerModeEnabled=" + mLowPowerModeEnabled);
3314 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003315 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003316 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
3317 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003318 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07003319 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3320 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Jeff Brown96307042012-07-27 15:51:34 -07003321 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3322 pw.println(" mLastUserActivityTimeNoChangeLights="
3323 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07003324 pw.println(" mLastInteractivePowerHintTime="
3325 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07003326 pw.println(" mLastScreenBrightnessBoostTime="
3327 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3328 pw.println(" mScreenBrightnessBoostInProgress="
3329 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07003330 pw.println(" mDisplayReady=" + mDisplayReady);
3331 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08003332 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07003333
3334 pw.println();
3335 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07003336 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
3337 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3338 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
3339 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003340 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
3341 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07003342 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3343 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3344 pw.println(" mTheaterModeEnabled="
3345 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07003346 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
3347 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003348 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003349 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3350 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
3351 + mDreamsActivatedOnSleepByDefaultConfig);
3352 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
3353 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08003354 pw.println(" mDreamsEnabledOnBatteryConfig="
3355 + mDreamsEnabledOnBatteryConfig);
3356 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
3357 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3358 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3359 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3360 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
3361 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003362 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04003363 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07003364 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Jeff Brown2175e9c2014-09-12 16:11:07 -07003365 pw.println(" mDozeAfterScreenOffConfig=" + mDozeAfterScreenOffConfig);
Dianne Hackborn14272302014-06-10 23:13:02 -07003366 pw.println(" mLowPowerModeSetting=" + mLowPowerModeSetting);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04003367 pw.println(" mAutoLowPowerModeConfigured=" + mAutoLowPowerModeConfigured);
John Spurlock1bb480a2014-08-02 17:12:43 -04003368 pw.println(" mAutoLowPowerModeSnoozing=" + mAutoLowPowerModeSnoozing);
Jeff Brown27736f52014-05-20 17:17:10 -07003369 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3370 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3371 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003372 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07003373 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003374 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
3375 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3376 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3377 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
3378 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
3379 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
3380 pw.println(" mScreenBrightnessOverrideFromWindowManager="
3381 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003382 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
3383 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003384 pw.println(" mUserInactiveOverrideFromWindowManager="
3385 + mUserInactiveOverrideFromWindowManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003386 pw.println(" mDozeScreenStateOverrideFromDreamManager="
3387 + mDozeScreenStateOverrideFromDreamManager);
3388 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
3389 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07003390 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
3391 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
3392 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
Jason Monk27bbb2d2015-03-31 16:46:39 -04003393 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003394 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Pavel Grafov28939982017-10-03 15:11:52 +01003395 pw.println(" mForegroundProfile=" + mForegroundProfile);
Jeff Brown96307042012-07-27 15:51:34 -07003396
Pavel Grafov28939982017-10-03 15:11:52 +01003397 final long sleepTimeout = getSleepTimeoutLocked();
3398 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3399 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003400 pw.println();
Jeff Brown05af6ad2014-09-30 20:54:30 -07003401 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003402 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3403 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3404
Jeff Brown96307042012-07-27 15:51:34 -07003405 pw.println();
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003406 pw.print("UID states (changing=");
3407 pw.print(mUidsChanging);
3408 pw.print(" changed=");
3409 pw.print(mUidsChanged);
3410 pw.println("):");
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003411 for (int i=0; i<mUidState.size(); i++) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003412 final UidState state = mUidState.valueAt(i);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003413 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003414 pw.print(": ");
3415 if (state.mActive) pw.print(" ACTIVE ");
3416 else pw.print("INACTIVE ");
3417 pw.print(" count=");
3418 pw.print(state.mNumWakeLocks);
3419 pw.print(" state=");
3420 pw.println(state.mProcState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003421 }
3422
3423 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003424 pw.println("Looper state:");
3425 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3426
3427 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003428 pw.println("Wake Locks: size=" + mWakeLocks.size());
3429 for (WakeLock wl : mWakeLocks) {
3430 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003431 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003432
Jeff Brown96307042012-07-27 15:51:34 -07003433 pw.println();
3434 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3435 for (SuspendBlocker sb : mSuspendBlockers) {
3436 pw.println(" " + sb);
3437 }
3438
Jeff Brownc38c9be2012-10-04 13:16:19 -07003439 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003440 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003441
jackqdyulei455e90a2017-02-09 15:29:16 -08003442 mBatterySaverPolicy.dump(pw);
3443
Pavel Grafov28939982017-10-03 15:11:52 +01003444 pw.println();
3445 final int numProfiles = mProfilePowerState.size();
3446 pw.println("Profile power states: size=" + numProfiles);
3447 for (int i = 0; i < numProfiles; i++) {
3448 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3449 pw.print(" mUserId=");
3450 pw.print(profile.mUserId);
3451 pw.print(" mScreenOffTimeout=");
3452 pw.print(profile.mScreenOffTimeout);
3453 pw.print(" mWakeLockSummary=");
3454 pw.print(profile.mWakeLockSummary);
3455 pw.print(" mLastUserActivityTime=");
3456 pw.print(profile.mLastUserActivityTime);
3457 pw.print(" mLockingNotified=");
3458 pw.println(profile.mLockingNotified);
3459 }
3460
Jeff Brown3b971592013-01-09 18:46:37 -08003461 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003462 }
3463
Jeff Brown3b971592013-01-09 18:46:37 -08003464 if (wcd != null) {
3465 wcd.dump(pw);
3466 }
Jeff Brown96307042012-07-27 15:51:34 -07003467 }
3468
Netta P958d0a52017-02-07 11:20:55 -08003469 private void dumpProto(FileDescriptor fd) {
3470 final WirelessChargerDetector wcd;
3471 final ProtoOutputStream proto = new ProtoOutputStream(fd);
3472
3473 synchronized (mLock) {
3474 mConstants.dumpProto(proto);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003475 proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3476 proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3477 proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3478 proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3479 proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3480 proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
Netta P958d0a52017-02-07 11:20:55 -08003481 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003482 PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
Netta P958d0a52017-02-07 11:20:55 -08003483 mBatteryLevelWhenDreamStarted);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003484 proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3485 proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3486 proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3487 proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3488 proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
Netta P958d0a52017-02-07 11:20:55 -08003489 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003490 PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003491 mHalAutoSuspendModeEnabled);
3492 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003493 PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003494 mHalInteractiveModeEnabled);
3495
Kweku Adamse6b00c22017-10-23 16:46:45 -07003496 final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003497 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003498 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
Netta P958d0a52017-02-07 11:20:55 -08003499 (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3500 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003501 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003502 (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3503 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003504 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003505 (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3506 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003507 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003508 (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3509 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003510 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
Netta P958d0a52017-02-07 11:20:55 -08003511 (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3512 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003513 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
Netta P958d0a52017-02-07 11:20:55 -08003514 (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3515 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003516 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
Netta P958d0a52017-02-07 11:20:55 -08003517 (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3518 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003519 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
Netta P958d0a52017-02-07 11:20:55 -08003520 (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3521 proto.end(activeWakeLocksToken);
3522
Kweku Adamse6b00c22017-10-23 16:46:45 -07003523 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3524 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3525 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
Netta P958d0a52017-02-07 11:20:55 -08003526
Kweku Adamse6b00c22017-10-23 16:46:45 -07003527 final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
Netta P958d0a52017-02-07 11:20:55 -08003528 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003529 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003530 (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3531 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003532 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003533 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3534 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003535 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
Netta P958d0a52017-02-07 11:20:55 -08003536 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
3537 proto.end(userActivityToken);
3538
3539 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003540 PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
Netta P958d0a52017-02-07 11:20:55 -08003541 mRequestWaitForNegativeProximity);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003542 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
3543 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
3544 proto.write(PowerManagerServiceDumpProto.IS_LOW_POWER_MODE_ENABLED, mLowPowerModeEnabled);
3545 proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
3546 proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
3547 proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
Netta P958d0a52017-02-07 11:20:55 -08003548
3549 for (int id : mDeviceIdleWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003550 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003551 }
3552 for (int id : mDeviceIdleTempWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003553 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003554 }
3555
Kweku Adamse6b00c22017-10-23 16:46:45 -07003556 proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
3557 proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
3558 proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
Netta P958d0a52017-02-07 11:20:55 -08003559 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003560 PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
Netta P958d0a52017-02-07 11:20:55 -08003561 mLastUserActivityTimeNoChangeLights);
3562 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003563 PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003564 mLastInteractivePowerHintTime);
3565 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003566 PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003567 mLastScreenBrightnessBoostTime);
3568 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003569 PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
Netta P958d0a52017-02-07 11:20:55 -08003570 mScreenBrightnessBoostInProgress);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003571 proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
Netta P958d0a52017-02-07 11:20:55 -08003572 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003573 PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003574 mHoldingWakeLockSuspendBlocker);
3575 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003576 PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003577 mHoldingDisplaySuspendBlocker);
3578
3579 final long settingsAndConfigurationToken =
Kweku Adamse6b00c22017-10-23 16:46:45 -07003580 proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
Netta P958d0a52017-02-07 11:20:55 -08003581 proto.write(
3582 PowerServiceSettingsAndConfigurationDumpProto
3583 .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
3584 mDecoupleHalAutoSuspendModeFromDisplayConfig);
3585 proto.write(
3586 PowerServiceSettingsAndConfigurationDumpProto
3587 .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
3588 mDecoupleHalInteractiveModeFromDisplayConfig);
3589 proto.write(
3590 PowerServiceSettingsAndConfigurationDumpProto
3591 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
3592 mWakeUpWhenPluggedOrUnpluggedConfig);
3593 proto.write(
3594 PowerServiceSettingsAndConfigurationDumpProto
3595 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
3596 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3597 proto.write(
3598 PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
3599 mTheaterModeEnabled);
3600 proto.write(
3601 PowerServiceSettingsAndConfigurationDumpProto
3602 .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
3603 mSuspendWhenScreenOffDueToProximityConfig);
3604 proto.write(
3605 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
3606 mDreamsSupportedConfig);
3607 proto.write(
3608 PowerServiceSettingsAndConfigurationDumpProto
3609 .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
3610 mDreamsEnabledByDefaultConfig);
3611 proto.write(
3612 PowerServiceSettingsAndConfigurationDumpProto
3613 .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
3614 mDreamsActivatedOnSleepByDefaultConfig);
3615 proto.write(
3616 PowerServiceSettingsAndConfigurationDumpProto
3617 .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
3618 mDreamsActivatedOnDockByDefaultConfig);
3619 proto.write(
3620 PowerServiceSettingsAndConfigurationDumpProto
3621 .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
3622 mDreamsEnabledOnBatteryConfig);
3623 proto.write(
3624 PowerServiceSettingsAndConfigurationDumpProto
3625 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
3626 mDreamsBatteryLevelMinimumWhenPoweredConfig);
3627 proto.write(
3628 PowerServiceSettingsAndConfigurationDumpProto
3629 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
3630 mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3631 proto.write(
3632 PowerServiceSettingsAndConfigurationDumpProto
3633 .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
3634 mDreamsBatteryLevelDrainCutoffConfig);
3635 proto.write(
3636 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
3637 mDreamsEnabledSetting);
3638 proto.write(
3639 PowerServiceSettingsAndConfigurationDumpProto
3640 .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
3641 mDreamsActivateOnSleepSetting);
3642 proto.write(
3643 PowerServiceSettingsAndConfigurationDumpProto
3644 .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
3645 mDreamsActivateOnDockSetting);
3646 proto.write(
3647 PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
3648 mDozeAfterScreenOffConfig);
3649 proto.write(
3650 PowerServiceSettingsAndConfigurationDumpProto.IS_LOW_POWER_MODE_SETTING,
3651 mLowPowerModeSetting);
3652 proto.write(
3653 PowerServiceSettingsAndConfigurationDumpProto.IS_AUTO_LOW_POWER_MODE_CONFIGURED,
3654 mAutoLowPowerModeConfigured);
3655 proto.write(
3656 PowerServiceSettingsAndConfigurationDumpProto.IS_AUTO_LOW_POWER_MODE_SNOOZING,
3657 mAutoLowPowerModeSnoozing);
3658 proto.write(
3659 PowerServiceSettingsAndConfigurationDumpProto
3660 .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
3661 mMinimumScreenOffTimeoutConfig);
3662 proto.write(
3663 PowerServiceSettingsAndConfigurationDumpProto
3664 .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
3665 mMaximumScreenDimDurationConfig);
3666 proto.write(
3667 PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
3668 mMaximumScreenDimRatioConfig);
3669 proto.write(
3670 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
3671 mScreenOffTimeoutSetting);
3672 proto.write(
3673 PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
3674 mSleepTimeoutSetting);
3675 proto.write(
3676 PowerServiceSettingsAndConfigurationDumpProto
3677 .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
Pavel Grafov28939982017-10-03 15:11:52 +01003678 // Clamp to int32
3679 Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
Netta P958d0a52017-02-07 11:20:55 -08003680 proto.write(
3681 PowerServiceSettingsAndConfigurationDumpProto
3682 .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
3683 isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
3684
3685 final long stayOnWhilePluggedInToken =
3686 proto.start(
3687 PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
3688 proto.write(
3689 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3690 .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
3691 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
3692 proto.write(
3693 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3694 .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
3695 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
3696 proto.write(
3697 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3698 .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
3699 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
3700 != 0));
3701 proto.end(stayOnWhilePluggedInToken);
3702
3703 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003704 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
3705 mScreenBrightnessModeSetting);
3706 proto.write(
3707 PowerServiceSettingsAndConfigurationDumpProto
3708 .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
3709 mScreenBrightnessOverrideFromWindowManager);
3710 proto.write(
3711 PowerServiceSettingsAndConfigurationDumpProto
3712 .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
3713 mUserActivityTimeoutOverrideFromWindowManager);
3714 proto.write(
3715 PowerServiceSettingsAndConfigurationDumpProto
3716 .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
3717 mUserInactiveOverrideFromWindowManager);
3718 proto.write(
3719 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003720 .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
3721 mDozeScreenStateOverrideFromDreamManager);
3722 proto.write(
3723 PowerServiceSettingsAndConfigurationDumpProto
3724 .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
3725 mDozeScreenBrightnessOverrideFromDreamManager);
3726
3727 final long screenBrightnessSettingLimitsToken =
3728 proto.start(
3729 PowerServiceSettingsAndConfigurationDumpProto
3730 .SCREEN_BRIGHTNESS_SETTING_LIMITS);
3731 proto.write(
3732 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3733 .SETTING_MINIMUM,
3734 mScreenBrightnessSettingMinimum);
3735 proto.write(
3736 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3737 .SETTING_MAXIMUM,
3738 mScreenBrightnessSettingMaximum);
3739 proto.write(
3740 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3741 .SETTING_DEFAULT,
3742 mScreenBrightnessSettingDefault);
Netta P958d0a52017-02-07 11:20:55 -08003743 proto.end(screenBrightnessSettingLimitsToken);
3744
3745 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003746 PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
3747 mDoubleTapWakeEnabled);
3748 proto.write(
3749 PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
3750 mIsVrModeEnabled);
3751 proto.end(settingsAndConfigurationToken);
3752
Pavel Grafov28939982017-10-03 15:11:52 +01003753 final long sleepTimeout = getSleepTimeoutLocked();
3754 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3755 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003756 proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
3757 proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
3758 proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
3759 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
3760 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
Netta P958d0a52017-02-07 11:20:55 -08003761
3762 for (int i = 0; i < mUidState.size(); i++) {
3763 final UidState state = mUidState.valueAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003764 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
Netta P958d0a52017-02-07 11:20:55 -08003765 final int uid = mUidState.keyAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003766 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
3767 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
3768 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
3769 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
Bookatzdb026a22018-01-10 19:01:56 -08003770 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
3771 ActivityManager.processStateAmToProto(state.mProcState));
Netta P958d0a52017-02-07 11:20:55 -08003772 proto.end(uIDToken);
3773 }
3774
Kweku Adamse6b00c22017-10-23 16:46:45 -07003775 mHandler.getLooper().writeToProto(proto, PowerManagerServiceDumpProto.LOOPER);
Netta P958d0a52017-02-07 11:20:55 -08003776
3777 for (WakeLock wl : mWakeLocks) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003778 wl.writeToProto(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003779 }
3780
3781 for (SuspendBlocker sb : mSuspendBlockers) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003782 sb.writeToProto(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
Netta P958d0a52017-02-07 11:20:55 -08003783 }
3784 wcd = mWirelessChargerDetector;
3785 }
3786
3787 if (wcd != null) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003788 wcd.writeToProto(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
Netta P958d0a52017-02-07 11:20:55 -08003789 }
3790 proto.flush();
3791 }
3792
Jeff Brown96307042012-07-27 15:51:34 -07003793 private SuspendBlocker createSuspendBlockerLocked(String name) {
3794 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
3795 mSuspendBlockers.add(suspendBlocker);
3796 return suspendBlocker;
3797 }
3798
Daichi Hirono82ab9802016-03-02 13:23:29 +09003799 private void incrementBootCount() {
3800 synchronized (mLock) {
3801 int count;
3802 try {
3803 count = Settings.Global.getInt(
3804 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
3805 } catch (SettingNotFoundException e) {
3806 count = 0;
3807 }
3808 Settings.Global.putInt(
3809 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
3810 }
3811 }
3812
Jeff Brown96307042012-07-27 15:51:34 -07003813 private static WorkSource copyWorkSource(WorkSource workSource) {
3814 return workSource != null ? new WorkSource(workSource) : null;
3815 }
3816
3817 private final class BatteryReceiver extends BroadcastReceiver {
3818 @Override
3819 public void onReceive(Context context, Intent intent) {
3820 synchronized (mLock) {
3821 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003822 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003823 }
3824 }
3825
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003826 private final class DreamReceiver extends BroadcastReceiver {
3827 @Override
3828 public void onReceive(Context context, Intent intent) {
3829 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07003830 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003831 }
3832 }
3833 }
3834
Jeff Brownd4935962012-09-25 13:27:20 -07003835 private final class UserSwitchedReceiver extends BroadcastReceiver {
3836 @Override
3837 public void onReceive(Context context, Intent intent) {
3838 synchronized (mLock) {
3839 handleSettingsChangedLocked();
3840 }
3841 }
3842 }
3843
Jeff Brownec6aa592012-10-17 20:30:25 -07003844 private final class DockReceiver extends BroadcastReceiver {
3845 @Override
3846 public void onReceive(Context context, Intent intent) {
3847 synchronized (mLock) {
3848 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3849 Intent.EXTRA_DOCK_STATE_UNDOCKED);
3850 if (mDockState != dockState) {
3851 mDockState = dockState;
3852 mDirty |= DIRTY_DOCK_STATE;
3853 updatePowerStateLocked();
3854 }
3855 }
3856 }
3857 }
3858
Jeff Brown96307042012-07-27 15:51:34 -07003859 private final class SettingsObserver extends ContentObserver {
3860 public SettingsObserver(Handler handler) {
3861 super(handler);
3862 }
3863
3864 @Override
3865 public void onChange(boolean selfChange, Uri uri) {
3866 synchronized (mLock) {
3867 handleSettingsChangedLocked();
3868 }
3869 }
3870 }
3871
Ruben Brunkc7be3be2016-04-01 17:07:51 -07003872 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003873 @Override
3874 public void onVrStateChanged(boolean enabled) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07003875 powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
Santos Cordon3107d292016-09-20 15:50:35 -07003876
3877 synchronized (mLock) {
3878 if (mIsVrModeEnabled != enabled) {
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003879 setVrModeEnabled(enabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003880 mDirty |= DIRTY_VR_MODE_CHANGED;
3881 updatePowerStateLocked();
3882 }
3883 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003884 }
3885 };
3886
Jeff Brown96307042012-07-27 15:51:34 -07003887 /**
3888 * Handler for asynchronous operations performed by the power manager.
3889 */
3890 private final class PowerManagerHandler extends Handler {
3891 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07003892 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07003893 }
3894
3895 @Override
3896 public void handleMessage(Message msg) {
3897 switch (msg.what) {
3898 case MSG_USER_ACTIVITY_TIMEOUT:
3899 handleUserActivityTimeout();
3900 break;
3901 case MSG_SANDMAN:
3902 handleSandman();
3903 break;
Jeff Browne333e672014-10-28 13:48:55 -07003904 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
3905 handleScreenBrightnessBoostTimeout();
3906 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003907 case MSG_CHECK_FOR_LONG_WAKELOCKS:
3908 checkForLongWakeLocks();
3909 break;
Jeff Brown96307042012-07-27 15:51:34 -07003910 }
3911 }
3912 }
3913
3914 /**
3915 * Represents a wake lock that has been acquired by an application.
3916 */
3917 private final class WakeLock implements IBinder.DeathRecipient {
3918 public final IBinder mLock;
3919 public int mFlags;
3920 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003921 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07003922 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003923 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003924 public final int mOwnerUid;
3925 public final int mOwnerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003926 public final UidState mUidState;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003927 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07003928 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003929 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003930 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07003931
Dianne Hackborn713df152013-05-17 11:27:57 -07003932 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003933 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
3934 UidState uidState) {
Jeff Brown96307042012-07-27 15:51:34 -07003935 mLock = lock;
3936 mFlags = flags;
3937 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003938 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07003939 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003940 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07003941 mOwnerUid = ownerUid;
3942 mOwnerPid = ownerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003943 mUidState = uidState;
Jeff Brown96307042012-07-27 15:51:34 -07003944 }
3945
3946 @Override
3947 public void binderDied() {
3948 PowerManagerService.this.handleWakeLockDeath(this);
3949 }
3950
3951 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
3952 int ownerUid, int ownerPid) {
3953 return mFlags == flags
3954 && mTag.equals(tag)
3955 && hasSameWorkSource(workSource)
3956 && mOwnerUid == ownerUid
3957 && mOwnerPid == ownerPid;
3958 }
3959
Dianne Hackborn713df152013-05-17 11:27:57 -07003960 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003961 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07003962 if (!mPackageName.equals(packageName)) {
3963 throw new IllegalStateException("Existing wake lock package name changed: "
3964 + mPackageName + " to " + packageName);
3965 }
3966 if (mOwnerUid != ownerUid) {
3967 throw new IllegalStateException("Existing wake lock uid changed: "
3968 + mOwnerUid + " to " + ownerUid);
3969 }
3970 if (mOwnerPid != ownerPid) {
3971 throw new IllegalStateException("Existing wake lock pid changed: "
3972 + mOwnerPid + " to " + ownerPid);
3973 }
Jeff Brown96307042012-07-27 15:51:34 -07003974 mFlags = flags;
3975 mTag = tag;
3976 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003977 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07003978 }
3979
3980 public boolean hasSameWorkSource(WorkSource workSource) {
3981 return Objects.equal(mWorkSource, workSource);
3982 }
3983
3984 public void updateWorkSource(WorkSource workSource) {
3985 mWorkSource = copyWorkSource(workSource);
3986 }
3987
3988 @Override
3989 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003990 StringBuilder sb = new StringBuilder();
3991 sb.append(getLockLevelString());
3992 sb.append(" '");
3993 sb.append(mTag);
3994 sb.append("'");
3995 sb.append(getLockFlagsString());
3996 if (mDisabled) {
3997 sb.append(" DISABLED");
3998 }
3999 if (mNotifiedAcquired) {
4000 sb.append(" ACQ=");
4001 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
4002 }
4003 if (mNotifiedLong) {
4004 sb.append(" LONG");
4005 }
4006 sb.append(" (uid=");
4007 sb.append(mOwnerUid);
4008 if (mOwnerPid != 0) {
4009 sb.append(" pid=");
4010 sb.append(mOwnerPid);
4011 }
4012 if (mWorkSource != null) {
4013 sb.append(" ws=");
4014 sb.append(mWorkSource);
4015 }
4016 sb.append(")");
4017 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07004018 }
4019
Netta P958d0a52017-02-07 11:20:55 -08004020 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4021 final long wakeLockToken = proto.start(fieldId);
4022 proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
4023 proto.write(WakeLockProto.TAG, mTag);
4024
4025 final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
4026 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
4027 (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
4028 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
4029 (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
4030 proto.end(wakeLockFlagsToken);
4031
4032 proto.write(WakeLockProto.IS_DISABLED, mDisabled);
4033 if (mNotifiedAcquired) {
4034 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
4035 }
4036 proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
4037 proto.write(WakeLockProto.UID, mOwnerUid);
4038 proto.write(WakeLockProto.PID, mOwnerPid);
4039
4040 if (mWorkSource != null) {
4041 mWorkSource.writeToProto(proto, WakeLockProto.WORK_SOURCE);
4042 }
4043 proto.end(wakeLockToken);
4044 }
4045
Jeff Brown26875502014-01-30 21:47:47 -08004046 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07004047 private String getLockLevelString() {
4048 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
4049 case PowerManager.FULL_WAKE_LOCK:
4050 return "FULL_WAKE_LOCK ";
4051 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
4052 return "SCREEN_BRIGHT_WAKE_LOCK ";
4053 case PowerManager.SCREEN_DIM_WAKE_LOCK:
4054 return "SCREEN_DIM_WAKE_LOCK ";
4055 case PowerManager.PARTIAL_WAKE_LOCK:
4056 return "PARTIAL_WAKE_LOCK ";
4057 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4058 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08004059 case PowerManager.DOZE_WAKE_LOCK:
4060 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08004061 case PowerManager.DRAW_WAKE_LOCK:
4062 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07004063 default:
4064 return "??? ";
4065 }
4066 }
4067
4068 private String getLockFlagsString() {
4069 String result = "";
4070 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4071 result += " ACQUIRE_CAUSES_WAKEUP";
4072 }
4073 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4074 result += " ON_AFTER_RELEASE";
4075 }
4076 return result;
4077 }
4078 }
4079
4080 private final class SuspendBlockerImpl implements SuspendBlocker {
4081 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07004082 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07004083 private int mReferenceCount;
4084
4085 public SuspendBlockerImpl(String name) {
4086 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07004087 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07004088 }
4089
4090 @Override
4091 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004092 try {
Jeff Brown96307042012-07-27 15:51:34 -07004093 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004094 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004095 + "\" was finalized without being released!");
4096 mReferenceCount = 0;
4097 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004098 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004099 }
4100 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07004101 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004102 }
4103 }
4104
Craig Mautner75fc9de2012-06-18 16:53:27 -07004105 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004106 public void acquire() {
4107 synchronized (this) {
4108 mReferenceCount += 1;
4109 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004110 if (DEBUG_SPEW) {
4111 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4112 }
Jeff Brown3edf5272014-08-14 19:25:14 -07004113 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004114 nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07004115 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004116 }
4117 }
4118
Craig Mautner75fc9de2012-06-18 16:53:27 -07004119 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004120 public void release() {
4121 synchronized (this) {
4122 mReferenceCount -= 1;
4123 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004124 if (DEBUG_SPEW) {
4125 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4126 }
Jeff Brown96307042012-07-27 15:51:34 -07004127 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004128 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004129 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004130 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004131 + "\" was released without being acquired!", new Throwable());
4132 mReferenceCount = 0;
4133 }
4134 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004135 }
Jeff Brown96307042012-07-27 15:51:34 -07004136
4137 @Override
4138 public String toString() {
4139 synchronized (this) {
4140 return mName + ": ref count=" + mReferenceCount;
4141 }
4142 }
Netta P958d0a52017-02-07 11:20:55 -08004143
4144 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4145 final long sbToken = proto.start(fieldId);
4146 synchronized (this) {
4147 proto.write(SuspendBlockerProto.NAME, mName);
4148 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4149 }
4150 proto.end(sbToken);
4151 }
Jeff Brown96307042012-07-27 15:51:34 -07004152 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07004153
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004154 static final class UidState {
4155 final int mUid;
4156 int mNumWakeLocks;
4157 int mProcState;
4158 boolean mActive;
4159
4160 UidState(int uid) {
4161 mUid = uid;
4162 }
4163 }
4164
Jeff Brown6f357d32014-01-15 20:40:55 -08004165 private final class BinderService extends IPowerManager.Stub {
Jocelyn Dangf2c38c12017-03-31 14:03:37 -07004166 @Override
4167 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4168 FileDescriptor err, String[] args, ShellCallback callback,
4169 ResultReceiver resultReceiver) {
4170 (new PowerManagerShellCommand(this)).exec(
4171 this, in, out, err, args, callback, resultReceiver);
4172 }
4173
Jeff Brown6f357d32014-01-15 20:40:55 -08004174 @Override // Binder call
4175 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4176 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07004177 if (uid < 0) {
4178 uid = Binder.getCallingUid();
4179 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004180 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004181 }
4182
4183 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004184 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07004185 if (!mSystemReady) {
4186 // Service not ready yet, so who the heck cares about power hints, bah.
4187 return;
4188 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004189 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07004190 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004191 }
4192
4193 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004194 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004195 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004196 if (lock == null) {
4197 throw new IllegalArgumentException("lock must not be null");
4198 }
4199 if (packageName == null) {
4200 throw new IllegalArgumentException("packageName must not be null");
4201 }
4202 PowerManager.validateWakeLockParameters(flags, tag);
4203
4204 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07004205 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4206 mContext.enforceCallingOrSelfPermission(
4207 android.Manifest.permission.DEVICE_POWER, null);
4208 }
Narayan Kamath81822022017-12-08 11:56:01 +00004209 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004210 mContext.enforceCallingOrSelfPermission(
4211 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4212 } else {
4213 ws = null;
4214 }
4215
4216 final int uid = Binder.getCallingUid();
4217 final int pid = Binder.getCallingPid();
4218 final long ident = Binder.clearCallingIdentity();
4219 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004220 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004221 } finally {
4222 Binder.restoreCallingIdentity(ident);
4223 }
4224 }
4225
4226 @Override // Binder call
4227 public void releaseWakeLock(IBinder lock, int flags) {
4228 if (lock == null) {
4229 throw new IllegalArgumentException("lock must not be null");
4230 }
4231
4232 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4233
4234 final long ident = Binder.clearCallingIdentity();
4235 try {
4236 releaseWakeLockInternal(lock, flags);
4237 } finally {
4238 Binder.restoreCallingIdentity(ident);
4239 }
4240 }
4241
4242 @Override // Binder call
4243 public void updateWakeLockUids(IBinder lock, int[] uids) {
4244 WorkSource ws = null;
4245
4246 if (uids != null) {
4247 ws = new WorkSource();
4248 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4249 // one at a time?
4250 for (int i = 0; i < uids.length; i++) {
4251 ws.add(uids[i]);
4252 }
4253 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07004254 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004255 }
4256
4257 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07004258 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004259 if (lock == null) {
4260 throw new IllegalArgumentException("lock must not be null");
4261 }
4262
4263 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Narayan Kamath81822022017-12-08 11:56:01 +00004264 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004265 mContext.enforceCallingOrSelfPermission(
4266 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4267 } else {
4268 ws = null;
4269 }
4270
Dianne Hackbornd953c532014-08-16 18:17:38 -07004271 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004272 final long ident = Binder.clearCallingIdentity();
4273 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07004274 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004275 } finally {
4276 Binder.restoreCallingIdentity(ident);
4277 }
4278 }
4279
4280 @Override // Binder call
4281 public boolean isWakeLockLevelSupported(int level) {
4282 final long ident = Binder.clearCallingIdentity();
4283 try {
4284 return isWakeLockLevelSupportedInternal(level);
4285 } finally {
4286 Binder.restoreCallingIdentity(ident);
4287 }
4288 }
4289
4290 @Override // Binder call
4291 public void userActivity(long eventTime, int event, int flags) {
4292 final long now = SystemClock.uptimeMillis();
4293 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07004294 != PackageManager.PERMISSION_GRANTED
4295 && mContext.checkCallingOrSelfPermission(
4296 android.Manifest.permission.USER_ACTIVITY)
4297 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004298 // Once upon a time applications could call userActivity().
4299 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
4300 // request instead of throwing a SecurityException so we don't break old apps.
4301 synchronized (mLock) {
4302 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4303 mLastWarningAboutUserActivityPermission = now;
4304 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07004305 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4306 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08004307 + " pid=" + Binder.getCallingPid()
4308 + " uid=" + Binder.getCallingUid());
4309 }
4310 }
4311 return;
4312 }
4313
Jim Millerdca15d22015-06-16 20:55:13 -07004314 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004315 throw new IllegalArgumentException("event time must not be in the future");
4316 }
4317
4318 final int uid = Binder.getCallingUid();
4319 final long ident = Binder.clearCallingIdentity();
4320 try {
4321 userActivityInternal(eventTime, event, flags, uid);
4322 } finally {
4323 Binder.restoreCallingIdentity(ident);
4324 }
4325 }
4326
4327 @Override // Binder call
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004328 public void wakeUp(long eventTime, String reason, String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004329 if (eventTime > SystemClock.uptimeMillis()) {
4330 throw new IllegalArgumentException("event time must not be in the future");
4331 }
4332
4333 mContext.enforceCallingOrSelfPermission(
4334 android.Manifest.permission.DEVICE_POWER, null);
4335
Jeff Brownc12035c2014-08-13 18:52:25 -07004336 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004337 final long ident = Binder.clearCallingIdentity();
4338 try {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004339 wakeUpInternal(eventTime, reason, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004340 } finally {
4341 Binder.restoreCallingIdentity(ident);
4342 }
4343 }
4344
4345 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07004346 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004347 if (eventTime > SystemClock.uptimeMillis()) {
4348 throw new IllegalArgumentException("event time must not be in the future");
4349 }
4350
4351 mContext.enforceCallingOrSelfPermission(
4352 android.Manifest.permission.DEVICE_POWER, null);
4353
Jeff Brownc12035c2014-08-13 18:52:25 -07004354 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004355 final long ident = Binder.clearCallingIdentity();
4356 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004357 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004358 } finally {
4359 Binder.restoreCallingIdentity(ident);
4360 }
4361 }
4362
4363 @Override // Binder call
4364 public void nap(long eventTime) {
4365 if (eventTime > SystemClock.uptimeMillis()) {
4366 throw new IllegalArgumentException("event time must not be in the future");
4367 }
4368
4369 mContext.enforceCallingOrSelfPermission(
4370 android.Manifest.permission.DEVICE_POWER, null);
4371
Jeff Brownc12035c2014-08-13 18:52:25 -07004372 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004373 final long ident = Binder.clearCallingIdentity();
4374 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004375 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004376 } finally {
4377 Binder.restoreCallingIdentity(ident);
4378 }
4379 }
4380
4381 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07004382 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08004383 final long ident = Binder.clearCallingIdentity();
4384 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07004385 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08004386 } finally {
4387 Binder.restoreCallingIdentity(ident);
4388 }
4389 }
4390
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004391 @Override // Binder call
4392 public boolean isPowerSaveMode() {
4393 final long ident = Binder.clearCallingIdentity();
4394 try {
4395 return isLowPowerModeInternal();
4396 } finally {
4397 Binder.restoreCallingIdentity(ident);
4398 }
4399 }
4400
jackqdyulei455e90a2017-02-09 15:29:16 -08004401 // Binder call
4402 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4403 final long ident = Binder.clearCallingIdentity();
4404 try {
4405 synchronized (mLock) {
4406 return mBatterySaverPolicy.getBatterySaverPolicy(
4407 serviceType, isLowPowerModeInternal());
4408 }
4409 } finally {
4410 Binder.restoreCallingIdentity(ident);
4411 }
4412 }
4413
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004414 @Override // Binder call
4415 public boolean setPowerSaveMode(boolean mode) {
4416 mContext.enforceCallingOrSelfPermission(
4417 android.Manifest.permission.DEVICE_POWER, null);
4418 final long ident = Binder.clearCallingIdentity();
4419 try {
4420 return setLowPowerModeInternal(mode);
4421 } finally {
4422 Binder.restoreCallingIdentity(ident);
4423 }
4424 }
4425
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004426 @Override // Binder call
4427 public boolean isDeviceIdleMode() {
4428 final long ident = Binder.clearCallingIdentity();
4429 try {
4430 return isDeviceIdleModeInternal();
4431 } finally {
4432 Binder.restoreCallingIdentity(ident);
4433 }
4434 }
4435
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004436 @Override // Binder call
4437 public boolean isLightDeviceIdleMode() {
4438 final long ident = Binder.clearCallingIdentity();
4439 try {
4440 return isLightDeviceIdleModeInternal();
4441 } finally {
4442 Binder.restoreCallingIdentity(ident);
4443 }
4444 }
4445
Jeff Brown6f357d32014-01-15 20:40:55 -08004446 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07004447 * Gets the reason for the last time the phone had to reboot.
4448 *
4449 * @return The reason the phone last shut down as an int or
Makoto Onuki66a78122017-11-14 15:03:21 -08004450 * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
Salvador Martineza6f7b252017-04-10 10:46:15 -07004451 */
4452 @Override // Binder call
4453 public int getLastShutdownReason() {
4454 mContext.enforceCallingOrSelfPermission(
4455 android.Manifest.permission.DEVICE_POWER, null);
4456
4457 final long ident = Binder.clearCallingIdentity();
4458 try {
Mark Salyzyne65c0c62017-08-15 07:53:47 -07004459 return getLastShutdownReasonInternal(LAST_REBOOT_PROPERTY);
Salvador Martineza6f7b252017-04-10 10:46:15 -07004460 } finally {
4461 Binder.restoreCallingIdentity(ident);
4462 }
4463 }
4464
4465 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004466 * Reboots the device.
4467 *
4468 * @param confirm If true, shows a reboot confirmation dialog.
4469 * @param reason The reason for the reboot, or null if none.
4470 * @param wait If true, this call waits for the reboot to complete and does not return.
4471 */
4472 @Override // Binder call
4473 public void reboot(boolean confirm, String reason, boolean wait) {
4474 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08004475 if (PowerManager.REBOOT_RECOVERY.equals(reason)
4476 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08004477 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
4478 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004479
4480 final long ident = Binder.clearCallingIdentity();
4481 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004482 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
4483 } finally {
4484 Binder.restoreCallingIdentity(ident);
4485 }
4486 }
4487
4488 /**
4489 * Reboots the device into safe mode
4490 *
4491 * @param confirm If true, shows a reboot confirmation dialog.
4492 * @param wait If true, this call waits for the reboot to complete and does not return.
4493 */
4494 @Override // Binder call
4495 public void rebootSafeMode(boolean confirm, boolean wait) {
4496 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4497
4498 final long ident = Binder.clearCallingIdentity();
4499 try {
4500 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
4501 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004502 } finally {
4503 Binder.restoreCallingIdentity(ident);
4504 }
4505 }
4506
4507 /**
4508 * Shuts down the device.
4509 *
4510 * @param confirm If true, shows a shutdown confirmation dialog.
4511 * @param wait If true, this call waits for the shutdown to complete and does not return.
4512 */
4513 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07004514 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004515 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4516
4517 final long ident = Binder.clearCallingIdentity();
4518 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004519 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004520 } finally {
4521 Binder.restoreCallingIdentity(ident);
4522 }
4523 }
4524
4525 /**
4526 * Crash the runtime (causing a complete restart of the Android framework).
4527 * Requires REBOOT permission. Mostly for testing. Should not return.
4528 */
4529 @Override // Binder call
4530 public void crash(String message) {
4531 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4532
4533 final long ident = Binder.clearCallingIdentity();
4534 try {
4535 crashInternal(message);
4536 } finally {
4537 Binder.restoreCallingIdentity(ident);
4538 }
4539 }
4540
4541 /**
4542 * Set the setting that determines whether the device stays on when plugged in.
4543 * The argument is a bit string, with each bit specifying a power source that,
4544 * when the device is connected to that source, causes the device to stay on.
4545 * See {@link android.os.BatteryManager} for the list of power sources that
4546 * can be specified. Current values include
4547 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
4548 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
4549 *
4550 * Used by "adb shell svc power stayon ..."
4551 *
4552 * @param val an {@code int} containing the bits that specify which power sources
4553 * should cause the device to stay on.
4554 */
4555 @Override // Binder call
4556 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01004557 int uid = Binder.getCallingUid();
4558 // if uid is of root's, we permit this operation straight away
4559 if (uid != Process.ROOT_UID) {
4560 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
4561 Settings.getPackageNameForUid(mContext, uid), true)) {
4562 return;
4563 }
4564 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004565
4566 final long ident = Binder.clearCallingIdentity();
4567 try {
4568 setStayOnSettingInternal(val);
4569 } finally {
4570 Binder.restoreCallingIdentity(ident);
4571 }
4572 }
4573
4574 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004575 * Used by the phone application to make the attention LED flash when ringing.
4576 */
4577 @Override // Binder call
4578 public void setAttentionLight(boolean on, int color) {
4579 mContext.enforceCallingOrSelfPermission(
4580 android.Manifest.permission.DEVICE_POWER, null);
4581
4582 final long ident = Binder.clearCallingIdentity();
4583 try {
4584 setAttentionLightInternal(on, color);
4585 } finally {
4586 Binder.restoreCallingIdentity(ident);
4587 }
4588 }
4589
4590 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07004591 public void boostScreenBrightness(long eventTime) {
4592 if (eventTime > SystemClock.uptimeMillis()) {
4593 throw new IllegalArgumentException("event time must not be in the future");
4594 }
4595
4596 mContext.enforceCallingOrSelfPermission(
4597 android.Manifest.permission.DEVICE_POWER, null);
4598
4599 final int uid = Binder.getCallingUid();
4600 final long ident = Binder.clearCallingIdentity();
4601 try {
4602 boostScreenBrightnessInternal(eventTime, uid);
4603 } finally {
4604 Binder.restoreCallingIdentity(ident);
4605 }
4606 }
4607
4608 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004609 public boolean isScreenBrightnessBoosted() {
4610 final long ident = Binder.clearCallingIdentity();
4611 try {
4612 return isScreenBrightnessBoostedInternal();
4613 } finally {
4614 Binder.restoreCallingIdentity(ident);
4615 }
4616 }
4617
4618 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004619 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004620 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown6f357d32014-01-15 20:40:55 -08004621
4622 final long ident = Binder.clearCallingIdentity();
Netta P958d0a52017-02-07 11:20:55 -08004623
4624 boolean isDumpProto = false;
4625 for (String arg : args) {
4626 if (arg.equals("--proto")) {
4627 isDumpProto = true;
4628 }
4629 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004630 try {
Netta P958d0a52017-02-07 11:20:55 -08004631 if (isDumpProto) {
4632 dumpProto(fd);
4633 } else {
4634 dumpInternal(pw);
4635 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004636 } finally {
4637 Binder.restoreCallingIdentity(ident);
4638 }
4639 }
4640 }
4641
Salvador Martineza6f7b252017-04-10 10:46:15 -07004642 @VisibleForTesting
Mark Salyzyne65c0c62017-08-15 07:53:47 -07004643 // lastRebootReasonProperty argument to permit testing
4644 int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
4645 String line = SystemProperties.get(lastRebootReasonProperty);
Michael Wright9199d0c2017-05-10 21:35:13 +01004646 if (line == null) {
4647 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4648 }
Salvador Martineza6f7b252017-04-10 10:46:15 -07004649 switch (line) {
4650 case REASON_SHUTDOWN:
4651 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
4652 case REASON_REBOOT:
4653 return PowerManager.SHUTDOWN_REASON_REBOOT;
4654 case REASON_USERREQUESTED:
4655 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
4656 case REASON_THERMAL_SHUTDOWN:
4657 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
Sudheer Shanka292637f2017-09-25 10:36:23 -07004658 case REASON_LOW_BATTERY:
4659 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
4660 case REASON_BATTERY_THERMAL_STATE:
4661 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
Salvador Martineza6f7b252017-04-10 10:46:15 -07004662 default:
4663 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4664 }
4665 }
4666
Jeff Brown4ccb8232014-01-16 22:16:42 -08004667 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08004668 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004669 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
4670 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4671 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4672 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08004673 }
Jeff Brown970d4132014-07-19 11:33:47 -07004674 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08004675 }
4676
Jeff Brown6f357d32014-01-15 20:40:55 -08004677 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004678 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
4679 switch (screenState) {
4680 case Display.STATE_UNKNOWN:
4681 case Display.STATE_OFF:
4682 case Display.STATE_DOZE:
4683 case Display.STATE_DOZE_SUSPEND:
Chris Phoenix10a4a642017-09-25 13:21:00 -07004684 case Display.STATE_ON_SUSPEND:
Jeff Brown970d4132014-07-19 11:33:47 -07004685 case Display.STATE_ON:
Santos Cordon3107d292016-09-20 15:50:35 -07004686 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07004687 break;
4688 default:
4689 screenState = Display.STATE_UNKNOWN;
4690 break;
4691 }
4692 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4693 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4694 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
4695 }
4696 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
4697 }
4698
Jeff Brown6f357d32014-01-15 20:40:55 -08004699 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07004700 public void setUserInactiveOverrideFromWindowManager() {
4701 setUserInactiveOverrideFromWindowManagerInternal();
4702 }
4703
4704 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08004705 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07004706 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08004707 }
4708
4709 @Override
Pavel Grafov28939982017-10-03 15:11:52 +01004710 public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
4711 setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
Jeff Brown5ce1cb22014-11-06 19:05:33 -08004712 }
4713
4714 @Override
jackqdyulei455e90a2017-02-09 15:29:16 -08004715 public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004716 synchronized (mLock) {
jackqdyulei455e90a2017-02-09 15:29:16 -08004717 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType, mLowPowerModeEnabled);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004718 }
4719 }
4720
4721 @Override
4722 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
Makoto Onuki66a78122017-11-14 15:03:21 -08004723 mBatterySaverController.addListener(listener);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004724 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004725
4726 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004727 public boolean setDeviceIdleMode(boolean enabled) {
4728 return setDeviceIdleModeInternal(enabled);
4729 }
4730
4731 @Override
4732 public boolean setLightDeviceIdleMode(boolean enabled) {
4733 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004734 }
4735
4736 @Override
4737 public void setDeviceIdleWhitelist(int[] appids) {
4738 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004739 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004740
4741 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07004742 public void setDeviceIdleTempWhitelist(int[] appids) {
4743 setDeviceIdleTempWhitelistInternal(appids);
4744 }
4745
4746 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004747 public void startUidChanges() {
4748 startUidChangesInternal();
4749 }
4750
4751 @Override
4752 public void finishUidChanges() {
4753 finishUidChangesInternal();
4754 }
4755
4756 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004757 public void updateUidProcState(int uid, int procState) {
4758 updateUidProcStateInternal(uid, procState);
4759 }
4760
4761 @Override
4762 public void uidGone(int uid) {
4763 uidGoneInternal(uid);
4764 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01004765
4766 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004767 public void uidActive(int uid) {
4768 uidActiveInternal(uid);
4769 }
4770
4771 @Override
4772 public void uidIdle(int uid) {
4773 uidIdleInternal(uid);
4774 }
4775
4776 @Override
Michael Wrighta4d22d72015-09-16 23:19:26 +01004777 public void powerHint(int hintId, int data) {
4778 powerHintInternal(hintId, data);
4779 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004781}