blob: 89d24b194b139be7b98b9a9f79e66bcdff494583 [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;
Kweku Adams9f488e22019-01-14 16:25:08 -080025import android.annotation.NonNull;
Pavel Grafov28939982017-10-03 15:11:52 +010026import android.annotation.UserIdInt;
Jason Monkafae4bd2015-12-15 14:20:06 -050027import android.app.ActivityManager;
Pavel Grafov28939982017-10-03 15:11:52 +010028import android.app.SynchronousUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.ContentResolver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070035import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080036import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080037import android.hardware.SensorManager;
38import android.hardware.SystemSensorManager;
Issei Suzukica19e6e2019-02-26 12:39:11 +010039import android.hardware.display.AmbientDisplayConfiguration;
Jeff Brown4ccb8232014-01-16 22:16:42 -080040import android.hardware.display.DisplayManagerInternal;
Jeff Brown131206b2014-04-08 17:27:14 -070041import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Ruchi Kandoi0d434042016-10-03 09:12:02 -070042import android.hardware.power.V1_0.PowerHint;
Jeff Brown96307042012-07-27 15:51:34 -070043import android.net.Uri;
Amith Yamasani8b619832010-09-22 16:11:59 -070044import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070045import android.os.BatteryManagerInternal;
Kweku Adams9f488e22019-01-14 16:25:08 -080046import android.os.BatterySaverPolicyConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.Binder;
48import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.IBinder;
50import android.os.IPowerManager;
Jeff Brown96307042012-07-27 15:51:34 -070051import android.os.Looper;
Jim Miller92e66dd2012-02-21 18:57:12 -080052import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -070054import android.os.PowerManager.ServiceType;
Michael Wrighte3001042019-02-05 00:13:14 +000055import android.os.PowerManager.WakeReason;
Jeff Brown6f357d32014-01-15 20:40:55 -080056import android.os.PowerManagerInternal;
jackqdyulei92681e82017-02-28 11:26:28 -080057import android.os.PowerSaveState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.Process;
59import android.os.RemoteException;
Jocelyn Dangf2c38c12017-03-31 14:03:37 -070060import android.os.ResultReceiver;
61import android.os.ShellCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070063import android.os.SystemProperties;
Jeff Brown3edf5272014-08-14 19:25:14 -070064import android.os.Trace;
Jeff Brownd4935962012-09-25 13:27:20 -070065import android.os.UserHandle;
Christine Franks732c0432017-06-23 18:12:46 -070066import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070067import android.os.WorkSource;
Narayan Kamath2f916ed2017-12-29 13:02:15 +000068import android.os.WorkSource.WorkChain;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.provider.Settings;
Daichi Hirono82ab9802016-03-02 13:23:29 +090070import android.provider.Settings.SettingNotFoundException;
Jeff Brown567f7ca2014-01-30 23:38:03 -080071import android.service.dreams.DreamManagerInternal;
Ruben Brunkc7be3be2016-04-01 17:07:51 -070072import android.service.vr.IVrManager;
73import android.service.vr.IVrStateCallbacks;
Dianne Hackborn0ef403e2017-01-24 18:22:15 -080074import android.util.KeyValueListParser;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -070075import android.util.PrintWriterPrinter;
Joe Onorato8a9b2202010-02-26 18:56:32 -080076import android.util.Slog;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -070077import android.util.SparseArray;
Jeff Brown96307042012-07-27 15:51:34 -070078import android.util.TimeUtils;
Netta P958d0a52017-02-07 11:20:55 -080079import android.util.proto.ProtoOutputStream;
Jeff Brown037c33e2014-04-09 00:31:55 -070080import android.view.Display;
Makoto Onukiaae89532017-11-08 14:32:03 -080081
jackqdyulei92681e82017-02-28 11:26:28 -080082import com.android.internal.annotations.VisibleForTesting;
Jason Monkafae4bd2015-12-15 14:20:06 -050083import com.android.internal.app.IAppOpsService;
84import com.android.internal.app.IBatteryStats;
85import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060086import com.android.internal.util.DumpUtils;
Jason Monkafae4bd2015-12-15 14:20:06 -050087import com.android.server.EventLogTags;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060088import com.android.server.LockGuard;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -070089import com.android.server.RescueParty;
Jason Monkafae4bd2015-12-15 14:20:06 -050090import com.android.server.ServiceThread;
91import com.android.server.SystemService;
Michael Wright64c820d2017-03-21 12:36:55 +000092import com.android.server.UiThread;
Jason Monkafae4bd2015-12-15 14:20:06 -050093import com.android.server.Watchdog;
94import com.android.server.am.BatteryStatsService;
95import com.android.server.lights.Light;
96import com.android.server.lights.LightsManager;
Adrian Roose99bc052017-11-20 17:55:31 +010097import com.android.server.policy.WindowManagerPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -080098import com.android.server.power.batterysaver.BatterySaverController;
Kweku Adams7fb72a42019-01-08 16:08:49 -080099import com.android.server.power.batterysaver.BatterySaverPolicy;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700100import com.android.server.power.batterysaver.BatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700101import com.android.server.power.batterysaver.BatterySavingStats;
Makoto Onuki66a78122017-11-14 15:03:21 -0800102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.io.FileDescriptor;
104import java.io.PrintWriter;
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700105import java.lang.annotation.Retention;
106import java.lang.annotation.RetentionPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700108import java.util.Arrays;
Narayan Kamath607223f2018-02-19 14:09:02 +0000109import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Jeff Brown96307042012-07-27 15:51:34 -0700111/**
112 * The power manager service is responsible for coordinating power management
113 * functions on the device.
114 */
Jeff Brown2175e9c2014-09-12 16:11:07 -0700115public final class PowerManagerService extends SystemService
Jeff Brown96307042012-07-27 15:51:34 -0700116 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Santos Cordon4ddb8012017-09-20 15:25:44 -0700119 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -0700120 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -0700121
Jeff Brown96307042012-07-27 15:51:34 -0700122 // Message: Sent when a user activity timeout occurs to update the power state.
123 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -0800124 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -0700125 private static final int MSG_SANDMAN = 2;
Jeff Browne333e672014-10-28 13:48:55 -0700126 // Message: Sent when the screen brightness boost expires.
127 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700128 // Message: Polling to look for long held wake locks.
129 private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
Jeff Brown7304c342012-05-11 18:42:42 -0700130
Jeff Brown96307042012-07-27 15:51:34 -0700131 // Dirty bit: mWakeLocks changed
132 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
133 // Dirty bit: mWakefulness changed
134 private static final int DIRTY_WAKEFULNESS = 1 << 1;
135 // Dirty bit: user activity was poked or may have timed out
136 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
137 // Dirty bit: actual display power state was updated asynchronously
138 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
139 // Dirty bit: mBootCompleted changed
140 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
141 // Dirty bit: settings changed
142 private static final int DIRTY_SETTINGS = 1 << 5;
143 // Dirty bit: mIsPowered changed
144 private static final int DIRTY_IS_POWERED = 1 << 6;
145 // Dirty bit: mStayOn changed
146 private static final int DIRTY_STAY_ON = 1 << 7;
147 // Dirty bit: battery state changed
148 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700149 // Dirty bit: proximity state changed
150 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownec6aa592012-10-17 20:30:25 -0700151 // Dirty bit: dock state changed
Jeff Brown3ee549c2014-09-22 20:14:39 -0700152 private static final int DIRTY_DOCK_STATE = 1 << 10;
Jeff Browne333e672014-10-28 13:48:55 -0700153 // Dirty bit: brightness boost changed
154 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800155 // Dirty bit: sQuiescent changed
156 private static final int DIRTY_QUIESCENT = 1 << 12;
Santos Cordon3107d292016-09-20 15:50:35 -0700157 // Dirty bit: VR Mode enabled changed
158 private static final int DIRTY_VR_MODE_CHANGED = 1 << 13;
Jeff Brown7304c342012-05-11 18:42:42 -0700159
Jeff Brown96307042012-07-27 15:51:34 -0700160 // Summarizes the state of all active wakelocks.
161 private static final int WAKE_LOCK_CPU = 1 << 0;
162 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
163 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
164 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
165 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700166 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800167 private static final int WAKE_LOCK_DOZE = 1 << 6;
Jeff Brownc2932a12014-11-20 18:04:05 -0800168 private static final int WAKE_LOCK_DRAW = 1 << 7;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
Jeff Brown96307042012-07-27 15:51:34 -0700170 // Summarizes the user activity state.
171 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
172 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700173 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
Jeff Brown27736f52014-05-20 17:17:10 -0700175 // Default timeout in milliseconds. This is only used until the settings
176 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700177 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700178 private static final int DEFAULT_SLEEP_TIMEOUT = -1;
Jeff Brownff532542012-10-02 21:18:04 -0700179
Jeff Browne333e672014-10-28 13:48:55 -0700180 // Screen brightness boost timeout.
181 // Hardcoded for now until we decide what the right policy should be.
182 // This should perhaps be a setting.
183 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
184
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700185 // How long a partial wake lock must be held until we consider it a long wake lock.
186 static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
187
Jason Monk27bbb2d2015-03-31 16:46:39 -0400188 // Power features defined in hardware/libhardware/include/hardware/power.h.
189 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1;
190
191 // Default setting for double tap to wake.
192 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
193
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800194 // System property indicating that the screen should remain off until an explicit user action
195 private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
196
Christine Franks732c0432017-06-23 18:12:46 -0700197 // System Property indicating that retail demo mode is currently enabled.
198 private static final String SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED = "sys.retaildemo.enabled";
199
Wei Wang72b77cc2019-02-07 14:10:23 -0800200 // Possible reasons for shutting down or reboot for use in REBOOT_PROPERTY(sys.boot.reason)
201 // which is set by bootstat
Salvador Martineza6f7b252017-04-10 10:46:15 -0700202 private static final String REASON_SHUTDOWN = "shutdown";
203 private static final String REASON_REBOOT = "reboot";
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700204 private static final String REASON_USERREQUESTED = "shutdown,userrequested";
205 private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
Sudheer Shanka292637f2017-09-25 10:36:23 -0700206 private static final String REASON_LOW_BATTERY = "shutdown,battery";
207 private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700208
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -0700209 private static final String TRACE_SCREEN_ON = "Screen turning on";
210
211 /** If turning screen on takes more than this long, we show a warning on logcat. */
212 private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
213
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700214 /** Constants for {@link #shutdownOrRebootInternal} */
215 @Retention(RetentionPolicy.SOURCE)
216 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
217 public @interface HaltMode {}
218 private static final int HALT_MODE_SHUTDOWN = 0;
219 private static final int HALT_MODE_REBOOT = 1;
220 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
221
Mark Salyzyn74ce8b32018-06-05 09:06:54 -0700222 // property for last reboot reason
223 private static final String REBOOT_PROPERTY = "sys.boot.reason";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700224
Jeff Brownb880d882014-02-10 19:47:07 -0800225 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700226 private final ServiceThread mHandlerThread;
227 private final PowerManagerHandler mHandler;
Adrian Roos56021892017-02-27 20:25:09 +0100228 private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
jackqdyulei455e90a2017-02-09 15:29:16 -0800229 private final BatterySaverPolicy mBatterySaverPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800230 private final BatterySaverController mBatterySaverController;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700231 private final BatterySaverStateMachine mBatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700232 private final BatterySavingStats mBatterySavingStats;
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800233 private final AttentionDetector mAttentionDetector;
Santos Cordon64a6e612018-08-22 19:27:04 +0100234 private final BinderService mBinderService;
235 private final LocalService mLocalService;
236 private final NativeWrapper mNativeWrapper;
237 private final Injector mInjector;
Jeff Brown2c43c332014-06-12 22:38:59 -0700238
Adam Lesinski182f73f2013-12-05 16:48:06 -0800239 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700240 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800241 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700242 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700243 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700244 private WindowManagerPolicy mPolicy;
245 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800246 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700247 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800248 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800249 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700250
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600251 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
Jeff Brown96307042012-07-27 15:51:34 -0700252
253 // A bitfield that indicates what parts of the power state have
254 // changed and need to be recalculated.
255 private int mDirty;
256
257 // Indicates whether the device is awake or asleep or somewhere in between.
258 // This is distinct from the screen power state, which is managed separately.
259 private int mWakefulness;
Jeff Brownfbe96702014-11-19 18:30:58 -0800260 private boolean mWakefulnessChanging;
Jeff Brown96307042012-07-27 15:51:34 -0700261
Jeff Brown26875502014-01-30 21:47:47 -0800262 // True if the sandman has just been summoned for the first time since entering the
263 // dreaming or dozing state. Indicates whether a new dream should begin.
264 private boolean mSandmanSummoned;
265
Jeff Brown96307042012-07-27 15:51:34 -0700266 // True if MSG_SANDMAN has been scheduled.
267 private boolean mSandmanScheduled;
268
269 // Table of all suspend blockers.
270 // There should only be a few of these.
271 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
272
273 // Table of all wake locks acquired by applications.
274 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
275
276 // A bitfield that summarizes the state of all active wakelocks.
277 private int mWakeLockSummary;
278
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700279 // Have we scheduled a message to check for long wake locks? This is when we will check.
280 private long mNotifyLongScheduled;
281
282 // Last time we checked for long wake locks.
283 private long mNotifyLongDispatched;
284
285 // The time we decided to do next long check.
286 private long mNotifyLongNextCheck;
287
Jeff Brown96307042012-07-27 15:51:34 -0700288 // If true, instructs the display controller to wait for the proximity sensor to
289 // go negative before turning the screen on.
290 private boolean mRequestWaitForNegativeProximity;
291
292 // Timestamp of the last time the device was awoken or put to sleep.
293 private long mLastWakeTime;
294 private long mLastSleepTime;
295
Calin Tatarua3805722018-08-09 16:41:28 +0200296 // Last reason the device went to sleep.
Michael Wrighte3001042019-02-05 00:13:14 +0000297 private @WakeReason int mLastWakeReason;
Calin Tatarua3805722018-08-09 16:41:28 +0200298 private int mLastSleepReason;
299
Jeff Brown96307042012-07-27 15:51:34 -0700300 // Timestamp of the last call to user activity.
301 private long mLastUserActivityTime;
302 private long mLastUserActivityTimeNoChangeLights;
303
Jeff Brown0a571122014-08-21 21:50:43 -0700304 // Timestamp of last interactive power hint.
305 private long mLastInteractivePowerHintTime;
306
Jeff Browne333e672014-10-28 13:48:55 -0700307 // Timestamp of the last screen brightness boost.
308 private long mLastScreenBrightnessBoostTime;
309 private boolean mScreenBrightnessBoostInProgress;
310
Jeff Brown96307042012-07-27 15:51:34 -0700311 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700312 private int mUserActivitySummary;
313
314 // The desired display power state. The actual state may lag behind the
315 // requested because it is updated asynchronously by the display power controller.
316 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
317
Jeff Brown96307042012-07-27 15:51:34 -0700318 // True if the display power state has been fully applied, which means the display
319 // is actually on or actually off or whatever was requested.
320 private boolean mDisplayReady;
321
Jeff Brown27f7a862012-12-12 15:43:31 -0800322 // The suspend blocker used to keep the CPU alive when an application has acquired
323 // a wake lock.
324 private final SuspendBlocker mWakeLockSuspendBlocker;
325
326 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700327 private boolean mHoldingWakeLockSuspendBlocker;
328
Jeff Brown27f7a862012-12-12 15:43:31 -0800329 // The suspend blocker used to keep the CPU alive when the display is on, the
330 // display is getting ready or there is user activity (in which case the display
331 // must be on).
332 private final SuspendBlocker mDisplaySuspendBlocker;
333
334 // True if the display suspend blocker has been acquired.
335 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700336
337 // True if systemReady() has been called.
338 private boolean mSystemReady;
339
340 // True if boot completed occurred. We keep the screen on until this happens.
341 private boolean mBootCompleted;
342
Jeff Brown26875502014-01-30 21:47:47 -0800343 // True if auto-suspend mode is enabled.
344 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700345 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800346
347 // True if interactive mode is enabled.
348 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700349 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800350
Jeff Brown96307042012-07-27 15:51:34 -0700351 // True if the device is plugged into a power source.
352 private boolean mIsPowered;
353
Jeff Brownf3fb8952012-10-02 20:57:05 -0700354 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
355 private int mPlugType;
356
Jeff Brown016ff142012-10-15 16:47:22 -0700357 // The current battery level percentage.
358 private int mBatteryLevel;
359
360 // The battery level percentage at the time the dream started.
361 // This is used to terminate a dream and go to sleep if the battery is
362 // draining faster than it is charging and the user activity timeout has expired.
363 private int mBatteryLevelWhenDreamStarted;
364
Jeff Brownec6aa592012-10-17 20:30:25 -0700365 // The current dock state.
366 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
367
Jeff Brown26875502014-01-30 21:47:47 -0800368 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700369 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800370
371 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700372 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800373
Jeff Brown96307042012-07-27 15:51:34 -0700374 // True if the device should wake up when plugged or unplugged.
375 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
376
Bryce Lee584a4452014-10-21 15:55:55 -0700377 // True if the device should wake up when plugged or unplugged in theater mode.
378 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
379
Jeff Brownec083212013-09-11 20:45:25 -0700380 // True if the device should suspend when the screen is off due to proximity.
381 private boolean mSuspendWhenScreenOffDueToProximityConfig;
382
Jeff Brown96307042012-07-27 15:51:34 -0700383 // True if dreams are supported on this device.
384 private boolean mDreamsSupportedConfig;
385
John Spurlocked108f32012-10-18 16:49:24 -0400386 // Default value for dreams enabled
387 private boolean mDreamsEnabledByDefaultConfig;
388
389 // Default value for dreams activate-on-sleep
390 private boolean mDreamsActivatedOnSleepByDefaultConfig;
391
392 // Default value for dreams activate-on-dock
393 private boolean mDreamsActivatedOnDockByDefaultConfig;
394
Jeff Brown26875502014-01-30 21:47:47 -0800395 // True if dreams can run while not plugged in.
396 private boolean mDreamsEnabledOnBatteryConfig;
397
398 // Minimum battery level to allow dreaming when powered.
399 // Use -1 to disable this safety feature.
400 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
401
402 // Minimum battery level to allow dreaming when not powered.
403 // Use -1 to disable this safety feature.
404 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
405
406 // If the battery level drops by this percentage and the user activity timeout
407 // has expired, then assume the device is receiving insufficient current to charge
408 // effectively and terminate the dream. Use -1 to disable this safety feature.
409 private int mDreamsBatteryLevelDrainCutoffConfig;
410
Jeff Brown96307042012-07-27 15:51:34 -0700411 // True if dreams are enabled by the user.
412 private boolean mDreamsEnabledSetting;
413
John Spurlock1a868b72012-08-22 09:56:51 -0400414 // True if dreams should be activated on sleep.
415 private boolean mDreamsActivateOnSleepSetting;
416
Jeff Brownec6aa592012-10-17 20:30:25 -0700417 // True if dreams should be activated on dock.
418 private boolean mDreamsActivateOnDockSetting;
419
Jeff Brown2175e9c2014-09-12 16:11:07 -0700420 // True if doze should not be started until after the screen off transition.
Lucas Dupin16cfe452018-02-08 13:14:50 -0800421 private boolean mDozeAfterScreenOff;
Jeff Brown2175e9c2014-09-12 16:11:07 -0700422
Jeff Brown27736f52014-05-20 17:17:10 -0700423 // The minimum screen off timeout, in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100424 private long mMinimumScreenOffTimeoutConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700425
426 // The screen dim duration, in milliseconds.
427 // This is subtracted from the end of the screen off timeout so the
428 // minimum screen off timeout should be longer than this.
Pavel Grafov28939982017-10-03 15:11:52 +0100429 private long mMaximumScreenDimDurationConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700430
431 // The maximum screen dim time expressed as a ratio relative to the screen
432 // off timeout. If the screen off timeout is very short then we want the
433 // dim timeout to also be quite short so that most of the time is spent on.
434 // Otherwise the user won't get much screen on time before dimming occurs.
435 private float mMaximumScreenDimRatioConfig;
436
Jason Monk27bbb2d2015-03-31 16:46:39 -0400437 // Whether device supports double tap to wake.
438 private boolean mSupportsDoubleTapWakeConfig;
439
Jeff Brown96307042012-07-27 15:51:34 -0700440 // The screen off timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100441 private long mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -0700442
Jeff Brown05af6ad2014-09-30 20:54:30 -0700443 // The sleep timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100444 private long mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700445
Jeff Brown96307042012-07-27 15:51:34 -0700446 // The maximum allowable screen off timeout according to the device
447 // administration policy. Overrides other settings.
Pavel Grafov28939982017-10-03 15:11:52 +0100448 private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
Jeff Brown96307042012-07-27 15:51:34 -0700449
450 // The stay on while plugged in setting.
451 // A bitfield of battery conditions under which to make the screen stay on.
452 private int mStayOnWhilePluggedInSetting;
453
454 // True if the device should stay on.
455 private boolean mStayOn;
456
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800457 // True if the lights should stay off until an explicit user action.
458 private static boolean sQuiescent;
459
Jeff Brown93cbbb22012-10-04 13:18:36 -0700460 // True if the proximity sensor reads a positive result.
461 private boolean mProximityPositive;
462
Jeff Brown96307042012-07-27 15:51:34 -0700463 // Screen brightness setting limits.
464 private int mScreenBrightnessSettingMinimum;
465 private int mScreenBrightnessSettingMaximum;
466 private int mScreenBrightnessSettingDefault;
467
468 // The screen brightness setting, from 0 to 255.
469 // Use -1 if no value has been set.
470 private int mScreenBrightnessSetting;
471
472 // The screen brightness mode.
473 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
474 private int mScreenBrightnessModeSetting;
475
476 // The screen brightness setting override from the window manager
477 // to allow the current foreground activity to override the brightness.
478 // Use -1 to disable.
479 private int mScreenBrightnessOverrideFromWindowManager = -1;
480
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -0700481 // The window manager has determined the user to be inactive via other means.
482 // Set this to false to disable.
483 private boolean mUserInactiveOverrideFromWindowManager;
484
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -0700485 // The next possible user activity timeout after being explicitly told the user is inactive.
486 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
487 private long mOverriddenTimeout = -1;
488
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700489 // The user activity timeout override from the window manager
490 // to allow the current foreground activity to override the user activity timeout.
491 // Use -1 to disable.
492 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
493
Jeff Brown970d4132014-07-19 11:33:47 -0700494 // The screen state to use while dozing.
495 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
496
497 // The screen brightness to use while dozing.
498 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
499
Ivan Podogov56bc6d02018-02-26 16:04:24 +0000500 // Keep display state when dozing.
501 private boolean mDrawWakeLockOverrideFromSidekick;
502
Jeff Brown9ba8d782012-10-01 16:38:23 -0700503 // Time when we last logged a warning about calling userActivity() without permission.
504 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
505
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700506 // True if the battery level is currently considered low.
507 private boolean mBatteryLevelLow;
508
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700509 // True if we are currently in device idle mode.
510 private boolean mDeviceIdleMode;
511
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700512 // True if we are currently in light device idle mode.
513 private boolean mLightDeviceIdleMode;
514
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700515 // Set of app ids that we will always respect the wake locks for.
516 int[] mDeviceIdleWhitelist = new int[0];
517
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700518 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
519 int[] mDeviceIdleTempWhitelist = new int[0];
520
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -0700521 private final SparseArray<UidState> mUidState = new SparseArray<>();
522
523 // We are currently in the middle of a batch change of uids.
524 private boolean mUidsChanging;
525
526 // Some uids have actually changed while mUidsChanging was true.
527 private boolean mUidsChanged;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700528
Bryce Lee584a4452014-10-21 15:55:55 -0700529 // True if theater mode is enabled
530 private boolean mTheaterModeEnabled;
531
Adrian Roos56021892017-02-27 20:25:09 +0100532 // True if always on display is enabled
533 private boolean mAlwaysOnEnabled;
534
Jason Monk27bbb2d2015-03-31 16:46:39 -0400535 // True if double tap to wake is enabled
536 private boolean mDoubleTapWakeEnabled;
537
Santos Cordon3107d292016-09-20 15:50:35 -0700538 // True if we are currently in VR Mode.
539 private boolean mIsVrModeEnabled;
540
Santos Cordon12f92eb2019-02-01 21:28:47 +0000541 // True if we in the process of performing a forceSuspend
542 private boolean mForceSuspendActive;
543
Pavel Grafov28939982017-10-03 15:11:52 +0100544 private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
545 @Override
546 public void onUserSwitching(int newUserId) throws RemoteException {}
547
548 @Override
549 public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
550 final long now = SystemClock.uptimeMillis();
551 synchronized(mLock) {
552 mForegroundProfile = newProfileId;
553 maybeUpdateForegroundProfileLastActivityLocked(now);
554 }
555 }
556 }
557
558 // User id corresponding to activity the user is currently interacting with.
559 private @UserIdInt int mForegroundProfile;
560
561 // Per-profile state to track when a profile should be locked.
562 private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
563
564 private static final class ProfilePowerState {
565 // Profile user id.
566 final @UserIdInt int mUserId;
567 // Maximum time to lock set by admin.
568 long mScreenOffTimeout;
569 // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
570 int mWakeLockSummary;
571 // Last user activity that happened in an app running in the profile.
572 long mLastUserActivityTime;
573 // Whether profile has been locked last time it timed out.
574 boolean mLockingNotified;
575
576 public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout) {
577 mUserId = userId;
578 mScreenOffTimeout = screenOffTimeout;
579 // Not accurate but at least won't cause immediate locking of the profile.
580 mLastUserActivityTime = SystemClock.uptimeMillis();
581 }
582 }
583
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800584 /**
585 * All times are in milliseconds. These constants are kept synchronized with the system
586 * global Settings. Any access to this class or its fields should be done while
587 * holding the PowerManagerService.mLock lock.
588 */
589 private final class Constants extends ContentObserver {
590 // Key names stored in the settings value.
591 private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
592
593 private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
594
595 // Prevent processes that are cached from holding wake locks?
596 public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
597
598 private ContentResolver mResolver;
599 private final KeyValueListParser mParser = new KeyValueListParser(',');
600
601 public Constants(Handler handler) {
602 super(handler);
603 }
604
605 public void start(ContentResolver resolver) {
606 mResolver = resolver;
607 mResolver.registerContentObserver(Settings.Global.getUriFor(
608 Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
609 updateConstants();
610 }
611
612 @Override
613 public void onChange(boolean selfChange, Uri uri) {
614 updateConstants();
615 }
616
617 private void updateConstants() {
618 synchronized (mLock) {
619 try {
620 mParser.setString(Settings.Global.getString(mResolver,
621 Settings.Global.POWER_MANAGER_CONSTANTS));
622 } catch (IllegalArgumentException e) {
623 // Failed to parse the settings string, log this and move on
624 // with defaults.
625 Slog.e(TAG, "Bad alarm manager settings", e);
626 }
627
628 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
629 DEFAULT_NO_CACHED_WAKE_LOCKS);
630 }
631 }
632
633 void dump(PrintWriter pw) {
634 pw.println(" Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
635
636 pw.print(" "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
637 pw.println(NO_CACHED_WAKE_LOCKS);
638 }
Netta P958d0a52017-02-07 11:20:55 -0800639
640 void dumpProto(ProtoOutputStream proto) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700641 final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
642 proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
Netta P958d0a52017-02-07 11:20:55 -0800643 NO_CACHED_WAKE_LOCKS);
644 proto.end(constantsToken);
645 }
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800646 }
647
Santos Cordon64a6e612018-08-22 19:27:04 +0100648 /**
649 * Wrapper around the static-native methods of PowerManagerService.
650 *
651 * This class exists to allow us to mock static native methods in our tests. If mocking static
652 * methods becomes easier than this in the future, we can delete this class.
653 */
654 @VisibleForTesting
655 public static class NativeWrapper {
656 /** Wrapper for PowerManager.nativeInit */
657 public void nativeInit(PowerManagerService service) {
658 service.nativeInit();
659 }
660
661 /** Wrapper for PowerManager.nativeAcquireSuspectBlocker */
662 public void nativeAcquireSuspendBlocker(String name) {
663 PowerManagerService.nativeAcquireSuspendBlocker(name);
664 }
665
666 /** Wrapper for PowerManager.nativeReleaseSuspendBlocker */
667 public void nativeReleaseSuspendBlocker(String name) {
668 PowerManagerService.nativeReleaseSuspendBlocker(name);
669 }
670
671 /** Wrapper for PowerManager.nativeSetInteractive */
672 public void nativeSetInteractive(boolean enable) {
673 PowerManagerService.nativeSetInteractive(enable);
674 }
675
676 /** Wrapper for PowerManager.nativeSetAutoSuspend */
677 public void nativeSetAutoSuspend(boolean enable) {
678 PowerManagerService.nativeSetAutoSuspend(enable);
679 }
680
681 /** Wrapper for PowerManager.nativeSendPowerHint */
682 public void nativeSendPowerHint(int hintId, int data) {
683 PowerManagerService.nativeSendPowerHint(hintId, data);
684 }
685
686 /** Wrapper for PowerManager.nativeSetFeature */
687 public void nativeSetFeature(int featureId, int data) {
688 PowerManagerService.nativeSetFeature(featureId, data);
689 }
Santos Cordon12f92eb2019-02-01 21:28:47 +0000690
691 /** Wrapper for PowerManager.nativeForceSuspend */
692 public boolean nativeForceSuspend() {
693 return PowerManagerService.nativeForceSuspend();
694 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100695 }
696
697 @VisibleForTesting
698 static class Injector {
699 Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
700 SuspendBlocker suspendBlocker, WindowManagerPolicy policy) {
701 return new Notifier(looper, context, batteryStats, suspendBlocker, policy);
702 }
703
704 SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
705 SuspendBlocker suspendBlocker = service.new SuspendBlockerImpl(name);
706 service.mSuspendBlockers.add(suspendBlocker);
707 return suspendBlocker;
708 }
709
710 BatterySaverPolicy createBatterySaverPolicy(
711 Object lock, Context context, BatterySavingStats batterySavingStats) {
712 return new BatterySaverPolicy(lock, context, batterySavingStats);
713 }
714
715 NativeWrapper createNativeWrapper() {
716 return new NativeWrapper();
717 }
718 }
719
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800720 final Constants mConstants;
721
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700722 private native void nativeInit();
Jeff Brown96307042012-07-27 15:51:34 -0700723 private static native void nativeAcquireSuspendBlocker(String name);
724 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700725 private static native void nativeSetInteractive(boolean enable);
726 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700727 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400728 private static native void nativeSetFeature(int featureId, int data);
Santos Cordon12f92eb2019-02-01 21:28:47 +0000729 private static native boolean nativeForceSuspend();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730
Jeff Brownb880d882014-02-10 19:47:07 -0800731 public PowerManagerService(Context context) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100732 this(context, new Injector());
733 }
734
735 @VisibleForTesting
736 PowerManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800737 super(context);
Santos Cordon64a6e612018-08-22 19:27:04 +0100738
Jeff Brownb880d882014-02-10 19:47:07 -0800739 mContext = context;
Santos Cordon64a6e612018-08-22 19:27:04 +0100740 mBinderService = new BinderService();
741 mLocalService = new LocalService();
742 mNativeWrapper = injector.createNativeWrapper();
743 mInjector = injector;
744
Jeff Brown2c43c332014-06-12 22:38:59 -0700745 mHandlerThread = new ServiceThread(TAG,
746 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
747 mHandlerThread.start();
748 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800749 mConstants = new Constants(mHandler);
Adrian Roos56021892017-02-27 20:25:09 +0100750 mAmbientDisplayConfiguration = new AmbientDisplayConfiguration(mContext);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800751 mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
Makoto Onuki66a78122017-11-14 15:03:21 -0800752
Makoto Onukibd7a6252018-05-10 13:41:39 -0700753 mBatterySavingStats = new BatterySavingStats(mLock);
Santos Cordon64a6e612018-08-22 19:27:04 +0100754 mBatterySaverPolicy =
755 mInjector.createBatterySaverPolicy(mLock, mContext, mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700756 mBatterySaverController = new BatterySaverController(mLock, mContext,
Santos Cordon64a6e612018-08-22 19:27:04 +0100757 BackgroundThread.get().getLooper(), mBatterySaverPolicy,
758 mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700759 mBatterySaverStateMachine = new BatterySaverStateMachine(
760 mLock, mContext, mBatterySaverController);
Jeff Brown2c43c332014-06-12 22:38:59 -0700761
Jeff Brown96307042012-07-27 15:51:34 -0700762 synchronized (mLock) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100763 mWakeLockSuspendBlocker =
764 mInjector.createSuspendBlocker(this, "PowerManagerService.WakeLocks");
765 mDisplaySuspendBlocker =
766 mInjector.createSuspendBlocker(this, "PowerManagerService.Display");
767 if (mDisplaySuspendBlocker != null) {
768 mDisplaySuspendBlocker.acquire();
769 mHoldingDisplaySuspendBlocker = true;
770 }
Jeff Brown037c33e2014-04-09 00:31:55 -0700771 mHalAutoSuspendModeEnabled = false;
772 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800773
Jeff Brown96307042012-07-27 15:51:34 -0700774 mWakefulness = WAKEFULNESS_AWAKE;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800775 sQuiescent = SystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
776
Santos Cordon64a6e612018-08-22 19:27:04 +0100777 mNativeWrapper.nativeInit(this);
778 mNativeWrapper.nativeSetAutoSuspend(false);
779 mNativeWrapper.nativeSetInteractive(true);
780 mNativeWrapper.nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 }
783
Jeff Brown6f357d32014-01-15 20:40:55 -0800784 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800785 public void onStart() {
Santos Cordon64a6e612018-08-22 19:27:04 +0100786 publishBinderService(Context.POWER_SERVICE, mBinderService);
787 publishLocalService(PowerManagerInternal.class, mLocalService);
Jeff Brown9e316a12012-10-08 19:17:06 -0700788
789 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800790 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700791 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800792
Jeff Brown6d2a9492014-08-07 19:06:49 -0700793 @Override
794 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700795 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600796 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
797 incrementBootCount();
798
799 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700800 final long now = SystemClock.uptimeMillis();
801 mBootCompleted = true;
802 mDirty |= DIRTY_BOOT_COMPLETED;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700803
804 mBatterySaverStateMachine.onBootCompleted();
Craig Mautner6e2f3952014-09-09 14:26:41 -0700805 userActivityNoUpdateLocked(
806 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
807 updatePowerStateLocked();
808 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700809 }
810 }
811
Jeff Brown21392762014-06-13 19:00:36 -0700812 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700813 synchronized (mLock) {
814 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700815 mAppOps = appOps;
816 mDreamManager = getLocalService(DreamManagerInternal.class);
817 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
818 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700819 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800820 mAttentionDetector.systemReady(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821
Adam Lesinski182f73f2013-12-05 16:48:06 -0800822 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700823 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
824 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
825 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700827 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800828
Jeff Brownc38c9be2012-10-04 13:16:19 -0700829 // The notifier runs on the system server's main looper so as not to interfere
830 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700831 mBatteryStats = BatteryStatsService.getService();
Santos Cordon64a6e612018-08-22 19:27:04 +0100832 mNotifier = mInjector.createNotifier(Looper.getMainLooper(), mContext, mBatteryStats,
833 mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
834 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700835
Jeff Brown3b971592013-01-09 18:46:37 -0800836 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
Santos Cordon64a6e612018-08-22 19:27:04 +0100837 mInjector.createSuspendBlocker(
838 this, "PowerManagerService.WirelessChargerDetector"),
Jeff Browndbcc8a22013-10-01 16:16:44 -0700839 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700840 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700841
842 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800843 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400844
Jeff Brown131206b2014-04-08 17:27:14 -0700845 // Initialize display power management.
846 mDisplayManagerInternal.initPowerManagement(
847 mDisplayPowerCallbacks, mHandler, sensorManager);
848
Pavel Grafov28939982017-10-03 15:11:52 +0100849 try {
850 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
851 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
852 } catch (RemoteException e) {
853 // Shouldn't happen since in-process.
854 }
Makoto Onuki66a78122017-11-14 15:03:21 -0800855
Jeff Brown96307042012-07-27 15:51:34 -0700856 // Go.
857 readConfigurationLocked();
858 updateSettingsLocked();
859 mDirty |= DIRTY_BATTERY_STATE;
860 updatePowerStateLocked();
861 }
Shibin George43f5de02016-07-06 02:12:10 +0530862
Jeff Sharkey6e544612017-02-20 11:02:26 -0700863 final ContentResolver resolver = mContext.getContentResolver();
864 mConstants.start(resolver);
Makoto Onuki66a78122017-11-14 15:03:21 -0800865
866 mBatterySaverController.systemReady();
Makoto Onukibd7a6252018-05-10 13:41:39 -0700867 mBatterySaverPolicy.systemReady();
Jeff Sharkey6e544612017-02-20 11:02:26 -0700868
869 // Register for settings changes.
870 resolver.registerContentObserver(Settings.Secure.getUriFor(
871 Settings.Secure.SCREENSAVER_ENABLED),
872 false, mSettingsObserver, UserHandle.USER_ALL);
873 resolver.registerContentObserver(Settings.Secure.getUriFor(
874 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
875 false, mSettingsObserver, UserHandle.USER_ALL);
876 resolver.registerContentObserver(Settings.Secure.getUriFor(
877 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
878 false, mSettingsObserver, UserHandle.USER_ALL);
879 resolver.registerContentObserver(Settings.System.getUriFor(
880 Settings.System.SCREEN_OFF_TIMEOUT),
881 false, mSettingsObserver, UserHandle.USER_ALL);
882 resolver.registerContentObserver(Settings.Secure.getUriFor(
883 Settings.Secure.SLEEP_TIMEOUT),
884 false, mSettingsObserver, UserHandle.USER_ALL);
885 resolver.registerContentObserver(Settings.Global.getUriFor(
886 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
887 false, mSettingsObserver, UserHandle.USER_ALL);
888 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700889 Settings.System.SCREEN_BRIGHTNESS_MODE),
890 false, mSettingsObserver, UserHandle.USER_ALL);
891 resolver.registerContentObserver(Settings.System.getUriFor(
892 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
893 false, mSettingsObserver, UserHandle.USER_ALL);
894 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700895 Settings.Global.THEATER_MODE_ON),
896 false, mSettingsObserver, UserHandle.USER_ALL);
897 resolver.registerContentObserver(Settings.Secure.getUriFor(
Adrian Roos56021892017-02-27 20:25:09 +0100898 Settings.Secure.DOZE_ALWAYS_ON),
899 false, mSettingsObserver, UserHandle.USER_ALL);
900 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700901 Settings.Secure.DOUBLE_TAP_TO_WAKE),
902 false, mSettingsObserver, UserHandle.USER_ALL);
Christine Franks732c0432017-06-23 18:12:46 -0700903 resolver.registerContentObserver(Settings.Global.getUriFor(
904 Settings.Global.DEVICE_DEMO_MODE),
905 false, mSettingsObserver, UserHandle.USER_SYSTEM);
Santos Cordon64a6e612018-08-22 19:27:04 +0100906 IVrManager vrManager = IVrManager.Stub.asInterface(getBinderService(Context.VR_SERVICE));
Jeff Sharkey6e544612017-02-20 11:02:26 -0700907 if (vrManager != null) {
908 try {
909 vrManager.registerListener(mVrStateCallbacks);
910 } catch (RemoteException e) {
911 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
912 }
913 }
914
Shibin George43f5de02016-07-06 02:12:10 +0530915 // Register for broadcasts from other components of the system.
916 IntentFilter filter = new IntentFilter();
917 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
918 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
919 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
920
921 filter = new IntentFilter();
922 filter.addAction(Intent.ACTION_DREAMING_STARTED);
923 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
924 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
925
926 filter = new IntentFilter();
927 filter.addAction(Intent.ACTION_USER_SWITCHED);
928 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
929
930 filter = new IntentFilter();
931 filter.addAction(Intent.ACTION_DOCK_EVENT);
932 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700933 }
934
935 private void readConfigurationLocked() {
936 final Resources resources = mContext.getResources();
937
Jeff Brown037c33e2014-04-09 00:31:55 -0700938 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800939 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700940 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800941 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700942 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700943 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700944 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
945 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700946 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
947 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700948 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400949 com.android.internal.R.bool.config_dreamsSupported);
950 mDreamsEnabledByDefaultConfig = resources.getBoolean(
951 com.android.internal.R.bool.config_dreamsEnabledByDefault);
952 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
953 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
954 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
955 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800956 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
957 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
958 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
959 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
960 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
961 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
962 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
963 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Lucas Dupin16cfe452018-02-08 13:14:50 -0800964 mDozeAfterScreenOff = resources.getBoolean(
Lucas Dupin5354cc02018-03-20 16:09:34 -0700965 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
Jeff Brown27736f52014-05-20 17:17:10 -0700966 mMinimumScreenOffTimeoutConfig = resources.getInteger(
967 com.android.internal.R.integer.config_minimumScreenOffTimeout);
968 mMaximumScreenDimDurationConfig = resources.getInteger(
969 com.android.internal.R.integer.config_maximumScreenDimDuration);
970 mMaximumScreenDimRatioConfig = resources.getFraction(
971 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400972 mSupportsDoubleTapWakeConfig = resources.getBoolean(
973 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
975
Jeff Brown96307042012-07-27 15:51:34 -0700976 private void updateSettingsLocked() {
977 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700978
Jeff Brownd4935962012-09-25 13:27:20 -0700979 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400980 Settings.Secure.SCREENSAVER_ENABLED,
981 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700982 UserHandle.USER_CURRENT) != 0);
983 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400984 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
985 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700986 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700987 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400988 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
989 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -0700990 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -0700991 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
992 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
993 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -0700994 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
995 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
996 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -0700997 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -0700998 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -0700999 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1000 Settings.Global.THEATER_MODE_ON, 0) == 1;
Adrian Roos56021892017-02-27 20:25:09 +01001001 mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
Jeff Brown7304c342012-05-11 18:42:42 -07001002
Jason Monk27bbb2d2015-03-31 16:46:39 -04001003 if (mSupportsDoubleTapWakeConfig) {
1004 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
1005 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
1006 UserHandle.USER_CURRENT) != 0;
1007 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
1008 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
Santos Cordon64a6e612018-08-22 19:27:04 +01001009 mNativeWrapper.nativeSetFeature(
1010 POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001011 }
1012 }
1013
Christine Franks732c0432017-06-23 18:12:46 -07001014 final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
1015 if (!retailDemoValue.equals(SystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED))) {
1016 SystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
1017 }
1018
Jeff Brownd4935962012-09-25 13:27:20 -07001019 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -07001020 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -07001021 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -07001022
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001023 mDirty |= DIRTY_SETTINGS;
1024 }
1025
Jeff Brown96307042012-07-27 15:51:34 -07001026 private void handleSettingsChangedLocked() {
1027 updateSettingsLocked();
1028 updatePowerStateLocked();
1029 }
1030
Dianne Hackborn713df152013-05-17 11:27:57 -07001031 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001032 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -07001033 synchronized (mLock) {
1034 if (DEBUG_SPEW) {
1035 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1036 + ", flags=0x" + Integer.toHexString(flags)
1037 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039
Jeff Brown96307042012-07-27 15:51:34 -07001040 WakeLock wakeLock;
1041 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001042 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -07001043 if (index >= 0) {
1044 wakeLock = mWakeLocks.get(index);
1045 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
1046 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001047 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1048 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001049 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001051 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 } else {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001053 UidState state = mUidState.get(uid);
1054 if (state == null) {
1055 state = new UidState(uid);
1056 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1057 mUidState.put(uid, state);
1058 }
1059 state.mNumWakeLocks++;
1060 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
1061 state);
Jeff Brown96307042012-07-27 15:51:34 -07001062 try {
1063 lock.linkToDeath(wakeLock, 0);
1064 } catch (RemoteException ex) {
1065 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
Jeff Brown96307042012-07-27 15:51:34 -07001067 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001068 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001069 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071
Jeff Brownc12035c2014-08-13 18:52:25 -07001072 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001073 mDirty |= DIRTY_WAKE_LOCKS;
1074 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001075 if (notifyAcquire) {
1076 // This needs to be done last so we are sure we have acquired the
1077 // kernel wake lock. Otherwise we have a race where the system may
1078 // go to sleep between the time we start the accounting in battery
1079 // stats and when we actually get around to telling the kernel to
1080 // stay awake.
1081 notifyWakeLockAcquiredLocked(wakeLock);
1082 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001083 }
1084 }
1085
Jeff Brownec083212013-09-11 20:45:25 -07001086 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -08001087 private static boolean isScreenLock(final WakeLock wakeLock) {
1088 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1089 case PowerManager.FULL_WAKE_LOCK:
1090 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1091 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1092 return true;
1093 }
1094 return false;
1095 }
1096
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001097 private static WorkChain getFirstNonEmptyWorkChain(WorkSource workSource) {
1098 if (workSource.getWorkChains() == null) {
1099 return null;
1100 }
1101
1102 for (WorkChain workChain: workSource.getWorkChains()) {
1103 if (workChain.getSize() > 0) {
1104 return workChain;
1105 }
1106 }
1107
1108 return null;
1109 }
1110
Jeff Brownc12035c2014-08-13 18:52:25 -07001111 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -07001112 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1113 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001114 String opPackageName;
1115 int opUid;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001116 if (wakeLock.mWorkSource != null && !wakeLock.mWorkSource.isEmpty()) {
1117 WorkSource workSource = wakeLock.mWorkSource;
1118 WorkChain workChain = getFirstNonEmptyWorkChain(workSource);
1119 if (workChain != null) {
1120 opPackageName = workChain.getAttributionTag();
1121 opUid = workChain.getAttributionUid();
1122 } else {
1123 opPackageName = workSource.getName(0) != null
1124 ? workSource.getName(0) : wakeLock.mPackageName;
1125 opUid = workSource.get(0);
1126 }
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001127 } else {
1128 opPackageName = wakeLock.mPackageName;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001129 opUid = wakeLock.mOwnerUid;
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001130 }
Michael Wrighte3001042019-02-05 00:13:14 +00001131 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
1132 PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag,
1133 opUid, opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135 }
1136
Jeff Brown96307042012-07-27 15:51:34 -07001137 private void releaseWakeLockInternal(IBinder lock, int flags) {
1138 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -07001139 int index = findWakeLockIndexLocked(lock);
1140 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001141 if (DEBUG_SPEW) {
1142 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1143 + " [not found], flags=0x" + Integer.toHexString(flags));
1144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 return;
1146 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001147
Jeff Brown96307042012-07-27 15:51:34 -07001148 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001149 if (DEBUG_SPEW) {
1150 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1151 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1152 }
1153
Michael Wright1208e272014-09-08 19:57:50 -07001154 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001155 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 }
1157
Jeff Brown3edf5272014-08-14 19:25:14 -07001158 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1159 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001162
Jeff Brown96307042012-07-27 15:51:34 -07001163 private void handleWakeLockDeath(WakeLock wakeLock) {
1164 synchronized (mLock) {
1165 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001166 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1167 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -07001168 }
1169
1170 int index = mWakeLocks.indexOf(wakeLock);
1171 if (index < 0) {
1172 return;
1173 }
1174
Jeff Brown3edf5272014-08-14 19:25:14 -07001175 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001176 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001178
Jeff Brown3edf5272014-08-14 19:25:14 -07001179 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1180 mWakeLocks.remove(index);
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001181 UidState state = wakeLock.mUidState;
1182 state.mNumWakeLocks--;
1183 if (state.mNumWakeLocks <= 0 &&
1184 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1185 mUidState.remove(state.mUid);
1186 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001187 notifyWakeLockReleasedLocked(wakeLock);
1188
1189 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1190 mDirty |= DIRTY_WAKE_LOCKS;
1191 updatePowerStateLocked();
1192 }
1193
Jeff Brown96307042012-07-27 15:51:34 -07001194 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001195 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1196 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001197 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1198 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1199 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1200 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 }
1203
Dianne Hackbornd953c532014-08-16 18:17:38 -07001204 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1205 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001206 synchronized (mLock) {
1207 int index = findWakeLockIndexLocked(lock);
1208 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001209 if (DEBUG_SPEW) {
1210 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1211 + " [not found], ws=" + ws);
1212 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001213 throw new IllegalArgumentException("Wake lock not active: " + lock
1214 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001215 }
1216
1217 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001218 if (DEBUG_SPEW) {
1219 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1220 + " [" + wakeLock.mTag + "], ws=" + ws);
1221 }
1222
Jeff Brown96307042012-07-27 15:51:34 -07001223 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001224 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1225 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001226 ws, historyTag);
1227 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001228 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001229 }
1230 }
1231 }
1232
1233 private int findWakeLockIndexLocked(IBinder lock) {
1234 final int count = mWakeLocks.size();
1235 for (int i = 0; i < count; i++) {
1236 if (mWakeLocks.get(i).mLock == lock) {
1237 return i;
1238 }
1239 }
1240 return -1;
1241 }
1242
1243 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001244 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001245 wakeLock.mNotifiedAcquired = true;
1246 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001247 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1248 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001249 restartNofifyLongTimerLocked(wakeLock);
1250 }
1251 }
1252
1253 private void enqueueNotifyLongMsgLocked(long time) {
1254 mNotifyLongScheduled = time;
1255 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1256 msg.setAsynchronous(true);
1257 mHandler.sendMessageAtTime(msg, time);
1258 }
1259
1260 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1261 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1262 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1263 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1264 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1265 }
1266 }
1267
1268 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1269 if (mSystemReady && !wakeLock.mDisabled) {
1270 wakeLock.mNotifiedLong = true;
1271 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1272 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1273 }
1274 }
1275
1276 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1277 if (wakeLock.mNotifiedLong) {
1278 wakeLock.mNotifiedLong = false;
1279 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1280 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001281 }
1282 }
1283
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001284 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1285 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1286 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1287 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1288 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1289 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001290 notifyWakeLockLongFinishedLocked(wakeLock);
1291 // Changing the wake lock will count as releasing the old wake lock(s) and
1292 // acquiring the new ones... we do this because otherwise once a wakelock
1293 // becomes long, if we just continued to treat it as long we can get in to
1294 // situations where we spam battery stats with every following change to it.
1295 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001296 }
1297 }
1298
Jeff Brown96307042012-07-27 15:51:34 -07001299 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001300 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1301 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001302 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001303 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1304 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1305 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001306 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001307 }
1308 }
1309
Jeff Brownec083212013-09-11 20:45:25 -07001310 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001311 private boolean isWakeLockLevelSupportedInternal(int level) {
1312 synchronized (mLock) {
1313 switch (level) {
1314 case PowerManager.PARTIAL_WAKE_LOCK:
1315 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1316 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1317 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001318 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001319 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001320 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001321
1322 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001323 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001324
1325 default:
1326 return false;
1327 }
1328 }
1329 }
1330
Jeff Brown96307042012-07-27 15:51:34 -07001331 // Called from native code.
1332 private void userActivityFromNative(long eventTime, int event, int flags) {
1333 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1334 }
1335
1336 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1337 synchronized (mLock) {
1338 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1339 updatePowerStateLocked();
1340 }
1341 }
1342 }
1343
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001344 private void onUserAttention() {
1345 synchronized (mLock) {
1346 if (userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1347 PowerManager.USER_ACTIVITY_EVENT_ATTENTION, 0 /* flags */,
1348 Process.SYSTEM_UID)) {
1349 updatePowerStateLocked();
1350 }
1351 }
1352 }
1353
Jeff Brown96307042012-07-27 15:51:34 -07001354 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1355 if (DEBUG_SPEW) {
1356 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1357 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1358 + ", uid=" + uid);
1359 }
1360
1361 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -08001362 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001363 return false;
1364 }
1365
Jeff Brown3edf5272014-08-14 19:25:14 -07001366 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1367 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001368 if (eventTime > mLastInteractivePowerHintTime) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07001369 powerHintInternal(PowerHint.INTERACTION, 0);
Jeff Brown0a571122014-08-21 21:50:43 -07001370 mLastInteractivePowerHintTime = eventTime;
1371 }
1372
Jeff Brown3edf5272014-08-14 19:25:14 -07001373 mNotifier.onUserActivity(event, uid);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001374 mAttentionDetector.onUserActivity(eventTime, event);
Jeff Brown96307042012-07-27 15:51:34 -07001375
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001376 if (mUserInactiveOverrideFromWindowManager) {
1377 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001378 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001379 }
1380
Jeff Brown0a571122014-08-21 21:50:43 -07001381 if (mWakefulness == WAKEFULNESS_ASLEEP
1382 || mWakefulness == WAKEFULNESS_DOZING
1383 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1384 return false;
1385 }
1386
Pavel Grafov28939982017-10-03 15:11:52 +01001387 maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1388
Jeff Brown3edf5272014-08-14 19:25:14 -07001389 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1390 if (eventTime > mLastUserActivityTimeNoChangeLights
1391 && eventTime > mLastUserActivityTime) {
1392 mLastUserActivityTimeNoChangeLights = eventTime;
1393 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001394 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1395 mDirty |= DIRTY_QUIESCENT;
1396 }
1397
Jeff Brown3edf5272014-08-14 19:25:14 -07001398 return true;
1399 }
1400 } else {
1401 if (eventTime > mLastUserActivityTime) {
1402 mLastUserActivityTime = eventTime;
1403 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001404 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1405 mDirty |= DIRTY_QUIESCENT;
1406 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001407 return true;
1408 }
Jeff Brown96307042012-07-27 15:51:34 -07001409 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001410 } finally {
1411 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001412 }
1413 return false;
1414 }
1415
Pavel Grafov28939982017-10-03 15:11:52 +01001416 private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1417 final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1418 if (profile != null && eventTime > profile.mLastUserActivityTime) {
1419 profile.mLastUserActivityTime = eventTime;
1420 }
1421 }
1422
Michael Wrighte3001042019-02-05 00:13:14 +00001423 private void wakeUpInternal(long eventTime, @WakeReason int reason, String details, int uid,
1424 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001425 synchronized (mLock) {
Michael Wrighte3001042019-02-05 00:13:14 +00001426 if (wakeUpNoUpdateLocked(eventTime, reason, details, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001427 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001428 }
1429 }
Jeff Brown96307042012-07-27 15:51:34 -07001430 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001431
Michael Wrighte3001042019-02-05 00:13:14 +00001432 private boolean wakeUpNoUpdateLocked(long eventTime, @WakeReason int reason, String details,
1433 int reasonUid, String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001434 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001435 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001436 }
Jeff Brown96307042012-07-27 15:51:34 -07001437
1438 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
Santos Cordon12f92eb2019-02-01 21:28:47 +00001439 || !mBootCompleted || !mSystemReady || mForceSuspendActive) {
Jeff Brown96307042012-07-27 15:51:34 -07001440 return false;
1441 }
1442
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001443 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1444
Jeff Brown3edf5272014-08-14 19:25:14 -07001445 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1446 try {
Michael Wrighte3001042019-02-05 00:13:14 +00001447 Slog.i(TAG, "Waking up from "
1448 + PowerManagerInternal.wakefulnessToString(mWakefulness)
1449 + " (uid=" + reasonUid
1450 + ", reason=" + PowerManager.wakeReasonToString(reason)
1451 + ", details=" + details
1452 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001453
1454 mLastWakeTime = eventTime;
Michael Wrighte3001042019-02-05 00:13:14 +00001455 mLastWakeReason = reason;
1456 setWakefulnessLocked(WAKEFULNESS_AWAKE, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001457
Michael Wrighte3001042019-02-05 00:13:14 +00001458 mNotifier.onWakeUp(reason, details, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001459 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001460 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001461 } finally {
1462 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001463 }
Jeff Brown96307042012-07-27 15:51:34 -07001464 return true;
1465 }
1466
Jeff Brownc12035c2014-08-13 18:52:25 -07001467 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001468 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001469 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001470 updatePowerStateLocked();
1471 }
1472 }
1473 }
1474
Santos Cordon12f92eb2019-02-01 21:28:47 +00001475 /**
1476 * Puts the system in doze.
1477 *
1478 * This method is called goToSleep for historical reasons but actually attempts to DOZE,
1479 * and only tucks itself in to SLEEP if requested with the flag
1480 * {@link PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE}.
1481 */
Jeff Brownec083212013-09-11 20:45:25 -07001482 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001483 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001484 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001485 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001486 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001487 }
1488
Jeff Brown26875502014-01-30 21:47:47 -08001489 if (eventTime < mLastWakeTime
1490 || mWakefulness == WAKEFULNESS_ASLEEP
1491 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001492 || !mBootCompleted || !mSystemReady) {
1493 return false;
1494 }
1495
Jeff Brown3edf5272014-08-14 19:25:14 -07001496 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1497 try {
Santos Cordon12f92eb2019-02-01 21:28:47 +00001498 reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX,
1499 Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN));
1500 Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
1501 + " (uid " + uid + ")...");
Jeff Brown6d8fd272014-05-20 21:24:38 -07001502
Jeff Brown3edf5272014-08-14 19:25:14 -07001503 mLastSleepTime = eventTime;
Calin Tatarua3805722018-08-09 16:41:28 +02001504 mLastSleepReason = reason;
Jeff Brown3edf5272014-08-14 19:25:14 -07001505 mSandmanSummoned = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001506 setWakefulnessLocked(WAKEFULNESS_DOZING, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001507
1508 // Report the number of wake locks that will be cleared by going to sleep.
1509 int numWakeLocksCleared = 0;
1510 final int numWakeLocks = mWakeLocks.size();
1511 for (int i = 0; i < numWakeLocks; i++) {
1512 final WakeLock wakeLock = mWakeLocks.get(i);
1513 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1514 case PowerManager.FULL_WAKE_LOCK:
1515 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1516 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1517 numWakeLocksCleared += 1;
1518 break;
1519 }
1520 }
Michael Wrightb55e3a12018-03-06 15:14:06 +00001521 EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
Jeff Brown3edf5272014-08-14 19:25:14 -07001522
1523 // Skip dozing if requested.
1524 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1525 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1526 }
1527 } finally {
1528 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001529 }
Jeff Brown96307042012-07-27 15:51:34 -07001530 return true;
1531 }
1532
Jeff Brownc12035c2014-08-13 18:52:25 -07001533 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001534 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001535 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001536 updatePowerStateLocked();
1537 }
1538 }
1539 }
1540
Jeff Brownc12035c2014-08-13 18:52:25 -07001541 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001542 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001543 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001544 }
1545
1546 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1547 || !mBootCompleted || !mSystemReady) {
1548 return false;
1549 }
1550
Jeff Brown3edf5272014-08-14 19:25:14 -07001551 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1552 try {
1553 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001554
Jeff Brown3edf5272014-08-14 19:25:14 -07001555 mSandmanSummoned = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001556 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001557 } finally {
1558 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1559 }
Jeff Brown26875502014-01-30 21:47:47 -08001560 return true;
1561 }
1562
1563 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001564 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001565 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001566 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1567 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001568 }
1569
1570 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1571 || !mBootCompleted || !mSystemReady) {
1572 return false;
1573 }
1574
Jeff Brown3edf5272014-08-14 19:25:14 -07001575 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1576 try {
1577 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001578
Michael Wrighte3001042019-02-05 00:13:14 +00001579 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
1580 eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001581 } finally {
1582 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1583 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001584 return true;
1585 }
1586
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001587 @VisibleForTesting
Michael Wrighte3001042019-02-05 00:13:14 +00001588 void setWakefulnessLocked(int wakefulness, int reason, long eventTime) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001589 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001590 mWakefulness = wakefulness;
1591 mWakefulnessChanging = true;
1592 mDirty |= DIRTY_WAKEFULNESS;
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001593 if (mNotifier != null) {
Michael Wrighte3001042019-02-05 00:13:14 +00001594 mNotifier.onWakefulnessChangeStarted(wakefulness, reason, eventTime);
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001595 }
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001596 mAttentionDetector.onWakefulnessChangeStarted(wakefulness);
Jeff Brown037c33e2014-04-09 00:31:55 -07001597 }
1598 }
1599
Santos Cordon64a6e612018-08-22 19:27:04 +01001600 @VisibleForTesting
1601 int getWakefulness() {
1602 return mWakefulness;
1603 }
1604
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001605 /**
1606 * Logs the time the device would have spent awake before user activity timeout,
1607 * had the system not been told the user was inactive.
1608 */
1609 private void logSleepTimeoutRecapturedLocked() {
1610 final long now = SystemClock.uptimeMillis();
1611 final long savedWakeTimeMs = mOverriddenTimeout - now;
1612 if (savedWakeTimeMs >= 0) {
Michael Wrightb55e3a12018-03-06 15:14:06 +00001613 EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001614 mOverriddenTimeout = -1;
1615 }
1616 }
1617
Jeff Brown416c49c2015-05-26 19:50:18 -07001618 private void finishWakefulnessChangeIfNeededLocked() {
1619 if (mWakefulnessChanging && mDisplayReady) {
1620 if (mWakefulness == WAKEFULNESS_DOZING
1621 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1622 return; // wait until dream has enabled dozing
1623 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001624 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1625 logSleepTimeoutRecapturedLocked();
1626 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001627 if (mWakefulness == WAKEFULNESS_AWAKE) {
Michael Wrighte3001042019-02-05 00:13:14 +00001628 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1629 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1630 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1631 Slog.w(TAG, "Screen on took " + latencyMs + " ms");
1632 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001633 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001634 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001635 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001636 }
1637 }
1638
Jeff Brown96307042012-07-27 15:51:34 -07001639 /**
1640 * Updates the global power state based on dirty bits recorded in mDirty.
1641 *
1642 * This is the main function that performs power state transitions.
1643 * We centralize them here so that we can recompute the power state completely
1644 * each time something important changes, and ensure that we do it the same
1645 * way each time. The point is to gather all of the transition logic here.
1646 */
1647 private void updatePowerStateLocked() {
1648 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001649 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001651 if (!Thread.holdsLock(mLock)) {
1652 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001654
Jeff Brown3edf5272014-08-14 19:25:14 -07001655 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1656 try {
1657 // Phase 0: Basic state updates.
1658 updateIsPoweredLocked(mDirty);
1659 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001660 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661
Jeff Brown3edf5272014-08-14 19:25:14 -07001662 // Phase 1: Update wakefulness.
1663 // Loop because the wake lock and user activity computations are influenced
1664 // by changes in wakefulness.
1665 final long now = SystemClock.uptimeMillis();
1666 int dirtyPhase2 = 0;
1667 for (;;) {
1668 int dirtyPhase1 = mDirty;
1669 dirtyPhase2 |= dirtyPhase1;
1670 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001671
Jeff Brown3edf5272014-08-14 19:25:14 -07001672 updateWakeLockSummaryLocked(dirtyPhase1);
1673 updateUserActivitySummaryLocked(now, dirtyPhase1);
1674 if (!updateWakefulnessLocked(dirtyPhase1)) {
1675 break;
1676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001678
Pavel Grafov28939982017-10-03 15:11:52 +01001679 // Phase 2: Lock profiles that became inactive/not kept awake.
1680 updateProfilesLocked(now);
Jeff Brown3edf5272014-08-14 19:25:14 -07001681
Pavel Grafov28939982017-10-03 15:11:52 +01001682 // Phase 3: Update display power state.
1683 final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1684
1685 // Phase 4: Update dream state (depends on display ready signal).
Jeff Brown2175e9c2014-09-12 16:11:07 -07001686 updateDreamLocked(dirtyPhase2, displayBecameReady);
1687
Pavel Grafov28939982017-10-03 15:11:52 +01001688 // Phase 5: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001689 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001690
Pavel Grafov28939982017-10-03 15:11:52 +01001691 // Phase 6: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001692 // Because we might release the last suspend blocker here, we need to make sure
1693 // we finished everything else first!
1694 updateSuspendBlockerLocked();
1695 } finally {
1696 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
Jeff Brown96307042012-07-27 15:51:34 -07001698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001699
Jim Miller92e66dd2012-02-21 18:57:12 -08001700 /**
Pavel Grafov28939982017-10-03 15:11:52 +01001701 * Check profile timeouts and notify profiles that should be locked.
1702 */
1703 private void updateProfilesLocked(long now) {
1704 final int numProfiles = mProfilePowerState.size();
1705 for (int i = 0; i < numProfiles; i++) {
1706 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1707 if (isProfileBeingKeptAwakeLocked(profile, now)) {
1708 profile.mLockingNotified = false;
1709 } else if (!profile.mLockingNotified) {
1710 profile.mLockingNotified = true;
1711 mNotifier.onProfileTimeout(profile.mUserId);
1712 }
1713 }
1714 }
1715
1716 private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1717 return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1718 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1719 || (mProximityPositive &&
1720 (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1721 }
1722
1723 /**
Jeff Brown96307042012-07-27 15:51:34 -07001724 * Updates the value of mIsPowered.
1725 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001726 */
Jeff Brown96307042012-07-27 15:51:34 -07001727 private void updateIsPoweredLocked(int dirty) {
1728 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001729 final boolean wasPowered = mIsPowered;
1730 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001731 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001732 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1733 mPlugType = mBatteryManagerInternal.getPlugType();
1734 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1735 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001736
Jeff Brown26875502014-01-30 21:47:47 -08001737 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001738 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001739 + ", mIsPowered=" + mIsPowered
1740 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001741 + ", mPlugType=" + mPlugType
1742 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001743 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001744
Jeff Brownf3fb8952012-10-02 20:57:05 -07001745 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001746 mDirty |= DIRTY_IS_POWERED;
1747
Jeff Brown3b971592013-01-09 18:46:37 -08001748 // Update wireless dock detection state.
1749 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
Beverlyfcaab292018-03-19 10:42:06 -04001750 mIsPowered, mPlugType);
Jeff Brown3b971592013-01-09 18:46:37 -08001751
Jeff Brown96307042012-07-27 15:51:34 -07001752 // Treat plugging and unplugging the devices as a user activity.
1753 // Users find it disconcerting when they plug or unplug the device
1754 // and it shuts off right away.
1755 // Some devices also wake the device when plugged or unplugged because
1756 // they don't have a charging LED.
1757 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001758 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1759 dockedOnWirelessCharger)) {
Michael Wrighte3001042019-02-05 00:13:14 +00001760 wakeUpNoUpdateLocked(now, PowerManager.WAKE_REASON_PLUGGED_IN,
1761 "android.server.power:PLUGGED:" + mIsPowered, Process.SYSTEM_UID,
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001762 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001763 }
1764 userActivityNoUpdateLocked(
1765 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001766
Beverlyac32c9a2018-01-31 16:10:41 -05001767 // only play charging sounds if boot is completed so charging sounds don't play
1768 // with potential notification sounds
1769 if (mBootCompleted) {
1770 if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
1771 && BatteryManager.isPlugWired(mPlugType)) {
Beverly91d0a632018-07-02 16:45:00 -04001772 mNotifier.onWiredChargingStarted(mForegroundProfile);
Beverlyac32c9a2018-01-31 16:10:41 -05001773 } else if (dockedOnWirelessCharger) {
Beverly91d0a632018-07-02 16:45:00 -04001774 mNotifier.onWirelessChargingStarted(mBatteryLevel, mForegroundProfile);
Beverlyac32c9a2018-01-31 16:10:41 -05001775 }
Jeff Brown84e27562012-12-07 13:56:34 -08001776 }
Jeff Brown96307042012-07-27 15:51:34 -07001777 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001778
Makoto Onukia3cd7b92018-03-19 14:47:05 -07001779 mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07001780 }
1781 }
1782
Jeff Brown3b971592013-01-09 18:46:37 -08001783 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1784 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001785 // Don't wake when powered unless configured to do so.
1786 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1787 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001788 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001789
Jeff Brown3b971592013-01-09 18:46:37 -08001790 // Don't wake when undocked from wireless charger.
1791 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001792 if (wasPowered && !mIsPowered
1793 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1794 return false;
1795 }
Jeff Brown3b971592013-01-09 18:46:37 -08001796
1797 // Don't wake when docked on wireless charger unless we are certain of it.
1798 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001799 if (!wasPowered && mIsPowered
1800 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001801 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001802 return false;
1803 }
1804
1805 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001806 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001807 return false;
1808 }
1809
Bryce Lee584a4452014-10-21 15:55:55 -07001810 // Don't wake while theater mode is enabled.
1811 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1812 return false;
1813 }
1814
Adrian Roos56021892017-02-27 20:25:09 +01001815 // On Always On Display, SystemUI shows the charging indicator
1816 if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
1817 return false;
1818 }
1819
Jeff Brown9fca9e92012-10-05 14:42:56 -07001820 // Otherwise wake up!
1821 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001822 }
1823
Jeff Brown96307042012-07-27 15:51:34 -07001824 /**
1825 * Updates the value of mStayOn.
1826 * Sets DIRTY_STAY_ON if a change occurred.
1827 */
1828 private void updateStayOnLocked(int dirty) {
1829 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001830 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001831 if (mStayOnWhilePluggedInSetting != 0
1832 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001833 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001834 } else {
1835 mStayOn = false;
1836 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001837
1838 if (mStayOn != wasStayOn) {
1839 mDirty |= DIRTY_STAY_ON;
1840 }
Jeff Brown96307042012-07-27 15:51:34 -07001841 }
1842 }
1843
1844 /**
1845 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1846 * Note that most wake-locks are ignored when the system is asleep.
1847 *
1848 * This function must have no other side-effects.
1849 */
Jeff Brownec083212013-09-11 20:45:25 -07001850 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001851 private void updateWakeLockSummaryLocked(int dirty) {
1852 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1853 mWakeLockSummary = 0;
1854
Pavel Grafov28939982017-10-03 15:11:52 +01001855 final int numProfiles = mProfilePowerState.size();
1856 for (int i = 0; i < numProfiles; i++) {
1857 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
1858 }
1859
Jeff Brown96307042012-07-27 15:51:34 -07001860 final int numWakeLocks = mWakeLocks.size();
1861 for (int i = 0; i < numWakeLocks; i++) {
1862 final WakeLock wakeLock = mWakeLocks.get(i);
Pavel Grafov28939982017-10-03 15:11:52 +01001863 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
1864 mWakeLockSummary |= wakeLockFlags;
1865 for (int j = 0; j < numProfiles; j++) {
1866 final ProfilePowerState profile = mProfilePowerState.valueAt(j);
1867 if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
1868 profile.mWakeLockSummary |= wakeLockFlags;
1869 }
Jeff Brown96307042012-07-27 15:51:34 -07001870 }
1871 }
1872
Pavel Grafov28939982017-10-03 15:11:52 +01001873 mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
1874 for (int i = 0; i < numProfiles; i++) {
1875 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1876 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
Jeff Brownc2932a12014-11-20 18:04:05 -08001877 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001878
Jeff Brown96307042012-07-27 15:51:34 -07001879 if (DEBUG_SPEW) {
1880 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001881 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001882 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1883 }
1884 }
1885 }
1886
Pavel Grafov28939982017-10-03 15:11:52 +01001887 private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
1888 // Cancel wake locks that make no sense based on the current state.
1889 if (mWakefulness != WAKEFULNESS_DOZING) {
1890 wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
1891 }
1892 if (mWakefulness == WAKEFULNESS_ASLEEP
1893 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1894 wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1895 | WAKE_LOCK_BUTTON_BRIGHT);
1896 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1897 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1898 }
1899 }
1900
1901 // Infer implied wake locks where necessary based on the current state.
1902 if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1903 if (mWakefulness == WAKEFULNESS_AWAKE) {
1904 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1905 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1906 wakeLockSummary |= WAKE_LOCK_CPU;
1907 }
1908 }
1909 if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1910 wakeLockSummary |= WAKE_LOCK_CPU;
1911 }
1912
1913 return wakeLockSummary;
1914 }
1915
1916 /** Get wake lock summary flags that correspond to the given wake lock. */
1917 private int getWakeLockSummaryFlags(WakeLock wakeLock) {
1918 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1919 case PowerManager.PARTIAL_WAKE_LOCK:
1920 if (!wakeLock.mDisabled) {
1921 // We only respect this if the wake lock is not disabled.
1922 return WAKE_LOCK_CPU;
1923 }
1924 break;
1925 case PowerManager.FULL_WAKE_LOCK:
1926 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1927 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1928 return WAKE_LOCK_SCREEN_BRIGHT;
1929 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1930 return WAKE_LOCK_SCREEN_DIM;
1931 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1932 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1933 case PowerManager.DOZE_WAKE_LOCK:
1934 return WAKE_LOCK_DOZE;
1935 case PowerManager.DRAW_WAKE_LOCK:
1936 return WAKE_LOCK_DRAW;
1937 }
1938 return 0;
1939 }
1940
1941 private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
1942 if (wakeLock.mWorkSource != null) {
1943 for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
1944 final int uid = wakeLock.mWorkSource.get(k);
1945 if (userId == UserHandle.getUserId(uid)) {
1946 return true;
1947 }
1948 }
Narayan Kamath2f916ed2017-12-29 13:02:15 +00001949
1950 final ArrayList<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
1951 if (workChains != null) {
1952 for (int k = 0; k < workChains.size(); k++) {
1953 final int uid = workChains.get(k).getAttributionUid();
1954 if (userId == UserHandle.getUserId(uid)) {
1955 return true;
1956 }
1957 }
1958 }
Pavel Grafov28939982017-10-03 15:11:52 +01001959 }
1960 return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
1961 }
1962
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001963 void checkForLongWakeLocks() {
1964 synchronized (mLock) {
1965 final long now = SystemClock.uptimeMillis();
1966 mNotifyLongDispatched = now;
1967 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
1968 long nextCheckTime = Long.MAX_VALUE;
1969 final int numWakeLocks = mWakeLocks.size();
1970 for (int i = 0; i < numWakeLocks; i++) {
1971 final WakeLock wakeLock = mWakeLocks.get(i);
1972 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1973 == PowerManager.PARTIAL_WAKE_LOCK) {
1974 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
1975 if (wakeLock.mAcquireTime < when) {
1976 // This wake lock has exceeded the long acquire time, report!
1977 notifyWakeLockLongStartedLocked(wakeLock);
1978 } else {
1979 // This wake lock could still become a long one, at this time.
1980 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
1981 if (checkTime < nextCheckTime) {
1982 nextCheckTime = checkTime;
1983 }
1984 }
1985 }
1986 }
1987 }
1988 mNotifyLongScheduled = 0;
1989 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
1990 if (nextCheckTime != Long.MAX_VALUE) {
1991 mNotifyLongNextCheck = nextCheckTime;
1992 enqueueNotifyLongMsgLocked(nextCheckTime);
1993 } else {
1994 mNotifyLongNextCheck = 0;
1995 }
1996 }
1997 }
1998
Jeff Brown96307042012-07-27 15:51:34 -07001999 /**
2000 * Updates the value of mUserActivitySummary to summarize the user requested
2001 * state of the system such as whether the screen should be bright or dim.
2002 * Note that user activity is ignored when the system is asleep.
2003 *
2004 * This function must have no other side-effects.
2005 */
2006 private void updateUserActivitySummaryLocked(long now, int dirty) {
2007 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07002008 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08002009 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002010 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
2011
2012 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08002013 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07002014 || mWakefulness == WAKEFULNESS_DREAMING
2015 || mWakefulness == WAKEFULNESS_DOZING) {
Pavel Grafov28939982017-10-03 15:11:52 +01002016 final long sleepTimeout = getSleepTimeoutLocked();
2017 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
2018 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002019 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Pavel Grafov28939982017-10-03 15:11:52 +01002020 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
Jeff Brown96307042012-07-27 15:51:34 -07002021
2022 mUserActivitySummary = 0;
2023 if (mLastUserActivityTime >= mLastWakeTime) {
2024 nextTimeout = mLastUserActivityTime
2025 + screenOffTimeout - screenDimDuration;
2026 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002027 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002028 } else {
2029 nextTimeout = mLastUserActivityTime + screenOffTimeout;
2030 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002031 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002032 }
2033 }
2034 }
2035 if (mUserActivitySummary == 0
2036 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
2037 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07002038 if (now < nextTimeout) {
Andrii Kulian9407a6b2017-05-24 12:24:09 -07002039 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
2040 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
Jeff Brown970d4132014-07-19 11:33:47 -07002041 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2042 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
2043 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2044 }
Jeff Brown96307042012-07-27 15:51:34 -07002045 }
2046 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002047
Jeff Brown05af6ad2014-09-30 20:54:30 -07002048 if (mUserActivitySummary == 0) {
2049 if (sleepTimeout >= 0) {
2050 final long anyUserActivity = Math.max(mLastUserActivityTime,
2051 mLastUserActivityTimeNoChangeLights);
2052 if (anyUserActivity >= mLastWakeTime) {
2053 nextTimeout = anyUserActivity + sleepTimeout;
2054 if (now < nextTimeout) {
2055 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2056 }
2057 }
2058 } else {
2059 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2060 nextTimeout = -1;
2061 }
2062 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002063
2064 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07002065 if ((mUserActivitySummary &
2066 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07002067 // Device is being kept awake by recent user activity
2068 if (nextTimeout >= now && mOverriddenTimeout == -1) {
2069 // Save when the next timeout would have occurred
2070 mOverriddenTimeout = nextTimeout;
2071 }
Mojtaba2d80edc2015-09-18 16:35:24 -07002072 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002073 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2074 nextTimeout = -1;
2075 }
2076
Lucas Dupin0a5d7972019-01-16 18:52:30 -08002077 if ((mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0) {
2078 nextTimeout = mAttentionDetector.updateUserActivity(nextTimeout);
2079 }
2080
Pavel Grafov28939982017-10-03 15:11:52 +01002081 if (nextProfileTimeout > 0) {
2082 nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2083 }
2084
Jeff Brown05af6ad2014-09-30 20:54:30 -07002085 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002086 scheduleUserInactivityTimeout(nextTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07002087 }
2088 } else {
2089 mUserActivitySummary = 0;
2090 }
2091
2092 if (DEBUG_SPEW) {
2093 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002094 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002095 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2096 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2097 }
2098 }
2099 }
2100
Pavel Grafov28939982017-10-03 15:11:52 +01002101 private void scheduleUserInactivityTimeout(long timeMs) {
2102 final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2103 msg.setAsynchronous(true);
2104 mHandler.sendMessageAtTime(msg, timeMs);
2105 }
2106
2107 /**
2108 * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2109 */
2110 private long getNextProfileTimeoutLocked(long now) {
2111 long nextTimeout = -1;
2112 final int numProfiles = mProfilePowerState.size();
2113 for (int i = 0; i < numProfiles; i++) {
2114 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2115 final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2116 if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2117 nextTimeout = timeout;
2118 }
2119 }
2120 return nextTimeout;
2121 }
2122
Jeff Brown96307042012-07-27 15:51:34 -07002123 /**
2124 * Called when a user activity timeout has occurred.
2125 * Simply indicates that something about user activity has changed so that the new
2126 * state can be recomputed when the power state is updated.
2127 *
2128 * This function must have no other side-effects besides setting the dirty
2129 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
2130 */
2131 private void handleUserActivityTimeout() { // runs on handler thread
2132 synchronized (mLock) {
2133 if (DEBUG_SPEW) {
2134 Slog.d(TAG, "handleUserActivityTimeout");
2135 }
2136
2137 mDirty |= DIRTY_USER_ACTIVITY;
2138 updatePowerStateLocked();
2139 }
2140 }
2141
Pavel Grafov28939982017-10-03 15:11:52 +01002142 private long getSleepTimeoutLocked() {
2143 final long timeout = mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -07002144 if (timeout <= 0) {
2145 return -1;
2146 }
2147 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2148 }
2149
Pavel Grafov28939982017-10-03 15:11:52 +01002150 private long getScreenOffTimeoutLocked(long sleepTimeout) {
2151 long timeout = mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002152 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2153 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2154 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002155 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002156 timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002157 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002158 if (sleepTimeout >= 0) {
2159 timeout = Math.min(timeout, sleepTimeout);
2160 }
Jeff Brown27736f52014-05-20 17:17:10 -07002161 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002162 }
2163
Pavel Grafov28939982017-10-03 15:11:52 +01002164 private long getScreenDimDurationLocked(long screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07002165 return Math.min(mMaximumScreenDimDurationConfig,
Pavel Grafov28939982017-10-03 15:11:52 +01002166 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07002167 }
2168
2169 /**
2170 * Updates the wakefulness of the device.
2171 *
Jeff Brown26875502014-01-30 21:47:47 -08002172 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07002173 * based on the current wake locks and user activity state. It may modify mDirty
2174 * if the wakefulness changes.
2175 *
2176 * Returns true if the wakefulness changed and we need to restart power state calculation.
2177 */
2178 private boolean updateWakefulnessLocked(int dirty) {
2179 boolean changed = false;
2180 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07002181 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
2182 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002183 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2184 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002185 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07002186 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002187 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07002188 if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07002189 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002190 } else {
2191 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07002192 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002193 }
Jeff Brown96307042012-07-27 15:51:34 -07002194 }
2195 }
2196 return changed;
2197 }
2198
Jeff Brown645832d2012-10-03 14:57:03 -07002199 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07002200 * Returns true if the device should automatically nap and start dreaming when the user
2201 * activity timeout has expired and it's bedtime.
2202 */
2203 private boolean shouldNapAtBedTimeLocked() {
2204 return mDreamsActivateOnSleepSetting
2205 || (mDreamsActivateOnDockSetting
2206 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2207 }
2208
2209 /**
Jeff Brown645832d2012-10-03 14:57:03 -07002210 * Returns true if the device should go to sleep now.
2211 * Also used when exiting a dream to determine whether we should go back
2212 * to being fully awake or else go to sleep for good.
2213 */
Jeff Brown96307042012-07-27 15:51:34 -07002214 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07002215 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07002216 }
2217
2218 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07002219 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07002220 * or the stay on while powered setting. We also keep the phone awake when
2221 * the proximity sensor returns a positive result so that the device does not
2222 * lock while in a phone call. This function only controls whether the device
2223 * will go to sleep or dream which is independent of whether it will be allowed
2224 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07002225 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07002226 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07002227 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07002228 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07002229 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07002230 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002231 | USER_ACTIVITY_SCREEN_DIM)) != 0
2232 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07002233 }
2234
2235 /**
2236 * Determines whether to post a message to the sandman to update the dream state.
2237 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002238 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002239 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07002240 | DIRTY_USER_ACTIVITY
2241 | DIRTY_WAKE_LOCKS
2242 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002243 | DIRTY_SETTINGS
2244 | DIRTY_IS_POWERED
2245 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07002246 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07002247 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2248 if (mDisplayReady) {
2249 scheduleSandmanLocked();
2250 }
Jeff Brown96307042012-07-27 15:51:34 -07002251 }
2252 }
2253
2254 private void scheduleSandmanLocked() {
2255 if (!mSandmanScheduled) {
2256 mSandmanScheduled = true;
2257 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2258 msg.setAsynchronous(true);
2259 mHandler.sendMessage(msg);
2260 }
2261 }
2262
2263 /**
Jeff Brown26875502014-01-30 21:47:47 -08002264 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07002265 *
2266 * We do this asynchronously because we must call out of the power manager to start
2267 * the dream and we don't want to hold our lock while doing so. There is a risk that
2268 * the device will wake or go to sleep in the meantime so we have to handle that case.
2269 */
2270 private void handleSandman() { // runs on handler thread
2271 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08002272 final boolean startDreaming;
2273 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07002274 synchronized (mLock) {
2275 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08002276 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07002277 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002278 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08002279 mSandmanSummoned = false;
2280 } else {
2281 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002282 }
2283 }
2284
Jeff Brown96307042012-07-27 15:51:34 -07002285 // Start dreaming if needed.
2286 // We only control the dream on the handler thread, so we don't need to worry about
2287 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08002288 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07002289 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08002290 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07002291 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002292 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08002293 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07002294 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002295 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08002296 } else {
2297 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002298 }
2299
2300 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07002301 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08002302 // Remember the initial battery level when the dream started.
2303 if (startDreaming && isDreaming) {
2304 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2305 if (wakefulness == WAKEFULNESS_DOZING) {
2306 Slog.i(TAG, "Dozing...");
2307 } else {
2308 Slog.i(TAG, "Dreaming...");
2309 }
2310 }
2311
2312 // If preconditions changed, wait for the next iteration to determine
2313 // whether the dream should continue (or be restarted).
2314 if (mSandmanSummoned || mWakefulness != wakefulness) {
2315 return; // wait for next cycle
2316 }
2317
2318 // Determine whether the dream should continue.
2319 if (wakefulness == WAKEFULNESS_DREAMING) {
2320 if (isDreaming && canDreamLocked()) {
2321 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002322 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002323 - mDreamsBatteryLevelDrainCutoffConfig
2324 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002325 // If the user activity timeout expired and the battery appears
2326 // to be draining faster than it is charging then stop dreaming
2327 // and go to sleep.
2328 Slog.i(TAG, "Stopping dream because the battery appears to "
2329 + "be draining faster than it is charging. "
2330 + "Battery level when dream started: "
2331 + mBatteryLevelWhenDreamStarted + "%. "
2332 + "Battery level now: " + mBatteryLevel + "%.");
2333 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002334 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002335 }
Jeff Brown96307042012-07-27 15:51:34 -07002336 }
Jeff Brown26875502014-01-30 21:47:47 -08002337
2338 // Dream has ended or will be stopped. Update the power state.
2339 if (isItBedTimeYetLocked()) {
2340 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
Jeff Brownc12035c2014-08-13 18:52:25 -07002341 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002342 updatePowerStateLocked();
2343 } else {
Michael Wrighte3001042019-02-05 00:13:14 +00002344 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
2345 PowerManager.WAKE_REASON_UNKNOWN,
2346 "android.server.power:DREAM_FINISHED", Process.SYSTEM_UID,
2347 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002348 updatePowerStateLocked();
2349 }
2350 } else if (wakefulness == WAKEFULNESS_DOZING) {
2351 if (isDreaming) {
2352 return; // continue dozing
2353 }
2354
2355 // Doze has ended or will be stopped. Update the power state.
Jeff Brownc12035c2014-08-13 18:52:25 -07002356 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002357 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002358 }
Jeff Brown96307042012-07-27 15:51:34 -07002359 }
2360
Jeff Brown26875502014-01-30 21:47:47 -08002361 // Stop dream.
2362 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002363 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002364 }
2365 }
2366
2367 /**
Jeff Brown26875502014-01-30 21:47:47 -08002368 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002369 */
2370 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002371 if (mWakefulness != WAKEFULNESS_DREAMING
2372 || !mDreamsSupportedConfig
2373 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002374 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordon3107d292016-09-20 15:50:35 -07002375 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002376 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2377 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002378 || !mBootCompleted) {
2379 return false;
2380 }
2381 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002382 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002383 return false;
2384 }
2385 if (!mIsPowered
2386 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2387 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2388 return false;
2389 }
2390 if (mIsPowered
2391 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2392 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2393 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002394 }
2395 }
Jeff Brown26875502014-01-30 21:47:47 -08002396 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002397 }
2398
Jeff Brown96307042012-07-27 15:51:34 -07002399 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002400 * Returns true if the device is allowed to doze in its current state.
2401 */
2402 private boolean canDozeLocked() {
2403 return mWakefulness == WAKEFULNESS_DOZING;
2404 }
2405
2406 /**
Jeff Brown96307042012-07-27 15:51:34 -07002407 * Updates the display power state asynchronously.
2408 * When the update is finished, mDisplayReady will be set to true. The display
2409 * controller posts a message to tell us when the actual display power state
2410 * has been updated so we come back here to double-check and finish up.
2411 *
2412 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002413 *
2414 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002415 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002416 private boolean updateDisplayPowerStateLocked(int dirty) {
2417 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002418 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2419 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordon3107d292016-09-20 15:50:35 -07002420 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2421 DIRTY_QUIESCENT)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07002422 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002423
Jeff Browne333e672014-10-28 13:48:55 -07002424 // Determine appropriate screen brightness and auto-brightness adjustments.
Michael Wrightd8460232018-01-16 18:04:59 +00002425 final boolean autoBrightness;
2426 final int screenBrightnessOverride;
Michael Wright9f818ea2016-07-29 19:59:39 +01002427 if (!mBootCompleted) {
2428 // Keep the brightness steady during boot. This requires the
2429 // bootloader brightness and the default brightness to be identical.
2430 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002431 screenBrightnessOverride = mScreenBrightnessSettingDefault;
Michael Wright9f818ea2016-07-29 19:59:39 +01002432 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002433 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002434 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManager;
2435 } else {
2436 autoBrightness = (mScreenBrightnessModeSetting ==
2437 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2438 screenBrightnessOverride = -1;
Jeff Brown96307042012-07-27 15:51:34 -07002439 }
Jeff Browne333e672014-10-28 13:48:55 -07002440
2441 // Update display power request.
Michael Wrightd8460232018-01-16 18:04:59 +00002442 mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
Jeff Brown96307042012-07-27 15:51:34 -07002443 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002444 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Santos Cordon3107d292016-09-20 15:50:35 -07002445 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002446
jackqdyulei92681e82017-02-28 11:26:28 -08002447 updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2448
Jeff Brown970d4132014-07-19 11:33:47 -07002449 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2450 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Ivan Podogov56bc6d02018-02-26 16:04:24 +00002451 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0
2452 && !mDrawWakeLockOverrideFromSidekick) {
Chris Phoenix10a4a642017-09-25 13:21:00 -07002453 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2454 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2455 }
2456 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2457 mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2458 }
Jeff Brownc2932a12014-11-20 18:04:05 -08002459 }
Jeff Brown970d4132014-07-19 11:33:47 -07002460 mDisplayPowerRequest.dozeScreenBrightness =
2461 mDozeScreenBrightnessOverrideFromDreamManager;
2462 } else {
2463 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2464 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2465 }
2466
Jeff Brown131206b2014-04-08 17:27:14 -07002467 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002468 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002469 mRequestWaitForNegativeProximity = false;
2470
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002471 if ((dirty & DIRTY_QUIESCENT) != 0) {
2472 sQuiescent = false;
2473 }
Jeff Brown96307042012-07-27 15:51:34 -07002474 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002475 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002476 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002477 + ", mWakefulness=" + mWakefulness
2478 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2479 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002480 + ", mBootCompleted=" + mBootCompleted
Michael Wrightd8460232018-01-16 18:04:59 +00002481 + ", screenBrightnessOverride=" + screenBrightnessOverride
2482 + ", useAutoBrightness=" + autoBrightness
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002483 + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
Santos Cordon3107d292016-09-20 15:50:35 -07002484 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002485 + ", sQuiescent=" + sQuiescent);
Jeff Brown96307042012-07-27 15:51:34 -07002486 }
2487 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002488 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002489 }
2490
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002491 private void updateScreenBrightnessBoostLocked(int dirty) {
2492 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2493 if (mScreenBrightnessBoostInProgress) {
2494 final long now = SystemClock.uptimeMillis();
2495 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2496 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2497 final long boostTimeout = mLastScreenBrightnessBoostTime +
2498 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2499 if (boostTimeout > now) {
2500 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2501 msg.setAsynchronous(true);
2502 mHandler.sendMessageAtTime(msg, boostTimeout);
2503 return;
2504 }
Jeff Browne333e672014-10-28 13:48:55 -07002505 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002506 mScreenBrightnessBoostInProgress = false;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07002507 mNotifier.onScreenBrightnessBoostChanged();
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002508 userActivityNoUpdateLocked(now,
2509 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002510 }
Jeff Browne333e672014-10-28 13:48:55 -07002511 }
2512 }
2513
Santos Cordon3107d292016-09-20 15:50:35 -07002514 private boolean shouldBoostScreenBrightness() {
2515 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2516 }
2517
Jeff Brown96307042012-07-27 15:51:34 -07002518 private static boolean isValidBrightness(int value) {
2519 return value >= 0 && value <= 255;
2520 }
2521
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002522 @VisibleForTesting
2523 int getDesiredScreenPolicyLocked() {
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002524 if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
Jeff Brown970d4132014-07-19 11:33:47 -07002525 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002526 }
2527
Jeff Brown2175e9c2014-09-12 16:11:07 -07002528 if (mWakefulness == WAKEFULNESS_DOZING) {
2529 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2530 return DisplayPowerRequest.POLICY_DOZE;
2531 }
Lucas Dupin16cfe452018-02-08 13:14:50 -08002532 if (mDozeAfterScreenOff) {
Jeff Brown2175e9c2014-09-12 16:11:07 -07002533 return DisplayPowerRequest.POLICY_OFF;
2534 }
2535 // Fall through and preserve the current screen policy if not configured to
2536 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002537 }
2538
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002539 // It is important that POLICY_VR check happens after the wakefulness checks above so
2540 // that VR-mode does not prevent displays from transitioning to the correct state when
2541 // dozing or sleeping.
2542 if (mIsVrModeEnabled) {
2543 return DisplayPowerRequest.POLICY_VR;
2544 }
2545
Jeff Brown96307042012-07-27 15:51:34 -07002546 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2547 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002548 || !mBootCompleted
2549 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002550 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002551 }
2552
Jeff Brown970d4132014-07-19 11:33:47 -07002553 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002554 }
2555
Jeff Brown131206b2014-04-08 17:27:14 -07002556 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2557 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002558 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002559
Jeff Brown96307042012-07-27 15:51:34 -07002560 @Override
2561 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002562 synchronized (mLock) {
2563 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2564 updatePowerStateLocked();
2565 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002566 }
2567
2568 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002569 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002570 synchronized (mLock) {
2571 mProximityPositive = true;
2572 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2573 updatePowerStateLocked();
2574 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002575 }
2576
2577 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002578 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002579 synchronized (mLock) {
2580 mProximityPositive = false;
2581 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2582 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2583 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2584 updatePowerStateLocked();
2585 }
Jeff Brown96307042012-07-27 15:51:34 -07002586 }
Jeff Brown131206b2014-04-08 17:27:14 -07002587
2588 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002589 public void onDisplayStateChange(int state) {
2590 // This method is only needed to support legacy display blanking behavior
2591 // where the display's power state is coupled to suspend or to the power HAL.
2592 // The order of operations matters here.
2593 synchronized (mLock) {
2594 if (mDisplayState != state) {
2595 mDisplayState = state;
2596 if (state == Display.STATE_OFF) {
2597 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2598 setHalInteractiveModeLocked(false);
2599 }
2600 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2601 setHalAutoSuspendModeLocked(true);
2602 }
2603 } else {
2604 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2605 setHalAutoSuspendModeLocked(false);
2606 }
2607 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2608 setHalInteractiveModeLocked(true);
2609 }
2610 }
2611 }
2612 }
2613 }
2614
2615 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002616 public void acquireSuspendBlocker() {
2617 mDisplaySuspendBlocker.acquire();
2618 }
2619
2620 @Override
2621 public void releaseSuspendBlocker() {
2622 mDisplaySuspendBlocker.release();
2623 }
2624
2625 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002626 public String toString() {
2627 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002628 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002629 }
2630 }
Jeff Brown96307042012-07-27 15:51:34 -07002631 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002632
Jeff Brown96307042012-07-27 15:51:34 -07002633 private boolean shouldUseProximitySensorLocked() {
Santos Cordon3107d292016-09-20 15:50:35 -07002634 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002635 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002636
Jeff Brown96307042012-07-27 15:51:34 -07002637 /**
2638 * Updates the suspend blocker that keeps the CPU alive.
2639 *
2640 * This function must have no other side-effects.
2641 */
2642 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002643 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002644 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2645 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002646 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002647
2648 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002649 // FIXME We should consider just leaving auto-suspend enabled forever since
2650 // we already hold the necessary wakelocks.
2651 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2652 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002653 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002654
2655 // First acquire suspend blockers if needed.
2656 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2657 mWakeLockSuspendBlocker.acquire();
2658 mHoldingWakeLockSuspendBlocker = true;
2659 }
2660 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2661 mDisplaySuspendBlocker.acquire();
2662 mHoldingDisplaySuspendBlocker = true;
2663 }
2664
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002665 // Inform the power HAL about interactive mode.
2666 // Although we could set interactive strictly based on the wakefulness
2667 // as reported by isInteractive(), it is actually more desirable to track
2668 // the display policy state instead so that the interactive state observed
2669 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2670 // Refer to getDesiredScreenPolicyLocked() for details.
2671 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2672 // When becoming non-interactive, we want to defer sending this signal
2673 // until the display is actually ready so that all transitions have
2674 // completed. This is probably a good sign that things have gotten
2675 // too tangled over here...
2676 if (interactive || mDisplayReady) {
2677 setHalInteractiveModeLocked(interactive);
2678 }
2679 }
2680
Jeff Brown27f7a862012-12-12 15:43:31 -08002681 // Then release suspend blockers if needed.
2682 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2683 mWakeLockSuspendBlocker.release();
2684 mHoldingWakeLockSuspendBlocker = false;
2685 }
2686 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2687 mDisplaySuspendBlocker.release();
2688 mHoldingDisplaySuspendBlocker = false;
2689 }
Jeff Brown26875502014-01-30 21:47:47 -08002690
2691 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002692 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2693 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002694 }
Jeff Brown96307042012-07-27 15:51:34 -07002695 }
2696
Jeff Brownec083212013-09-11 20:45:25 -07002697 /**
2698 * Return true if we must keep a suspend blocker active on behalf of the display.
2699 * We do so if the screen is on or is in transition between states.
2700 */
Jeff Brown26875502014-01-30 21:47:47 -08002701 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002702 if (!mDisplayReady) {
2703 return true;
2704 }
Jeff Brown970d4132014-07-19 11:33:47 -07002705 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002706 // If we asked for the screen to be on but it is off due to the proximity
2707 // sensor then we may suspend but only if the configuration allows it.
2708 // On some hardware it may not be safe to suspend because the proximity
2709 // sensor may not be correctly configured as a wake-up source.
2710 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2711 || !mSuspendWhenScreenOffDueToProximityConfig) {
2712 return true;
2713 }
2714 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002715 if (mScreenBrightnessBoostInProgress) {
2716 return true;
2717 }
Jeff Brown26875502014-01-30 21:47:47 -08002718 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002719 return false;
2720 }
2721
Jeff Brown037c33e2014-04-09 00:31:55 -07002722 private void setHalAutoSuspendModeLocked(boolean enable) {
2723 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002724 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002725 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002726 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002727 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002728 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2729 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002730 mNativeWrapper.nativeSetAutoSuspend(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002731 } finally {
2732 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2733 }
Jeff Brown26875502014-01-30 21:47:47 -08002734 }
2735 }
2736
Jeff Brown037c33e2014-04-09 00:31:55 -07002737 private void setHalInteractiveModeLocked(boolean enable) {
2738 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002739 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002740 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002741 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002742 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002743 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2744 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002745 mNativeWrapper.nativeSetInteractive(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002746 } finally {
2747 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2748 }
Jeff Brown26875502014-01-30 21:47:47 -08002749 }
2750 }
2751
Jeff Brown037c33e2014-04-09 00:31:55 -07002752 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002753 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08002754 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002755 }
2756 }
2757
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002758 private boolean setLowPowerModeInternal(boolean enabled) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002759 synchronized (mLock) {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002760 if (DEBUG) {
2761 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
2762 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002763 if (mIsPowered) {
2764 return false;
2765 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002766
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002767 mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002768
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002769 return true;
2770 }
2771 }
2772
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002773 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002774 synchronized (mLock) {
2775 return mDeviceIdleMode;
2776 }
2777 }
2778
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002779 boolean isLightDeviceIdleModeInternal() {
2780 synchronized (mLock) {
2781 return mLightDeviceIdleMode;
2782 }
2783 }
2784
Jeff Brown96307042012-07-27 15:51:34 -07002785 private void handleBatteryStateChangedLocked() {
2786 mDirty |= DIRTY_BATTERY_STATE;
2787 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002788 }
2789
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002790 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002791 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07002792 if (mHandler == null || !mSystemReady) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07002793 if (RescueParty.isAttemptingFactoryReset()) {
2794 // If we're stuck in a really low-level reboot loop, and a
2795 // rescue party is trying to prompt the user for a factory data
2796 // reset, we must GET TO DA CHOPPA!
2797 PowerManagerService.lowLevelReboot(reason);
2798 } else {
2799 throw new IllegalStateException("Too early to call shutdown() or reboot()");
2800 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002801 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002802
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002803 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07002804 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002805 public void run() {
2806 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002807 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002808 ShutdownThread.rebootSafeMode(getUiContext(), confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002809 } else if (haltMode == HALT_MODE_REBOOT) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002810 ShutdownThread.reboot(getUiContext(), reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002811 } else {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002812 ShutdownThread.shutdown(getUiContext(), reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002813 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002814 }
San Mehat1e512792010-01-07 10:40:29 -08002815 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002816 };
Jeff Brown96307042012-07-27 15:51:34 -07002817
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002818 // ShutdownThread must run on a looper capable of displaying the UI.
Michael Wright64c820d2017-03-21 12:36:55 +00002819 Message msg = Message.obtain(UiThread.getHandler(), runnable);
Jeff Brown96307042012-07-27 15:51:34 -07002820 msg.setAsynchronous(true);
Michael Wright64c820d2017-03-21 12:36:55 +00002821 UiThread.getHandler().sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002822
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002823 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002824 if (wait) {
2825 synchronized (runnable) {
2826 while (true) {
2827 try {
2828 runnable.wait();
2829 } catch (InterruptedException e) {
2830 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002831 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002832 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002833 }
2834 }
2835
Jeff Brown96307042012-07-27 15:51:34 -07002836 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08002837 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07002838 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002839 public void run() {
2840 throw new RuntimeException(message);
2841 }
Dan Egnor60d87622009-12-16 16:32:58 -08002842 };
2843 try {
2844 t.start();
2845 t.join();
2846 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002847 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08002848 }
2849 }
2850
jackqdyulei92681e82017-02-28 11:26:28 -08002851 @VisibleForTesting
2852 void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
2853 PowerSaveState state = mBatterySaverPolicy.
Kweku Adams9f488e22019-01-14 16:25:08 -08002854 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS);
jackqdyulei92681e82017-02-28 11:26:28 -08002855 displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
2856 displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
2857 }
2858
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002859 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07002860 Settings.Global.putInt(mContext.getContentResolver(),
2861 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 }
2863
Pavel Grafov28939982017-10-03 15:11:52 +01002864 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
2865 if (userId < 0) {
2866 Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
2867 return;
2868 }
Jeff Brown96307042012-07-27 15:51:34 -07002869 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01002870 // System-wide timeout
2871 if (userId == UserHandle.USER_SYSTEM) {
2872 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2873 } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
2874 mProfilePowerState.delete(userId);
2875 } else {
2876 final ProfilePowerState profile = mProfilePowerState.get(userId);
2877 if (profile != null) {
2878 profile.mScreenOffTimeout = timeMs;
2879 } else {
2880 mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
2881 // We need to recalculate wake locks for the new profile state.
2882 mDirty |= DIRTY_WAKE_LOCKS;
2883 }
2884 }
Jeff Brown96307042012-07-27 15:51:34 -07002885 mDirty |= DIRTY_SETTINGS;
2886 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 }
2888 }
2889
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002890 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002891 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002892 if (mDeviceIdleMode == enabled) {
2893 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002894 }
Felipe Lemeea014392016-09-06 13:59:54 -07002895 mDeviceIdleMode = enabled;
2896 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002897 }
Felipe Lemeea014392016-09-06 13:59:54 -07002898 if (enabled) {
2899 EventLogTags.writeDeviceIdleOnPhase("power");
2900 } else {
2901 EventLogTags.writeDeviceIdleOffPhase("power");
2902 }
2903 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002904 }
2905
2906 boolean setLightDeviceIdleModeInternal(boolean enabled) {
2907 synchronized (mLock) {
2908 if (mLightDeviceIdleMode != enabled) {
2909 mLightDeviceIdleMode = enabled;
2910 return true;
2911 }
2912 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002913 }
2914 }
2915
2916 void setDeviceIdleWhitelistInternal(int[] appids) {
2917 synchronized (mLock) {
2918 mDeviceIdleWhitelist = appids;
2919 if (mDeviceIdleMode) {
2920 updateWakeLockDisabledStatesLocked();
2921 }
2922 }
2923 }
2924
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002925 void setDeviceIdleTempWhitelistInternal(int[] appids) {
2926 synchronized (mLock) {
2927 mDeviceIdleTempWhitelist = appids;
2928 if (mDeviceIdleMode) {
2929 updateWakeLockDisabledStatesLocked();
2930 }
2931 }
2932 }
2933
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002934 void startUidChangesInternal() {
2935 synchronized (mLock) {
2936 mUidsChanging = true;
2937 }
2938 }
2939
2940 void finishUidChangesInternal() {
2941 synchronized (mLock) {
2942 mUidsChanging = false;
2943 if (mUidsChanged) {
2944 updateWakeLockDisabledStatesLocked();
2945 mUidsChanged = false;
2946 }
2947 }
2948 }
2949
2950 private void handleUidStateChangeLocked() {
2951 if (mUidsChanging) {
2952 mUidsChanged = true;
2953 } else {
2954 updateWakeLockDisabledStatesLocked();
2955 }
2956 }
2957
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002958 void updateUidProcStateInternal(int uid, int procState) {
2959 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002960 UidState state = mUidState.get(uid);
2961 if (state == null) {
2962 state = new UidState(uid);
2963 mUidState.put(uid, state);
2964 }
Dianne Hackborn951ea692016-11-02 10:41:53 -07002965 final boolean oldShouldAllow = state.mProcState
2966 <= ActivityManager.PROCESS_STATE_RECEIVER;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002967 state.mProcState = procState;
Dianne Hackborn951ea692016-11-02 10:41:53 -07002968 if (state.mNumWakeLocks > 0) {
2969 if (mDeviceIdleMode) {
2970 handleUidStateChangeLocked();
2971 } else if (!state.mActive && oldShouldAllow !=
2972 (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
2973 // If this uid is not active, but the process state has changed such
2974 // that we may still want to allow it to hold a wake lock, then take care of it.
2975 handleUidStateChangeLocked();
2976 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002977 }
2978 }
2979 }
2980
2981 void uidGoneInternal(int uid) {
2982 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002983 final int index = mUidState.indexOfKey(uid);
2984 if (index >= 0) {
2985 UidState state = mUidState.valueAt(index);
2986 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
2987 state.mActive = false;
2988 mUidState.removeAt(index);
2989 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
2990 handleUidStateChangeLocked();
2991 }
2992 }
2993 }
2994 }
2995
2996 void uidActiveInternal(int uid) {
2997 synchronized (mLock) {
2998 UidState state = mUidState.get(uid);
2999 if (state == null) {
3000 state = new UidState(uid);
3001 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
3002 mUidState.put(uid, state);
3003 }
3004 state.mActive = true;
3005 if (state.mNumWakeLocks > 0) {
3006 handleUidStateChangeLocked();
3007 }
3008 }
3009 }
3010
3011 void uidIdleInternal(int uid) {
3012 synchronized (mLock) {
3013 UidState state = mUidState.get(uid);
3014 if (state != null) {
3015 state.mActive = false;
3016 if (state.mNumWakeLocks > 0) {
3017 handleUidStateChangeLocked();
3018 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003019 }
3020 }
3021 }
3022
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003023 private void updateWakeLockDisabledStatesLocked() {
3024 boolean changed = false;
3025 final int numWakeLocks = mWakeLocks.size();
3026 for (int i = 0; i < numWakeLocks; i++) {
3027 final WakeLock wakeLock = mWakeLocks.get(i);
3028 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003029 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003030 if (setWakeLockDisabledStateLocked(wakeLock)) {
3031 changed = true;
3032 if (wakeLock.mDisabled) {
3033 // This wake lock is no longer being respected.
3034 notifyWakeLockReleasedLocked(wakeLock);
3035 } else {
3036 notifyWakeLockAcquiredLocked(wakeLock);
3037 }
3038 }
3039 }
3040 }
3041 if (changed) {
3042 mDirty |= DIRTY_WAKE_LOCKS;
3043 updatePowerStateLocked();
3044 }
3045 }
3046
3047 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
3048 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3049 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003050 boolean disabled = false;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003051 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
3052 if (appid >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003053 // Cached inactive processes are never allowed to hold wake locks.
3054 if (mConstants.NO_CACHED_WAKE_LOCKS) {
Santos Cordon12f92eb2019-02-01 21:28:47 +00003055 disabled = mForceSuspendActive
3056 || (!wakeLock.mUidState.mActive && wakeLock.mUidState.mProcState
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003057 != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Santos Cordon12f92eb2019-02-01 21:28:47 +00003058 wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003059 }
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003060 if (mDeviceIdleMode) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003061 // If we are in idle mode, we will also ignore all partial wake locks that are
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003062 // for application uids that are not whitelisted.
3063 final UidState state = wakeLock.mUidState;
3064 if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
3065 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
3066 state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003067 state.mProcState >
3068 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003069 disabled = true;
3070 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003071 }
3072 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003073 if (wakeLock.mDisabled != disabled) {
3074 wakeLock.mDisabled = disabled;
3075 return true;
3076 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003077 }
3078 return false;
3079 }
3080
Jeff Brown96307042012-07-27 15:51:34 -07003081 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3082 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
Pavel Grafov28939982017-10-03 15:11:52 +01003083 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003085
Jeff Brown96307042012-07-27 15:51:34 -07003086 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003087 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07003088 synchronized (mLock) {
3089 if (!mSystemReady) {
3090 return;
3091 }
3092 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07003093 }
Jeff Brown96307042012-07-27 15:51:34 -07003094
3095 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003096 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07003097 }
3098
Lucas Dupin16cfe452018-02-08 13:14:50 -08003099 private void setDozeAfterScreenOffInternal(boolean on) {
3100 synchronized (mLock) {
3101 mDozeAfterScreenOff = on;
3102 }
3103 }
3104
Jeff Browne333e672014-10-28 13:48:55 -07003105 private void boostScreenBrightnessInternal(long eventTime, int uid) {
3106 synchronized (mLock) {
3107 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3108 || eventTime < mLastScreenBrightnessBoostTime) {
3109 return;
3110 }
3111
3112 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3113 mLastScreenBrightnessBoostTime = eventTime;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003114 if (!mScreenBrightnessBoostInProgress) {
3115 mScreenBrightnessBoostInProgress = true;
3116 mNotifier.onScreenBrightnessBoostChanged();
3117 }
Jeff Browne333e672014-10-28 13:48:55 -07003118 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3119
3120 userActivityNoUpdateLocked(eventTime,
3121 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3122 updatePowerStateLocked();
3123 }
3124 }
3125
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003126 private boolean isScreenBrightnessBoostedInternal() {
3127 synchronized (mLock) {
3128 return mScreenBrightnessBoostInProgress;
3129 }
3130 }
3131
Jeff Browne333e672014-10-28 13:48:55 -07003132 /**
3133 * Called when a screen brightness boost timeout has occurred.
3134 *
3135 * This function must have no other side-effects besides setting the dirty
3136 * bit and calling update power state.
3137 */
3138 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3139 synchronized (mLock) {
3140 if (DEBUG_SPEW) {
3141 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3142 }
3143
3144 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3145 updatePowerStateLocked();
3146 }
3147 }
3148
Jeff Brown96307042012-07-27 15:51:34 -07003149 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3150 synchronized (mLock) {
3151 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3152 mScreenBrightnessOverrideFromWindowManager = brightness;
3153 mDirty |= DIRTY_SETTINGS;
3154 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003155 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003156 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003157 }
3158
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003159 private void setUserInactiveOverrideFromWindowManagerInternal() {
3160 synchronized (mLock) {
3161 mUserInactiveOverrideFromWindowManager = true;
3162 mDirty |= DIRTY_USER_ACTIVITY;
3163 updatePowerStateLocked();
3164 }
3165 }
3166
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003167 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3168 synchronized (mLock) {
3169 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3170 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
Michael Wrightb55e3a12018-03-06 15:14:06 +00003171 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003172 mDirty |= DIRTY_SETTINGS;
3173 updatePowerStateLocked();
3174 }
3175 }
3176 }
3177
Jeff Brown970d4132014-07-19 11:33:47 -07003178 private void setDozeOverrideFromDreamManagerInternal(
3179 int screenState, int screenBrightness) {
3180 synchronized (mLock) {
3181 if (mDozeScreenStateOverrideFromDreamManager != screenState
3182 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3183 mDozeScreenStateOverrideFromDreamManager = screenState;
3184 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
3185 mDirty |= DIRTY_SETTINGS;
3186 updatePowerStateLocked();
3187 }
3188 }
3189 }
3190
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003191 private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
3192 synchronized (mLock) {
3193 if (mDrawWakeLockOverrideFromSidekick != keepState) {
3194 mDrawWakeLockOverrideFromSidekick = keepState;
3195 mDirty |= DIRTY_SETTINGS;
3196 updatePowerStateLocked();
3197 }
3198 }
3199 }
3200
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003201 @VisibleForTesting
3202 void setVrModeEnabled(boolean enabled) {
3203 mIsVrModeEnabled = enabled;
3204 }
3205
Makoto Onukia7d8c4d2017-11-20 15:20:16 -08003206 private void powerHintInternal(int hintId, int data) {
3207 // Maybe filter the event.
3208 switch (hintId) {
3209 case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3210 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3211 return;
3212 }
3213 break;
3214 }
3215
Santos Cordon64a6e612018-08-22 19:27:04 +01003216 mNativeWrapper.nativeSendPowerHint(hintId, data);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003217 }
3218
Alex Kershaw2418ea92018-10-19 17:17:49 +01003219 @VisibleForTesting
3220 boolean wasDeviceIdleForInternal(long ms) {
3221 synchronized (mLock) {
3222 return mLastUserActivityTime + ms < SystemClock.uptimeMillis();
3223 }
3224 }
3225
3226 @VisibleForTesting
3227 void onUserActivity() {
3228 synchronized (mLock) {
3229 mLastUserActivityTime = SystemClock.uptimeMillis();
3230 }
3231 }
3232
Santos Cordon12f92eb2019-02-01 21:28:47 +00003233 private boolean forceSuspendInternal(int uid) {
3234 try {
3235 synchronized (mLock) {
3236 mForceSuspendActive = true;
3237 // Place the system in an non-interactive state
3238 goToSleepInternal(SystemClock.uptimeMillis(),
3239 PowerManager.GO_TO_SLEEP_REASON_FORCE_SUSPEND,
3240 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, uid);
3241
3242 // Disable all the partial wake locks as well
3243 updateWakeLockDisabledStatesLocked();
3244 }
3245
3246 Slog.i(TAG, "Force-Suspending (uid " + uid + ")...");
3247 boolean success = mNativeWrapper.nativeForceSuspend();
3248 if (!success) {
3249 Slog.i(TAG, "Force-Suspending failed in native.");
3250 }
3251 return success;
3252 } finally {
3253 synchronized (mLock) {
3254 mForceSuspendActive = false;
3255 // Re-enable wake locks once again.
3256 updateWakeLockDisabledStatesLocked();
3257 }
3258 }
3259 }
3260
Jeff Brown96307042012-07-27 15:51:34 -07003261 /**
3262 * Low-level function turn the device off immediately, without trying
3263 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07003264 *
3265 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003266 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07003267 public static void lowLevelShutdown(String reason) {
3268 if (reason == null) {
3269 reason = "";
3270 }
3271 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07003272 }
3273
3274 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08003275 * Low-level function to reboot the device. On success, this
3276 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07003277 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07003278 *
3279 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003280 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003281 public static void lowLevelReboot(String reason) {
3282 if (reason == null) {
3283 reason = "";
3284 }
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003285
3286 // If the reason is "quiescent", it means that the boot process should proceed
3287 // without turning on the screen/lights.
3288 // The "quiescent" property is sticky, meaning that any number
3289 // of subsequent reboots should honor the property until it is reset.
3290 if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3291 sQuiescent = true;
3292 reason = "";
Dmitri Plotnikov690c6bd2017-05-10 16:26:38 -07003293 } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3294 sQuiescent = true;
3295 reason = reason.substring(0,
3296 reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3297 }
3298
3299 if (reason.equals(PowerManager.REBOOT_RECOVERY)
3300 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3301 reason = "recovery";
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003302 }
3303
3304 if (sQuiescent) {
3305 // Pass the optional "quiescent" argument to the bootloader to let it know
3306 // that it should not turn the screen/lights on.
3307 reason = reason + ",quiescent";
3308 }
3309
3310 SystemProperties.set("sys.powerctl", "reboot," + reason);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003311 try {
Tao Bao90237f72015-05-21 16:25:19 -07003312 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003313 } catch (InterruptedException e) {
3314 Thread.currentThread().interrupt();
3315 }
Tao Bao90237f72015-05-21 16:25:19 -07003316 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07003317 }
3318
3319 @Override // Watchdog.Monitor implementation
3320 public void monitor() {
3321 // Grab and release lock for watchdog monitor to detect deadlocks.
3322 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003323 }
Jeff Brown96307042012-07-27 15:51:34 -07003324 }
3325
Jeff Brown6f357d32014-01-15 20:40:55 -08003326 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07003327 pw.println("POWER MANAGER (dumpsys power)\n");
3328
Jeff Brown3b971592013-01-09 18:46:37 -08003329 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07003330 synchronized (mLock) {
3331 pw.println("Power Manager State:");
Dianne Hackborn0ef403e2017-01-24 18:22:15 -08003332 mConstants.dump(pw);
Jeff Brown96307042012-07-27 15:51:34 -07003333 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08003334 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3335 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07003336 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07003337 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07003338 pw.println(" mBatteryLevel=" + mBatteryLevel);
3339 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07003340 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07003341 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07003342 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07003343 pw.println(" mBootCompleted=" + mBootCompleted);
3344 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07003345 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3346 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003347 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003348 pw.print(" mNotifyLongScheduled=");
3349 if (mNotifyLongScheduled == 0) {
3350 pw.print("(none)");
3351 } else {
3352 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3353 }
3354 pw.println();
3355 pw.print(" mNotifyLongDispatched=");
3356 if (mNotifyLongDispatched == 0) {
3357 pw.print("(none)");
3358 } else {
3359 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3360 }
3361 pw.println();
3362 pw.print(" mNotifyLongNextCheck=");
3363 if (mNotifyLongNextCheck == 0) {
3364 pw.print("(none)");
3365 } else {
3366 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3367 }
3368 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003369 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3370 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3371 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08003372 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07003373 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003374 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003375 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
3376 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003377 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07003378 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3379 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Calin Tatarua3805722018-08-09 16:41:28 +02003380 pw.println(" mLastSleepReason=" + PowerManager.sleepReasonToString(mLastSleepReason));
Jeff Brown96307042012-07-27 15:51:34 -07003381 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3382 pw.println(" mLastUserActivityTimeNoChangeLights="
3383 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07003384 pw.println(" mLastInteractivePowerHintTime="
3385 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07003386 pw.println(" mLastScreenBrightnessBoostTime="
3387 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3388 pw.println(" mScreenBrightnessBoostInProgress="
3389 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07003390 pw.println(" mDisplayReady=" + mDisplayReady);
3391 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08003392 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07003393
3394 pw.println();
3395 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07003396 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
3397 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3398 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
3399 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003400 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
3401 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07003402 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3403 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3404 pw.println(" mTheaterModeEnabled="
3405 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07003406 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
3407 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003408 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003409 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3410 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
3411 + mDreamsActivatedOnSleepByDefaultConfig);
3412 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
3413 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08003414 pw.println(" mDreamsEnabledOnBatteryConfig="
3415 + mDreamsEnabledOnBatteryConfig);
3416 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
3417 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3418 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3419 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3420 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
3421 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003422 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04003423 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07003424 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Lucas Dupin16cfe452018-02-08 13:14:50 -08003425 pw.println(" mDozeAfterScreenOff=" + mDozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -07003426 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3427 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3428 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003429 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07003430 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003431 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
3432 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3433 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3434 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
3435 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
3436 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
3437 pw.println(" mScreenBrightnessOverrideFromWindowManager="
3438 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003439 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
3440 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003441 pw.println(" mUserInactiveOverrideFromWindowManager="
3442 + mUserInactiveOverrideFromWindowManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003443 pw.println(" mDozeScreenStateOverrideFromDreamManager="
3444 + mDozeScreenStateOverrideFromDreamManager);
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003445 pw.println(" mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
Jeff Brown970d4132014-07-19 11:33:47 -07003446 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
3447 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07003448 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
3449 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
3450 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
Jason Monk27bbb2d2015-03-31 16:46:39 -04003451 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003452 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Pavel Grafov28939982017-10-03 15:11:52 +01003453 pw.println(" mForegroundProfile=" + mForegroundProfile);
Jeff Brown96307042012-07-27 15:51:34 -07003454
Pavel Grafov28939982017-10-03 15:11:52 +01003455 final long sleepTimeout = getSleepTimeoutLocked();
3456 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3457 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003458 pw.println();
Jeff Brown05af6ad2014-09-30 20:54:30 -07003459 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003460 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3461 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3462
Jeff Brown96307042012-07-27 15:51:34 -07003463 pw.println();
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003464 pw.print("UID states (changing=");
3465 pw.print(mUidsChanging);
3466 pw.print(" changed=");
3467 pw.print(mUidsChanged);
3468 pw.println("):");
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003469 for (int i=0; i<mUidState.size(); i++) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003470 final UidState state = mUidState.valueAt(i);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003471 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003472 pw.print(": ");
3473 if (state.mActive) pw.print(" ACTIVE ");
3474 else pw.print("INACTIVE ");
3475 pw.print(" count=");
3476 pw.print(state.mNumWakeLocks);
3477 pw.print(" state=");
3478 pw.println(state.mProcState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003479 }
3480
3481 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003482 pw.println("Looper state:");
3483 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3484
3485 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003486 pw.println("Wake Locks: size=" + mWakeLocks.size());
3487 for (WakeLock wl : mWakeLocks) {
3488 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003489 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003490
Jeff Brown96307042012-07-27 15:51:34 -07003491 pw.println();
3492 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3493 for (SuspendBlocker sb : mSuspendBlockers) {
3494 pw.println(" " + sb);
3495 }
3496
Jeff Brownc38c9be2012-10-04 13:16:19 -07003497 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003498 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003499
jackqdyulei455e90a2017-02-09 15:29:16 -08003500 mBatterySaverPolicy.dump(pw);
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003501 mBatterySaverStateMachine.dump(pw);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08003502 mAttentionDetector.dump(pw);
jackqdyulei455e90a2017-02-09 15:29:16 -08003503
Pavel Grafov28939982017-10-03 15:11:52 +01003504 pw.println();
3505 final int numProfiles = mProfilePowerState.size();
3506 pw.println("Profile power states: size=" + numProfiles);
3507 for (int i = 0; i < numProfiles; i++) {
3508 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3509 pw.print(" mUserId=");
3510 pw.print(profile.mUserId);
3511 pw.print(" mScreenOffTimeout=");
3512 pw.print(profile.mScreenOffTimeout);
3513 pw.print(" mWakeLockSummary=");
3514 pw.print(profile.mWakeLockSummary);
3515 pw.print(" mLastUserActivityTime=");
3516 pw.print(profile.mLastUserActivityTime);
3517 pw.print(" mLockingNotified=");
3518 pw.println(profile.mLockingNotified);
3519 }
3520
Jeff Brown3b971592013-01-09 18:46:37 -08003521 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003522 }
3523
Jeff Brown3b971592013-01-09 18:46:37 -08003524 if (wcd != null) {
3525 wcd.dump(pw);
3526 }
Jeff Brown96307042012-07-27 15:51:34 -07003527 }
3528
Netta P958d0a52017-02-07 11:20:55 -08003529 private void dumpProto(FileDescriptor fd) {
3530 final WirelessChargerDetector wcd;
3531 final ProtoOutputStream proto = new ProtoOutputStream(fd);
3532
3533 synchronized (mLock) {
3534 mConstants.dumpProto(proto);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003535 proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3536 proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3537 proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3538 proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3539 proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3540 proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
Netta P958d0a52017-02-07 11:20:55 -08003541 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003542 PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
Netta P958d0a52017-02-07 11:20:55 -08003543 mBatteryLevelWhenDreamStarted);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003544 proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3545 proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3546 proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3547 proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3548 proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
Netta P958d0a52017-02-07 11:20:55 -08003549 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003550 PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003551 mHalAutoSuspendModeEnabled);
3552 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003553 PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003554 mHalInteractiveModeEnabled);
3555
Kweku Adamse6b00c22017-10-23 16:46:45 -07003556 final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003557 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003558 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
Netta P958d0a52017-02-07 11:20:55 -08003559 (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3560 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003561 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003562 (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3563 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003564 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003565 (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3566 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003567 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003568 (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3569 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003570 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
Netta P958d0a52017-02-07 11:20:55 -08003571 (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3572 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003573 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
Netta P958d0a52017-02-07 11:20:55 -08003574 (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3575 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003576 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
Netta P958d0a52017-02-07 11:20:55 -08003577 (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3578 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003579 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
Netta P958d0a52017-02-07 11:20:55 -08003580 (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3581 proto.end(activeWakeLocksToken);
3582
Kweku Adamse6b00c22017-10-23 16:46:45 -07003583 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3584 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3585 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
Netta P958d0a52017-02-07 11:20:55 -08003586
Kweku Adamse6b00c22017-10-23 16:46:45 -07003587 final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
Netta P958d0a52017-02-07 11:20:55 -08003588 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003589 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003590 (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3591 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003592 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003593 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3594 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003595 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
Netta P958d0a52017-02-07 11:20:55 -08003596 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
3597 proto.end(userActivityToken);
3598
3599 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003600 PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
Netta P958d0a52017-02-07 11:20:55 -08003601 mRequestWaitForNegativeProximity);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003602 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
3603 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003604 proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
3605 proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
3606 proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
Netta P958d0a52017-02-07 11:20:55 -08003607
3608 for (int id : mDeviceIdleWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003609 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003610 }
3611 for (int id : mDeviceIdleTempWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003612 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003613 }
3614
Kweku Adamse6b00c22017-10-23 16:46:45 -07003615 proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
3616 proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
3617 proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
Netta P958d0a52017-02-07 11:20:55 -08003618 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003619 PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
Netta P958d0a52017-02-07 11:20:55 -08003620 mLastUserActivityTimeNoChangeLights);
3621 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003622 PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003623 mLastInteractivePowerHintTime);
3624 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003625 PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003626 mLastScreenBrightnessBoostTime);
3627 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003628 PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
Netta P958d0a52017-02-07 11:20:55 -08003629 mScreenBrightnessBoostInProgress);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003630 proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
Netta P958d0a52017-02-07 11:20:55 -08003631 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003632 PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003633 mHoldingWakeLockSuspendBlocker);
3634 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003635 PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003636 mHoldingDisplaySuspendBlocker);
3637
3638 final long settingsAndConfigurationToken =
Kweku Adamse6b00c22017-10-23 16:46:45 -07003639 proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
Netta P958d0a52017-02-07 11:20:55 -08003640 proto.write(
3641 PowerServiceSettingsAndConfigurationDumpProto
3642 .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
3643 mDecoupleHalAutoSuspendModeFromDisplayConfig);
3644 proto.write(
3645 PowerServiceSettingsAndConfigurationDumpProto
3646 .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
3647 mDecoupleHalInteractiveModeFromDisplayConfig);
3648 proto.write(
3649 PowerServiceSettingsAndConfigurationDumpProto
3650 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
3651 mWakeUpWhenPluggedOrUnpluggedConfig);
3652 proto.write(
3653 PowerServiceSettingsAndConfigurationDumpProto
3654 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
3655 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3656 proto.write(
3657 PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
3658 mTheaterModeEnabled);
3659 proto.write(
3660 PowerServiceSettingsAndConfigurationDumpProto
3661 .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
3662 mSuspendWhenScreenOffDueToProximityConfig);
3663 proto.write(
3664 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
3665 mDreamsSupportedConfig);
3666 proto.write(
3667 PowerServiceSettingsAndConfigurationDumpProto
3668 .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
3669 mDreamsEnabledByDefaultConfig);
3670 proto.write(
3671 PowerServiceSettingsAndConfigurationDumpProto
3672 .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
3673 mDreamsActivatedOnSleepByDefaultConfig);
3674 proto.write(
3675 PowerServiceSettingsAndConfigurationDumpProto
3676 .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
3677 mDreamsActivatedOnDockByDefaultConfig);
3678 proto.write(
3679 PowerServiceSettingsAndConfigurationDumpProto
3680 .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
3681 mDreamsEnabledOnBatteryConfig);
3682 proto.write(
3683 PowerServiceSettingsAndConfigurationDumpProto
3684 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
3685 mDreamsBatteryLevelMinimumWhenPoweredConfig);
3686 proto.write(
3687 PowerServiceSettingsAndConfigurationDumpProto
3688 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
3689 mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3690 proto.write(
3691 PowerServiceSettingsAndConfigurationDumpProto
3692 .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
3693 mDreamsBatteryLevelDrainCutoffConfig);
3694 proto.write(
3695 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
3696 mDreamsEnabledSetting);
3697 proto.write(
3698 PowerServiceSettingsAndConfigurationDumpProto
3699 .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
3700 mDreamsActivateOnSleepSetting);
3701 proto.write(
3702 PowerServiceSettingsAndConfigurationDumpProto
3703 .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
3704 mDreamsActivateOnDockSetting);
3705 proto.write(
3706 PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
Lucas Dupin16cfe452018-02-08 13:14:50 -08003707 mDozeAfterScreenOff);
Netta P958d0a52017-02-07 11:20:55 -08003708 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003709 PowerServiceSettingsAndConfigurationDumpProto
3710 .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
3711 mMinimumScreenOffTimeoutConfig);
3712 proto.write(
3713 PowerServiceSettingsAndConfigurationDumpProto
3714 .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
3715 mMaximumScreenDimDurationConfig);
3716 proto.write(
3717 PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
3718 mMaximumScreenDimRatioConfig);
3719 proto.write(
3720 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
3721 mScreenOffTimeoutSetting);
3722 proto.write(
3723 PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
3724 mSleepTimeoutSetting);
3725 proto.write(
3726 PowerServiceSettingsAndConfigurationDumpProto
3727 .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
Pavel Grafov28939982017-10-03 15:11:52 +01003728 // Clamp to int32
3729 Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
Netta P958d0a52017-02-07 11:20:55 -08003730 proto.write(
3731 PowerServiceSettingsAndConfigurationDumpProto
3732 .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
3733 isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
3734
3735 final long stayOnWhilePluggedInToken =
3736 proto.start(
3737 PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
3738 proto.write(
3739 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3740 .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
3741 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
3742 proto.write(
3743 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3744 .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
3745 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
3746 proto.write(
3747 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3748 .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
3749 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
3750 != 0));
3751 proto.end(stayOnWhilePluggedInToken);
3752
3753 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003754 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
3755 mScreenBrightnessModeSetting);
3756 proto.write(
3757 PowerServiceSettingsAndConfigurationDumpProto
3758 .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
3759 mScreenBrightnessOverrideFromWindowManager);
3760 proto.write(
3761 PowerServiceSettingsAndConfigurationDumpProto
3762 .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
3763 mUserActivityTimeoutOverrideFromWindowManager);
3764 proto.write(
3765 PowerServiceSettingsAndConfigurationDumpProto
3766 .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
3767 mUserInactiveOverrideFromWindowManager);
3768 proto.write(
3769 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003770 .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
3771 mDozeScreenStateOverrideFromDreamManager);
3772 proto.write(
3773 PowerServiceSettingsAndConfigurationDumpProto
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003774 .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
3775 mDrawWakeLockOverrideFromSidekick);
3776 proto.write(
3777 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003778 .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
3779 mDozeScreenBrightnessOverrideFromDreamManager);
3780
3781 final long screenBrightnessSettingLimitsToken =
3782 proto.start(
3783 PowerServiceSettingsAndConfigurationDumpProto
3784 .SCREEN_BRIGHTNESS_SETTING_LIMITS);
3785 proto.write(
3786 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3787 .SETTING_MINIMUM,
3788 mScreenBrightnessSettingMinimum);
3789 proto.write(
3790 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3791 .SETTING_MAXIMUM,
3792 mScreenBrightnessSettingMaximum);
3793 proto.write(
3794 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3795 .SETTING_DEFAULT,
3796 mScreenBrightnessSettingDefault);
Netta P958d0a52017-02-07 11:20:55 -08003797 proto.end(screenBrightnessSettingLimitsToken);
3798
3799 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003800 PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
3801 mDoubleTapWakeEnabled);
3802 proto.write(
3803 PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
3804 mIsVrModeEnabled);
3805 proto.end(settingsAndConfigurationToken);
3806
Pavel Grafov28939982017-10-03 15:11:52 +01003807 final long sleepTimeout = getSleepTimeoutLocked();
3808 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3809 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003810 proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
3811 proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
3812 proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
3813 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
3814 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
Netta P958d0a52017-02-07 11:20:55 -08003815
3816 for (int i = 0; i < mUidState.size(); i++) {
3817 final UidState state = mUidState.valueAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003818 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
Netta P958d0a52017-02-07 11:20:55 -08003819 final int uid = mUidState.keyAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003820 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
3821 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
3822 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
3823 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
Bookatzdb026a22018-01-10 19:01:56 -08003824 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
3825 ActivityManager.processStateAmToProto(state.mProcState));
Netta P958d0a52017-02-07 11:20:55 -08003826 proto.end(uIDToken);
3827 }
3828
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003829 mBatterySaverStateMachine.dumpProto(proto,
3830 PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
3831
Kweku Adamse6b00c22017-10-23 16:46:45 -07003832 mHandler.getLooper().writeToProto(proto, PowerManagerServiceDumpProto.LOOPER);
Netta P958d0a52017-02-07 11:20:55 -08003833
3834 for (WakeLock wl : mWakeLocks) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003835 wl.writeToProto(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003836 }
3837
3838 for (SuspendBlocker sb : mSuspendBlockers) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003839 sb.writeToProto(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
Netta P958d0a52017-02-07 11:20:55 -08003840 }
3841 wcd = mWirelessChargerDetector;
3842 }
3843
3844 if (wcd != null) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003845 wcd.writeToProto(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
Netta P958d0a52017-02-07 11:20:55 -08003846 }
3847 proto.flush();
3848 }
3849
Daichi Hirono82ab9802016-03-02 13:23:29 +09003850 private void incrementBootCount() {
3851 synchronized (mLock) {
3852 int count;
3853 try {
3854 count = Settings.Global.getInt(
3855 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
3856 } catch (SettingNotFoundException e) {
3857 count = 0;
3858 }
3859 Settings.Global.putInt(
3860 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
3861 }
3862 }
3863
Jeff Brown96307042012-07-27 15:51:34 -07003864 private static WorkSource copyWorkSource(WorkSource workSource) {
3865 return workSource != null ? new WorkSource(workSource) : null;
3866 }
3867
3868 private final class BatteryReceiver extends BroadcastReceiver {
3869 @Override
3870 public void onReceive(Context context, Intent intent) {
3871 synchronized (mLock) {
3872 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003873 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003874 }
3875 }
3876
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003877 private final class DreamReceiver extends BroadcastReceiver {
3878 @Override
3879 public void onReceive(Context context, Intent intent) {
3880 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07003881 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003882 }
3883 }
3884 }
3885
Jeff Brownd4935962012-09-25 13:27:20 -07003886 private final class UserSwitchedReceiver extends BroadcastReceiver {
3887 @Override
3888 public void onReceive(Context context, Intent intent) {
3889 synchronized (mLock) {
3890 handleSettingsChangedLocked();
3891 }
3892 }
3893 }
3894
Jeff Brownec6aa592012-10-17 20:30:25 -07003895 private final class DockReceiver extends BroadcastReceiver {
3896 @Override
3897 public void onReceive(Context context, Intent intent) {
3898 synchronized (mLock) {
3899 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3900 Intent.EXTRA_DOCK_STATE_UNDOCKED);
3901 if (mDockState != dockState) {
3902 mDockState = dockState;
3903 mDirty |= DIRTY_DOCK_STATE;
3904 updatePowerStateLocked();
3905 }
3906 }
3907 }
3908 }
3909
Jeff Brown96307042012-07-27 15:51:34 -07003910 private final class SettingsObserver extends ContentObserver {
3911 public SettingsObserver(Handler handler) {
3912 super(handler);
3913 }
3914
3915 @Override
3916 public void onChange(boolean selfChange, Uri uri) {
3917 synchronized (mLock) {
3918 handleSettingsChangedLocked();
3919 }
3920 }
3921 }
3922
Ruben Brunkc7be3be2016-04-01 17:07:51 -07003923 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003924 @Override
3925 public void onVrStateChanged(boolean enabled) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07003926 powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
Santos Cordon3107d292016-09-20 15:50:35 -07003927
3928 synchronized (mLock) {
3929 if (mIsVrModeEnabled != enabled) {
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003930 setVrModeEnabled(enabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003931 mDirty |= DIRTY_VR_MODE_CHANGED;
3932 updatePowerStateLocked();
3933 }
3934 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003935 }
3936 };
3937
Jeff Brown96307042012-07-27 15:51:34 -07003938 /**
3939 * Handler for asynchronous operations performed by the power manager.
3940 */
3941 private final class PowerManagerHandler extends Handler {
3942 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07003943 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07003944 }
3945
3946 @Override
3947 public void handleMessage(Message msg) {
3948 switch (msg.what) {
3949 case MSG_USER_ACTIVITY_TIMEOUT:
3950 handleUserActivityTimeout();
3951 break;
3952 case MSG_SANDMAN:
3953 handleSandman();
3954 break;
Jeff Browne333e672014-10-28 13:48:55 -07003955 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
3956 handleScreenBrightnessBoostTimeout();
3957 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003958 case MSG_CHECK_FOR_LONG_WAKELOCKS:
3959 checkForLongWakeLocks();
3960 break;
Jeff Brown96307042012-07-27 15:51:34 -07003961 }
3962 }
3963 }
3964
3965 /**
3966 * Represents a wake lock that has been acquired by an application.
3967 */
3968 private final class WakeLock implements IBinder.DeathRecipient {
3969 public final IBinder mLock;
3970 public int mFlags;
3971 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003972 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07003973 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003974 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003975 public final int mOwnerUid;
3976 public final int mOwnerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003977 public final UidState mUidState;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003978 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07003979 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003980 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003981 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07003982
Dianne Hackborn713df152013-05-17 11:27:57 -07003983 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003984 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
3985 UidState uidState) {
Jeff Brown96307042012-07-27 15:51:34 -07003986 mLock = lock;
3987 mFlags = flags;
3988 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003989 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07003990 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003991 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07003992 mOwnerUid = ownerUid;
3993 mOwnerPid = ownerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003994 mUidState = uidState;
Jeff Brown96307042012-07-27 15:51:34 -07003995 }
3996
3997 @Override
3998 public void binderDied() {
3999 PowerManagerService.this.handleWakeLockDeath(this);
4000 }
4001
4002 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
4003 int ownerUid, int ownerPid) {
4004 return mFlags == flags
4005 && mTag.equals(tag)
4006 && hasSameWorkSource(workSource)
4007 && mOwnerUid == ownerUid
4008 && mOwnerPid == ownerPid;
4009 }
4010
Dianne Hackborn713df152013-05-17 11:27:57 -07004011 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004012 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07004013 if (!mPackageName.equals(packageName)) {
4014 throw new IllegalStateException("Existing wake lock package name changed: "
4015 + mPackageName + " to " + packageName);
4016 }
4017 if (mOwnerUid != ownerUid) {
4018 throw new IllegalStateException("Existing wake lock uid changed: "
4019 + mOwnerUid + " to " + ownerUid);
4020 }
4021 if (mOwnerPid != ownerPid) {
4022 throw new IllegalStateException("Existing wake lock pid changed: "
4023 + mOwnerPid + " to " + ownerPid);
4024 }
Jeff Brown96307042012-07-27 15:51:34 -07004025 mFlags = flags;
4026 mTag = tag;
4027 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004028 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004029 }
4030
4031 public boolean hasSameWorkSource(WorkSource workSource) {
Narayan Kamath607223f2018-02-19 14:09:02 +00004032 return Objects.equals(mWorkSource, workSource);
Jeff Brown96307042012-07-27 15:51:34 -07004033 }
4034
4035 public void updateWorkSource(WorkSource workSource) {
4036 mWorkSource = copyWorkSource(workSource);
4037 }
4038
4039 @Override
4040 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004041 StringBuilder sb = new StringBuilder();
4042 sb.append(getLockLevelString());
4043 sb.append(" '");
4044 sb.append(mTag);
4045 sb.append("'");
4046 sb.append(getLockFlagsString());
4047 if (mDisabled) {
4048 sb.append(" DISABLED");
4049 }
4050 if (mNotifiedAcquired) {
4051 sb.append(" ACQ=");
4052 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
4053 }
4054 if (mNotifiedLong) {
4055 sb.append(" LONG");
4056 }
4057 sb.append(" (uid=");
4058 sb.append(mOwnerUid);
4059 if (mOwnerPid != 0) {
4060 sb.append(" pid=");
4061 sb.append(mOwnerPid);
4062 }
4063 if (mWorkSource != null) {
4064 sb.append(" ws=");
4065 sb.append(mWorkSource);
4066 }
4067 sb.append(")");
4068 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07004069 }
4070
Netta P958d0a52017-02-07 11:20:55 -08004071 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4072 final long wakeLockToken = proto.start(fieldId);
4073 proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
4074 proto.write(WakeLockProto.TAG, mTag);
4075
4076 final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
4077 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
4078 (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
4079 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
4080 (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
4081 proto.end(wakeLockFlagsToken);
4082
4083 proto.write(WakeLockProto.IS_DISABLED, mDisabled);
4084 if (mNotifiedAcquired) {
4085 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
4086 }
4087 proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
4088 proto.write(WakeLockProto.UID, mOwnerUid);
4089 proto.write(WakeLockProto.PID, mOwnerPid);
4090
4091 if (mWorkSource != null) {
4092 mWorkSource.writeToProto(proto, WakeLockProto.WORK_SOURCE);
4093 }
4094 proto.end(wakeLockToken);
4095 }
4096
Jeff Brown26875502014-01-30 21:47:47 -08004097 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07004098 private String getLockLevelString() {
4099 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
4100 case PowerManager.FULL_WAKE_LOCK:
4101 return "FULL_WAKE_LOCK ";
4102 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
4103 return "SCREEN_BRIGHT_WAKE_LOCK ";
4104 case PowerManager.SCREEN_DIM_WAKE_LOCK:
4105 return "SCREEN_DIM_WAKE_LOCK ";
4106 case PowerManager.PARTIAL_WAKE_LOCK:
4107 return "PARTIAL_WAKE_LOCK ";
4108 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4109 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08004110 case PowerManager.DOZE_WAKE_LOCK:
4111 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08004112 case PowerManager.DRAW_WAKE_LOCK:
4113 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07004114 default:
4115 return "??? ";
4116 }
4117 }
4118
4119 private String getLockFlagsString() {
4120 String result = "";
4121 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4122 result += " ACQUIRE_CAUSES_WAKEUP";
4123 }
4124 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4125 result += " ON_AFTER_RELEASE";
4126 }
4127 return result;
4128 }
4129 }
4130
4131 private final class SuspendBlockerImpl implements SuspendBlocker {
4132 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07004133 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07004134 private int mReferenceCount;
4135
4136 public SuspendBlockerImpl(String name) {
4137 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07004138 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07004139 }
4140
4141 @Override
4142 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004143 try {
Jeff Brown96307042012-07-27 15:51:34 -07004144 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004145 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004146 + "\" was finalized without being released!");
4147 mReferenceCount = 0;
Santos Cordon64a6e612018-08-22 19:27:04 +01004148 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004149 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004150 }
4151 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07004152 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004153 }
4154 }
4155
Craig Mautner75fc9de2012-06-18 16:53:27 -07004156 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004157 public void acquire() {
4158 synchronized (this) {
4159 mReferenceCount += 1;
4160 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004161 if (DEBUG_SPEW) {
4162 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4163 }
Jeff Brown3edf5272014-08-14 19:25:14 -07004164 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Santos Cordon64a6e612018-08-22 19:27:04 +01004165 mNativeWrapper.nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07004166 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004167 }
4168 }
4169
Craig Mautner75fc9de2012-06-18 16:53:27 -07004170 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004171 public void release() {
4172 synchronized (this) {
4173 mReferenceCount -= 1;
4174 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004175 if (DEBUG_SPEW) {
4176 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4177 }
Santos Cordon64a6e612018-08-22 19:27:04 +01004178 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004179 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004180 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004181 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004182 + "\" was released without being acquired!", new Throwable());
4183 mReferenceCount = 0;
4184 }
4185 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004186 }
Jeff Brown96307042012-07-27 15:51:34 -07004187
4188 @Override
4189 public String toString() {
4190 synchronized (this) {
4191 return mName + ": ref count=" + mReferenceCount;
4192 }
4193 }
Netta P958d0a52017-02-07 11:20:55 -08004194
4195 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4196 final long sbToken = proto.start(fieldId);
4197 synchronized (this) {
4198 proto.write(SuspendBlockerProto.NAME, mName);
4199 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4200 }
4201 proto.end(sbToken);
4202 }
Jeff Brown96307042012-07-27 15:51:34 -07004203 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07004204
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004205 static final class UidState {
4206 final int mUid;
4207 int mNumWakeLocks;
4208 int mProcState;
4209 boolean mActive;
4210
4211 UidState(int uid) {
4212 mUid = uid;
4213 }
4214 }
4215
Santos Cordon64a6e612018-08-22 19:27:04 +01004216 @VisibleForTesting
4217 final class BinderService extends IPowerManager.Stub {
Jocelyn Dangf2c38c12017-03-31 14:03:37 -07004218 @Override
4219 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4220 FileDescriptor err, String[] args, ShellCallback callback,
4221 ResultReceiver resultReceiver) {
4222 (new PowerManagerShellCommand(this)).exec(
4223 this, in, out, err, args, callback, resultReceiver);
4224 }
4225
Jeff Brown6f357d32014-01-15 20:40:55 -08004226 @Override // Binder call
4227 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4228 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07004229 if (uid < 0) {
4230 uid = Binder.getCallingUid();
4231 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004232 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004233 }
4234
4235 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004236 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07004237 if (!mSystemReady) {
4238 // Service not ready yet, so who the heck cares about power hints, bah.
4239 return;
4240 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004241 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07004242 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004243 }
4244
4245 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004246 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004247 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004248 if (lock == null) {
4249 throw new IllegalArgumentException("lock must not be null");
4250 }
4251 if (packageName == null) {
4252 throw new IllegalArgumentException("packageName must not be null");
4253 }
4254 PowerManager.validateWakeLockParameters(flags, tag);
4255
4256 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07004257 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4258 mContext.enforceCallingOrSelfPermission(
4259 android.Manifest.permission.DEVICE_POWER, null);
4260 }
Narayan Kamath81822022017-12-08 11:56:01 +00004261 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004262 mContext.enforceCallingOrSelfPermission(
4263 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4264 } else {
4265 ws = null;
4266 }
4267
4268 final int uid = Binder.getCallingUid();
4269 final int pid = Binder.getCallingPid();
4270 final long ident = Binder.clearCallingIdentity();
4271 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004272 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004273 } finally {
4274 Binder.restoreCallingIdentity(ident);
4275 }
4276 }
4277
4278 @Override // Binder call
4279 public void releaseWakeLock(IBinder lock, int flags) {
4280 if (lock == null) {
4281 throw new IllegalArgumentException("lock must not be null");
4282 }
4283
4284 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4285
4286 final long ident = Binder.clearCallingIdentity();
4287 try {
4288 releaseWakeLockInternal(lock, flags);
4289 } finally {
4290 Binder.restoreCallingIdentity(ident);
4291 }
4292 }
4293
4294 @Override // Binder call
4295 public void updateWakeLockUids(IBinder lock, int[] uids) {
4296 WorkSource ws = null;
4297
4298 if (uids != null) {
4299 ws = new WorkSource();
4300 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4301 // one at a time?
4302 for (int i = 0; i < uids.length; i++) {
4303 ws.add(uids[i]);
4304 }
4305 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07004306 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004307 }
4308
4309 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07004310 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004311 if (lock == null) {
4312 throw new IllegalArgumentException("lock must not be null");
4313 }
4314
4315 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Narayan Kamath81822022017-12-08 11:56:01 +00004316 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004317 mContext.enforceCallingOrSelfPermission(
4318 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4319 } else {
4320 ws = null;
4321 }
4322
Dianne Hackbornd953c532014-08-16 18:17:38 -07004323 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004324 final long ident = Binder.clearCallingIdentity();
4325 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07004326 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004327 } finally {
4328 Binder.restoreCallingIdentity(ident);
4329 }
4330 }
4331
4332 @Override // Binder call
4333 public boolean isWakeLockLevelSupported(int level) {
4334 final long ident = Binder.clearCallingIdentity();
4335 try {
4336 return isWakeLockLevelSupportedInternal(level);
4337 } finally {
4338 Binder.restoreCallingIdentity(ident);
4339 }
4340 }
4341
4342 @Override // Binder call
4343 public void userActivity(long eventTime, int event, int flags) {
4344 final long now = SystemClock.uptimeMillis();
4345 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07004346 != PackageManager.PERMISSION_GRANTED
4347 && mContext.checkCallingOrSelfPermission(
4348 android.Manifest.permission.USER_ACTIVITY)
4349 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004350 // Once upon a time applications could call userActivity().
4351 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
4352 // request instead of throwing a SecurityException so we don't break old apps.
4353 synchronized (mLock) {
4354 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4355 mLastWarningAboutUserActivityPermission = now;
4356 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07004357 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4358 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08004359 + " pid=" + Binder.getCallingPid()
4360 + " uid=" + Binder.getCallingUid());
4361 }
4362 }
4363 return;
4364 }
4365
Jim Millerdca15d22015-06-16 20:55:13 -07004366 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004367 throw new IllegalArgumentException("event time must not be in the future");
4368 }
4369
4370 final int uid = Binder.getCallingUid();
4371 final long ident = Binder.clearCallingIdentity();
4372 try {
4373 userActivityInternal(eventTime, event, flags, uid);
4374 } finally {
4375 Binder.restoreCallingIdentity(ident);
4376 }
4377 }
4378
4379 @Override // Binder call
Michael Wrighte3001042019-02-05 00:13:14 +00004380 public void wakeUp(long eventTime, @WakeReason int reason, String details,
4381 String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004382 if (eventTime > SystemClock.uptimeMillis()) {
4383 throw new IllegalArgumentException("event time must not be in the future");
4384 }
4385
4386 mContext.enforceCallingOrSelfPermission(
4387 android.Manifest.permission.DEVICE_POWER, null);
4388
Jeff Brownc12035c2014-08-13 18:52:25 -07004389 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004390 final long ident = Binder.clearCallingIdentity();
4391 try {
Michael Wrighte3001042019-02-05 00:13:14 +00004392 wakeUpInternal(eventTime, reason, details, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004393 } finally {
4394 Binder.restoreCallingIdentity(ident);
4395 }
4396 }
4397
4398 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07004399 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004400 if (eventTime > SystemClock.uptimeMillis()) {
4401 throw new IllegalArgumentException("event time must not be in the future");
4402 }
4403
4404 mContext.enforceCallingOrSelfPermission(
4405 android.Manifest.permission.DEVICE_POWER, null);
4406
Jeff Brownc12035c2014-08-13 18:52:25 -07004407 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004408 final long ident = Binder.clearCallingIdentity();
4409 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004410 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004411 } finally {
4412 Binder.restoreCallingIdentity(ident);
4413 }
4414 }
4415
4416 @Override // Binder call
4417 public void nap(long eventTime) {
4418 if (eventTime > SystemClock.uptimeMillis()) {
4419 throw new IllegalArgumentException("event time must not be in the future");
4420 }
4421
4422 mContext.enforceCallingOrSelfPermission(
4423 android.Manifest.permission.DEVICE_POWER, null);
4424
Jeff Brownc12035c2014-08-13 18:52:25 -07004425 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004426 final long ident = Binder.clearCallingIdentity();
4427 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004428 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004429 } finally {
4430 Binder.restoreCallingIdentity(ident);
4431 }
4432 }
4433
4434 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07004435 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08004436 final long ident = Binder.clearCallingIdentity();
4437 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07004438 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08004439 } finally {
4440 Binder.restoreCallingIdentity(ident);
4441 }
4442 }
4443
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004444 @Override // Binder call
4445 public boolean isPowerSaveMode() {
4446 final long ident = Binder.clearCallingIdentity();
4447 try {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004448 return mBatterySaverController.isEnabled();
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004449 } finally {
4450 Binder.restoreCallingIdentity(ident);
4451 }
4452 }
4453
jackqdyulei455e90a2017-02-09 15:29:16 -08004454 // Binder call
4455 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4456 final long ident = Binder.clearCallingIdentity();
4457 try {
Kweku Adams9f488e22019-01-14 16:25:08 -08004458 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
jackqdyulei455e90a2017-02-09 15:29:16 -08004459 } finally {
4460 Binder.restoreCallingIdentity(ident);
4461 }
4462 }
4463
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004464 @Override // Binder call
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004465 public boolean setPowerSaveMode(boolean enabled) {
Salvador Martineza80bbab2018-09-24 10:36:11 -07004466 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4467 != PackageManager.PERMISSION_GRANTED) {
4468 mContext.enforceCallingOrSelfPermission(
4469 android.Manifest.permission.DEVICE_POWER, null);
4470 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004471 final long ident = Binder.clearCallingIdentity();
4472 try {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004473 return setLowPowerModeInternal(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004474 } finally {
4475 Binder.restoreCallingIdentity(ident);
4476 }
4477 }
4478
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004479 @Override // Binder call
Salvador Martinez812ea752018-10-19 13:03:20 -07004480 public boolean setDynamicPowerSavings(boolean dynamicPowerSavingsEnabled,
4481 int disableThreshold) {
4482 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER,
4483 "updateDynamicPowerSavings");
4484 final long ident = Binder.clearCallingIdentity();
4485 try {
4486 final ContentResolver resolver = mContext.getContentResolver();
4487 boolean success = Settings.Global.putInt(resolver,
4488 Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
4489 disableThreshold);
4490 if (success) {
4491 // abort updating if we weren't able to succeed on the threshold
4492 success &= Settings.Global.putInt(resolver,
4493 Settings.Global.DYNAMIC_POWER_SAVINGS_ENABLED,
4494 dynamicPowerSavingsEnabled ? 1 : 0);
4495 }
4496 return success;
4497 } finally {
4498 Binder.restoreCallingIdentity(ident);
4499 }
4500 }
4501
4502 @Override // Binder call
Kweku Adams9f488e22019-01-14 16:25:08 -08004503 public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
4504 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4505 != PackageManager.PERMISSION_GRANTED) {
4506 mContext.enforceCallingOrSelfPermission(
4507 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSavePolicy");
4508 }
4509 final long ident = Binder.clearCallingIdentity();
4510 try {
4511 return mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
4512 } finally {
4513 Binder.restoreCallingIdentity(ident);
4514 }
4515 }
4516
4517 @Override // Binder call
4518 public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
4519 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4520 != PackageManager.PERMISSION_GRANTED) {
4521 mContext.enforceCallingOrSelfPermission(
4522 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSaveEnabled");
4523 }
4524 final long ident = Binder.clearCallingIdentity();
4525 try {
4526 return mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
4527 } finally {
4528 Binder.restoreCallingIdentity(ident);
4529 }
4530 }
4531
4532 @Override // Binder call
Salvador Martinez812ea752018-10-19 13:03:20 -07004533 public int getPowerSaveMode() {
4534 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER, null);
4535 final long ident = Binder.clearCallingIdentity();
4536 try {
4537 return Settings.Global.getInt(mContext.getContentResolver(),
4538 Settings.Global.AUTOMATIC_POWER_SAVER_MODE,
4539 PowerManager.POWER_SAVER_MODE_PERCENTAGE);
4540 } finally {
4541 Binder.restoreCallingIdentity(ident);
4542 }
4543 }
4544
4545 @Override // Binder call
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004546 public boolean isDeviceIdleMode() {
4547 final long ident = Binder.clearCallingIdentity();
4548 try {
4549 return isDeviceIdleModeInternal();
4550 } finally {
4551 Binder.restoreCallingIdentity(ident);
4552 }
4553 }
4554
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004555 @Override // Binder call
4556 public boolean isLightDeviceIdleMode() {
4557 final long ident = Binder.clearCallingIdentity();
4558 try {
4559 return isLightDeviceIdleModeInternal();
4560 } finally {
4561 Binder.restoreCallingIdentity(ident);
4562 }
4563 }
4564
Jeff Brown6f357d32014-01-15 20:40:55 -08004565 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07004566 * Gets the reason for the last time the phone had to reboot.
4567 *
4568 * @return The reason the phone last shut down as an int or
Makoto Onuki66a78122017-11-14 15:03:21 -08004569 * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
Salvador Martineza6f7b252017-04-10 10:46:15 -07004570 */
4571 @Override // Binder call
4572 public int getLastShutdownReason() {
4573 mContext.enforceCallingOrSelfPermission(
4574 android.Manifest.permission.DEVICE_POWER, null);
4575
4576 final long ident = Binder.clearCallingIdentity();
4577 try {
Mark Salyzyn74ce8b32018-06-05 09:06:54 -07004578 return getLastShutdownReasonInternal(REBOOT_PROPERTY);
Salvador Martineza6f7b252017-04-10 10:46:15 -07004579 } finally {
4580 Binder.restoreCallingIdentity(ident);
4581 }
4582 }
4583
Calin Tatarua3805722018-08-09 16:41:28 +02004584 @Override // Binder call
4585 public int getLastSleepReason() {
4586 mContext.enforceCallingOrSelfPermission(
4587 android.Manifest.permission.DEVICE_POWER, null);
4588
4589 final long ident = Binder.clearCallingIdentity();
4590 try {
4591 return getLastSleepReasonInternal();
4592 } finally {
4593 Binder.restoreCallingIdentity(ident);
4594 }
4595 }
4596
Salvador Martineza6f7b252017-04-10 10:46:15 -07004597 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004598 * Reboots the device.
4599 *
4600 * @param confirm If true, shows a reboot confirmation dialog.
4601 * @param reason The reason for the reboot, or null if none.
4602 * @param wait If true, this call waits for the reboot to complete and does not return.
4603 */
4604 @Override // Binder call
4605 public void reboot(boolean confirm, String reason, boolean wait) {
4606 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08004607 if (PowerManager.REBOOT_RECOVERY.equals(reason)
4608 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08004609 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
4610 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004611
4612 final long ident = Binder.clearCallingIdentity();
4613 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004614 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
4615 } finally {
4616 Binder.restoreCallingIdentity(ident);
4617 }
4618 }
4619
4620 /**
4621 * Reboots the device into safe mode
4622 *
4623 * @param confirm If true, shows a reboot confirmation dialog.
4624 * @param wait If true, this call waits for the reboot to complete and does not return.
4625 */
4626 @Override // Binder call
4627 public void rebootSafeMode(boolean confirm, boolean wait) {
4628 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4629
4630 final long ident = Binder.clearCallingIdentity();
4631 try {
4632 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
4633 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004634 } finally {
4635 Binder.restoreCallingIdentity(ident);
4636 }
4637 }
4638
4639 /**
4640 * Shuts down the device.
4641 *
4642 * @param confirm If true, shows a shutdown confirmation dialog.
4643 * @param wait If true, this call waits for the shutdown to complete and does not return.
4644 */
4645 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07004646 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004647 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4648
4649 final long ident = Binder.clearCallingIdentity();
4650 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004651 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004652 } finally {
4653 Binder.restoreCallingIdentity(ident);
4654 }
4655 }
4656
4657 /**
4658 * Crash the runtime (causing a complete restart of the Android framework).
4659 * Requires REBOOT permission. Mostly for testing. Should not return.
4660 */
4661 @Override // Binder call
4662 public void crash(String message) {
4663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4664
4665 final long ident = Binder.clearCallingIdentity();
4666 try {
4667 crashInternal(message);
4668 } finally {
4669 Binder.restoreCallingIdentity(ident);
4670 }
4671 }
4672
4673 /**
4674 * Set the setting that determines whether the device stays on when plugged in.
4675 * The argument is a bit string, with each bit specifying a power source that,
4676 * when the device is connected to that source, causes the device to stay on.
4677 * See {@link android.os.BatteryManager} for the list of power sources that
4678 * can be specified. Current values include
4679 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
4680 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
4681 *
4682 * Used by "adb shell svc power stayon ..."
4683 *
4684 * @param val an {@code int} containing the bits that specify which power sources
4685 * should cause the device to stay on.
4686 */
4687 @Override // Binder call
4688 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01004689 int uid = Binder.getCallingUid();
4690 // if uid is of root's, we permit this operation straight away
4691 if (uid != Process.ROOT_UID) {
4692 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
4693 Settings.getPackageNameForUid(mContext, uid), true)) {
4694 return;
4695 }
4696 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004697
4698 final long ident = Binder.clearCallingIdentity();
4699 try {
4700 setStayOnSettingInternal(val);
4701 } finally {
4702 Binder.restoreCallingIdentity(ident);
4703 }
4704 }
4705
4706 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004707 * Used by the phone application to make the attention LED flash when ringing.
4708 */
4709 @Override // Binder call
4710 public void setAttentionLight(boolean on, int color) {
4711 mContext.enforceCallingOrSelfPermission(
4712 android.Manifest.permission.DEVICE_POWER, null);
4713
4714 final long ident = Binder.clearCallingIdentity();
4715 try {
4716 setAttentionLightInternal(on, color);
4717 } finally {
4718 Binder.restoreCallingIdentity(ident);
4719 }
4720 }
4721
4722 @Override // Binder call
Lucas Dupin16cfe452018-02-08 13:14:50 -08004723 public void setDozeAfterScreenOff(boolean on) {
4724 mContext.enforceCallingOrSelfPermission(
4725 android.Manifest.permission.DEVICE_POWER, null);
4726
4727 final long ident = Binder.clearCallingIdentity();
4728 try {
4729 setDozeAfterScreenOffInternal(on);
4730 } finally {
4731 Binder.restoreCallingIdentity(ident);
4732 }
4733 }
4734
4735 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07004736 public void boostScreenBrightness(long eventTime) {
4737 if (eventTime > SystemClock.uptimeMillis()) {
4738 throw new IllegalArgumentException("event time must not be in the future");
4739 }
4740
4741 mContext.enforceCallingOrSelfPermission(
4742 android.Manifest.permission.DEVICE_POWER, null);
4743
4744 final int uid = Binder.getCallingUid();
4745 final long ident = Binder.clearCallingIdentity();
4746 try {
4747 boostScreenBrightnessInternal(eventTime, uid);
4748 } finally {
4749 Binder.restoreCallingIdentity(ident);
4750 }
4751 }
4752
4753 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004754 public boolean isScreenBrightnessBoosted() {
4755 final long ident = Binder.clearCallingIdentity();
4756 try {
4757 return isScreenBrightnessBoostedInternal();
4758 } finally {
4759 Binder.restoreCallingIdentity(ident);
4760 }
4761 }
4762
Santos Cordon12f92eb2019-02-01 21:28:47 +00004763 @Override // binder call
4764 public boolean forceSuspend() {
4765 mContext.enforceCallingOrSelfPermission(
4766 android.Manifest.permission.DEVICE_POWER, null);
4767
4768 final int uid = Binder.getCallingUid();
4769 final long ident = Binder.clearCallingIdentity();
4770 try {
4771 return forceSuspendInternal(uid);
4772 } finally {
4773 Binder.restoreCallingIdentity(ident);
4774 }
4775 }
4776
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004777 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004778 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004779 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown6f357d32014-01-15 20:40:55 -08004780
4781 final long ident = Binder.clearCallingIdentity();
Netta P958d0a52017-02-07 11:20:55 -08004782
4783 boolean isDumpProto = false;
4784 for (String arg : args) {
4785 if (arg.equals("--proto")) {
4786 isDumpProto = true;
4787 }
4788 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004789 try {
Netta P958d0a52017-02-07 11:20:55 -08004790 if (isDumpProto) {
4791 dumpProto(fd);
4792 } else {
4793 dumpInternal(pw);
4794 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004795 } finally {
4796 Binder.restoreCallingIdentity(ident);
4797 }
4798 }
4799 }
4800
Salvador Martineza6f7b252017-04-10 10:46:15 -07004801 @VisibleForTesting
Santos Cordon64a6e612018-08-22 19:27:04 +01004802 BinderService getBinderServiceInstance() {
4803 return mBinderService;
4804 }
4805
4806 @VisibleForTesting
4807 LocalService getLocalServiceInstance() {
4808 return mLocalService;
4809 }
4810
4811 @VisibleForTesting
Mark Salyzyne65c0c62017-08-15 07:53:47 -07004812 // lastRebootReasonProperty argument to permit testing
4813 int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
4814 String line = SystemProperties.get(lastRebootReasonProperty);
Michael Wright9199d0c2017-05-10 21:35:13 +01004815 if (line == null) {
4816 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4817 }
Salvador Martineza6f7b252017-04-10 10:46:15 -07004818 switch (line) {
4819 case REASON_SHUTDOWN:
4820 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
4821 case REASON_REBOOT:
4822 return PowerManager.SHUTDOWN_REASON_REBOOT;
4823 case REASON_USERREQUESTED:
4824 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
4825 case REASON_THERMAL_SHUTDOWN:
4826 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
Sudheer Shanka292637f2017-09-25 10:36:23 -07004827 case REASON_LOW_BATTERY:
4828 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
4829 case REASON_BATTERY_THERMAL_STATE:
4830 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
Salvador Martineza6f7b252017-04-10 10:46:15 -07004831 default:
4832 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4833 }
4834 }
4835
Calin Tatarua3805722018-08-09 16:41:28 +02004836 private int getLastSleepReasonInternal() {
4837 synchronized (mLock) {
4838 return mLastSleepReason;
4839 }
4840 }
4841
Jeff Brown4ccb8232014-01-16 22:16:42 -08004842 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08004843 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004844 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
4845 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4846 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4847 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08004848 }
Jeff Brown970d4132014-07-19 11:33:47 -07004849 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08004850 }
4851
Jeff Brown6f357d32014-01-15 20:40:55 -08004852 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004853 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
4854 switch (screenState) {
4855 case Display.STATE_UNKNOWN:
4856 case Display.STATE_OFF:
4857 case Display.STATE_DOZE:
4858 case Display.STATE_DOZE_SUSPEND:
Chris Phoenix10a4a642017-09-25 13:21:00 -07004859 case Display.STATE_ON_SUSPEND:
Jeff Brown970d4132014-07-19 11:33:47 -07004860 case Display.STATE_ON:
Santos Cordon3107d292016-09-20 15:50:35 -07004861 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07004862 break;
4863 default:
4864 screenState = Display.STATE_UNKNOWN;
4865 break;
4866 }
4867 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4868 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4869 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
4870 }
4871 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
4872 }
4873
Jeff Brown6f357d32014-01-15 20:40:55 -08004874 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07004875 public void setUserInactiveOverrideFromWindowManager() {
4876 setUserInactiveOverrideFromWindowManagerInternal();
4877 }
4878
4879 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08004880 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07004881 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08004882 }
4883
4884 @Override
Ivan Podogov56bc6d02018-02-26 16:04:24 +00004885 public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
4886 setDrawWakeLockOverrideFromSidekickInternal(keepState);
4887 }
4888
4889 @Override
Pavel Grafov28939982017-10-03 15:11:52 +01004890 public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
4891 setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
Jeff Brown5ce1cb22014-11-06 19:05:33 -08004892 }
4893
4894 @Override
jackqdyulei455e90a2017-02-09 15:29:16 -08004895 public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
Kweku Adams9f488e22019-01-14 16:25:08 -08004896 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004897 }
4898
4899 @Override
4900 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
Makoto Onuki66a78122017-11-14 15:03:21 -08004901 mBatterySaverController.addListener(listener);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004902 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004903
4904 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004905 public boolean setDeviceIdleMode(boolean enabled) {
4906 return setDeviceIdleModeInternal(enabled);
4907 }
4908
4909 @Override
4910 public boolean setLightDeviceIdleMode(boolean enabled) {
4911 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004912 }
4913
4914 @Override
4915 public void setDeviceIdleWhitelist(int[] appids) {
4916 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004917 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004918
4919 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07004920 public void setDeviceIdleTempWhitelist(int[] appids) {
4921 setDeviceIdleTempWhitelistInternal(appids);
4922 }
4923
4924 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004925 public void startUidChanges() {
4926 startUidChangesInternal();
4927 }
4928
4929 @Override
4930 public void finishUidChanges() {
4931 finishUidChangesInternal();
4932 }
4933
4934 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004935 public void updateUidProcState(int uid, int procState) {
4936 updateUidProcStateInternal(uid, procState);
4937 }
4938
4939 @Override
4940 public void uidGone(int uid) {
4941 uidGoneInternal(uid);
4942 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01004943
4944 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004945 public void uidActive(int uid) {
4946 uidActiveInternal(uid);
4947 }
4948
4949 @Override
4950 public void uidIdle(int uid) {
4951 uidIdleInternal(uid);
4952 }
4953
4954 @Override
Michael Wrighta4d22d72015-09-16 23:19:26 +01004955 public void powerHint(int hintId, int data) {
4956 powerHintInternal(hintId, data);
4957 }
Alex Kershaw2418ea92018-10-19 17:17:49 +01004958
4959 @Override
4960 public boolean wasDeviceIdleFor(long ms) {
4961 return wasDeviceIdleForInternal(ms);
4962 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964}